from sfa.trust.credential_legacy import CredentialLegacy\r
from sfa.trust.rights import Right, Rights, determine_rights\r
from sfa.trust.gid import GID\r
-from sfa.util.xrn import urn_to_hrn\r
+from sfa.util.xrn import urn_to_hrn, hrn_authfor_hrn\r
\r
# 2 weeks, in seconds \r
DEFAULT_CREDENTIAL_LIFETIME = 86400 * 14\r
# . That the issuer of the credential is the authority in the target's urn\r
# . In the case of a delegated credential, this must be true of the root\r
# . That all of the gids presented in the credential are valid\r
+ # . Including verifying GID chains, and includ the issuer\r
# . The credential is not expired\r
#\r
# -- For Delegates (credentials with parents)\r
cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])\r
\r
# If caller explicitly passed in None that means skip cert chain validation.\r
- # Strange and not typical\r
+ # - Strange and not typical\r
if trusted_certs is not None:\r
# Verify the gids of this cred and of its parents\r
for cur_cred in self.get_credential_list():\r
if self.parent:\r
self.verify_parent(self.parent)\r
\r
- # Make sure the issuer is the target's authority\r
- self.verify_issuer()\r
+ # Make sure the issuer is the target's authority, and is\r
+ # itself a valid GID\r
+ self.verify_issuer(trusted_cert_objects)\r
return True\r
\r
##\r
return list\r
\r
##\r
- # Make sure the credential's target gid was signed by (or is the same) the entity that signed\r
- # the original credential or an authority over that namespace.\r
- def verify_issuer(self): \r
+ # Make sure the credential's target gid (a) was signed by or (b)\r
+ # is the same as the entity that signed the original credential,\r
+ # or (c) is an authority over the target's namespace.\r
+ # Also ensure that the credential issuer / signer itself has a valid\r
+ # GID signature chain (signed by an authority with namespace rights).\r
+ def verify_issuer(self, trusted_gids):\r
root_cred = self.get_credential_list()[-1]\r
root_target_gid = root_cred.get_gid_object()\r
root_cred_signer = root_cred.get_signature().get_issuer_gid()\r
\r
+ # Case 1:\r
+ # Allow non authority to sign target and cred about target.\r
+ #\r
+ # Why do we need to allow non authorities to sign?\r
+ # If in the target gid validation step we correctly\r
+ # checked that the target is only signed by an authority,\r
+ # then this is just a special case of case 3.\r
+ # This short-circuit is the common case currently -\r
+ # and cause GID validation doesn't check 'authority',\r
+ # this allows users to generate valid slice credentials.\r
if root_target_gid.is_signed_by_cert(root_cred_signer):\r
# cred signer matches target signer, return success\r
return\r
\r
- root_target_gid_str = root_target_gid.save_to_string()\r
- root_cred_signer_str = root_cred_signer.save_to_string()\r
- if root_target_gid_str == root_cred_signer_str:\r
- # cred signer is target, return success\r
- return\r
+ # Case 2:\r
+ # Allow someone to sign credential about themeselves. Used?\r
+ # If not, remove this.\r
+ #root_target_gid_str = root_target_gid.save_to_string()\r
+ #root_cred_signer_str = root_cred_signer.save_to_string()\r
+ #if root_target_gid_str == root_cred_signer_str:\r
+ # # cred signer is target, return success\r
+ # return\r
+\r
+ # Case 3:\r
\r
# root_cred_signer is not the target_gid\r
- # So this is a different gid that we have not verified\r
- # Did xmlsec1 verify the cert chain on this already?\r
- # Regardless, it hasn't verified that the gid meets the HRN namespace\r
- # requirements\r
-# FIXME: Uncomment once we verify this is right\r
-# root_cred_signer.verify_chain(trusted_cert_objects)\r
-\r
- # See if it the signer is an authority over the domain of the target\r
+ # So this is a different gid that we have not verified.\r
+ # xmlsec1 verified the cert chain on this already, but\r
+ # it hasn't verified that the gid meets the HRN namespace\r
+ # requirements.\r
+ # Below we'll ensure that it is an authority.\r
+ # But we haven't verified that it is _signed by_ an authority\r
+ # We also don't know if xmlsec1 requires that cert signers\r
+ # are marked as CAs.\r
+ root_cred_signer.verify_chain(trusted_gids)\r
+\r
+ # See if the signer is an authority over the domain of the target.\r
+ # There are multiple types of authority - accept them all here\r
# Maybe should be (hrn, type) = urn_to_hrn(root_cred_signer.get_urn())\r
root_cred_signer_type = root_cred_signer.get_type()\r
- if (root_cred_signer_type == 'authority'):\r
+ if (root_cred_signer_type.find('authority') == 0):\r
#logger.debug('Cred signer is an authority')\r
# signer is an authority, see if target is in authority's domain\r
- hrn = root_cred_signer.get_hrn()\r
- if root_target_gid.get_hrn().startswith(hrn):\r
+ signerhrn = root_cred_signer.get_hrn()\r
+ if hrn_authfor_hrn(signerhrn, root_target_gid.get_hrn()):\r
return\r
\r
# We've required that the credential be signed by an authority\r
-#----------------------------------------------------------------------
-# Copyright (c) 2008 Board of Trustees, Princeton University
-#
-# Permission is hereby granted, free of charge, to any person obtaining
-# a copy of this software and/or hardware specification (the "Work") to
-# deal in the Work without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense,
-# and/or sell copies of the Work, and to permit persons to whom the Work
-# is furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be
-# included in all copies or substantial portions of the Work.
-#
-# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
-# IN THE WORK.
-#----------------------------------------------------------------------
-##
-# Implements SFA GID. GIDs are based on certificates, and the GID class is a
-# descendant of the certificate class.
-##
-
-import xmlrpclib
-import uuid
-
-from sfa.util.sfalogging import logger
-from sfa.trust.certificate import Certificate
-from sfa.util.xrn import hrn_to_urn, urn_to_hrn
-
-##
-# Create a new uuid. Returns the UUID as a string.
-
-def create_uuid():
- return str(uuid.uuid4().int)
-
-##
-# GID is a tuple:
-# (uuid, urn, public_key)
-#
-# UUID is a unique identifier and is created by the python uuid module
-# (or the utility function create_uuid() in gid.py).
-#
-# HRN is a human readable name. It is a dotted form similar to a backward domain
-# name. For example, planetlab.us.arizona.bakers.
-#
-# URN is a human readable identifier of form:
-# "urn:publicid:IDN+toplevelauthority[:sub-auth.]*[\res. type]\ +object name"
-# For example, urn:publicid:IDN+planetlab:us:arizona+user+bakers
-#
-# PUBLIC_KEY is the public key of the principal identified by the UUID/HRN.
-# It is a Keypair object as defined in the cert.py module.
-#
-# It is expected that there is a one-to-one pairing between UUIDs and HRN,
-# but it is uncertain how this would be inforced or if it needs to be enforced.
-#
-# These fields are encoded using xmlrpc into the subjectAltName field of the
-# x509 certificate. Note: Call encode() once the fields have been filled in
-# to perform this encoding.
-
-
-class GID(Certificate):
- uuid = None
- hrn = None
- urn = None
-
- ##
- # Create a new GID object
- #
- # @param create If true, create the X509 certificate
- # @param subject If subject!=None, create the X509 cert and set the subject name
- # @param string If string!=None, load the GID from a string
- # @param filename If filename!=None, load the GID from a file
-
- def __init__(self, create=False, subject=None, string=None, filename=None, uuid=None, hrn=None, urn=None):
-
- Certificate.__init__(self, create, subject, string, filename)
- if subject:
- logger.debug("Creating GID for subject: %s" % subject)
- if uuid:
- self.uuid = int(uuid)
- if hrn:
- self.hrn = hrn
- self.urn = hrn_to_urn(hrn, 'unknown')
- if urn:
- self.urn = urn
- self.hrn, type = urn_to_hrn(urn)
-
- def set_uuid(self, uuid):
- if isinstance(uuid, str):
- self.uuid = int(uuid)
- else:
- self.uuid = uuid
-
- def get_uuid(self):
- if not self.uuid:
- self.decode()
- return self.uuid
-
- def set_hrn(self, hrn):
- self.hrn = hrn
-
- def get_hrn(self):
- if not self.hrn:
- self.decode()
- return self.hrn
-
- def set_urn(self, urn):
- self.urn = urn
- self.hrn, type = urn_to_hrn(urn)
-
- def get_urn(self):
- if not self.urn:
- self.decode()
- return self.urn
-
- def get_type(self):
- if not self.urn:
- self.decode()
- _, t = urn_to_hrn(self.urn)
- return t
-
- ##
- # Encode the GID fields and package them into the subject-alt-name field
- # of the X509 certificate. This must be called prior to signing the
- # certificate. It may only be called once per certificate.
-
- def encode(self):
- if self.urn:
- urn = self.urn
- else:
- urn = hrn_to_urn(self.hrn, None)
-
- str = "URI:" + urn
-
- if self.uuid:
- str += ", " + "URI:" + uuid.UUID(int=self.uuid).urn
-
- self.set_data(str, 'subjectAltName')
-
-
-
-
- ##
- # Decode the subject-alt-name field of the X509 certificate into the
- # fields of the GID. This is automatically called by the various get_*()
- # functions in this class.
-
- def decode(self):
- data = self.get_data('subjectAltName')
- dict = {}
- if data:
- if data.lower().startswith('uri:http://<params>'):
- dict = xmlrpclib.loads(data[11:])[0][0]
- else:
- spl = data.split(', ')
- for val in spl:
- if val.lower().startswith('uri:urn:uuid:'):
- dict['uuid'] = uuid.UUID(val[4:]).int
- elif val.lower().startswith('uri:urn:publicid:idn+'):
- dict['urn'] = val[4:]
-
- self.uuid = dict.get("uuid", None)
- self.urn = dict.get("urn", None)
- self.hrn = dict.get("hrn", None)
- if self.urn:
- self.hrn = urn_to_hrn(self.urn)[0]
-
- ##
- # Dump the credential to stdout.
- #
- # @param indent specifies a number of spaces to indent the output
- # @param dump_parents If true, also dump the parents of the GID
-
- def dump(self, *args, **kwargs):
- print self.dump_string(*args,**kwargs)
-
- def dump_string(self, indent=0, dump_parents=False):
- result=" "*(indent-2) + "GID\n"
- result += " "*indent + "hrn:" + str(self.get_hrn()) +"\n"
- result += " "*indent + "urn:" + str(self.get_urn()) +"\n"
- result += " "*indent + "uuid:" + str(self.get_uuid()) + "\n"
- filename=self.get_filename()
- if filename: result += "Filename %s\n"%filename
-
- if self.parent and dump_parents:
- result += " "*indent + "parent:\n"
- result += self.parent.dump_string(indent+4, dump_parents)
- return result
-
- ##
- # Verify the chain of authenticity of the GID. First perform the checks
- # of the certificate class (verifying that each parent signs the child,
- # etc). In addition, GIDs also confirm that the parent's HRN is a prefix
- # of the child's HRN.
- #
- # Verifying these prefixes prevents a rogue authority from signing a GID
- # for a principal that is not a member of that authority. For example,
- # planetlab.us.arizona cannot sign a GID for planetlab.us.princeton.foo.
-
- def verify_chain(self, trusted_certs = None):
- # do the normal certificate verification stuff
- trusted_root = Certificate.verify_chain(self, trusted_certs)
-
- if self.parent:
- # make sure the parent's hrn is a prefix of the child's hrn
- if not self.get_hrn().startswith(self.parent.get_hrn()):
- raise GidParentHrn("This cert HRN %s doesnt start with parent HRN %s" % (self.get_hrn(), self.parent.get_hrn()))
- else:
- # make sure that the trusted root's hrn is a prefix of the child's
- trusted_gid = GID(string=trusted_root.save_to_string())
- trusted_type = trusted_gid.get_type()
- trusted_hrn = trusted_gid.get_hrn()
- #if trusted_type == 'authority':
- # trusted_hrn = trusted_hrn[:trusted_hrn.rindex('.')]
- cur_hrn = self.get_hrn()
- if not self.get_hrn().startswith(trusted_hrn):
- raise GidParentHrn("Trusted roots HRN %s isnt start of this cert %s" % (trusted_hrn, cur_hrn))
-
- return
+#----------------------------------------------------------------------\r
+# Copyright (c) 2008 Board of Trustees, Princeton University\r
+#\r
+# Permission is hereby granted, free of charge, to any person obtaining\r
+# a copy of this software and/or hardware specification (the "Work") to\r
+# deal in the Work without restriction, including without limitation the\r
+# rights to use, copy, modify, merge, publish, distribute, sublicense,\r
+# and/or sell copies of the Work, and to permit persons to whom the Work\r
+# is furnished to do so, subject to the following conditions:\r
+#\r
+# The above copyright notice and this permission notice shall be\r
+# included in all copies or substantial portions of the Work.\r
+#\r
+# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS \r
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \r
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \r
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT \r
+# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \r
+# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \r
+# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS \r
+# IN THE WORK.\r
+#----------------------------------------------------------------------\r
+##\r
+# Implements SFA GID. GIDs are based on certificates, and the GID class is a\r
+# descendant of the certificate class.\r
+##\r
+\r
+import xmlrpclib\r
+import uuid\r
+\r
+from sfa.trust.certificate import Certificate\r
+\r
+from sfa.util.faults import *\r
+from sfa.util.sfalogging import logger\r
+from sfa.util.xrn import hrn_to_urn, urn_to_hrn, hrn_authfor_hrn\r
+\r
+##\r
+# Create a new uuid. Returns the UUID as a string.\r
+\r
+def create_uuid():\r
+ return str(uuid.uuid4().int)\r
+\r
+##\r
+# GID is a tuple:\r
+# (uuid, urn, public_key)\r
+#\r
+# UUID is a unique identifier and is created by the python uuid module\r
+# (or the utility function create_uuid() in gid.py).\r
+#\r
+# HRN is a human readable name. It is a dotted form similar to a backward domain\r
+# name. For example, planetlab.us.arizona.bakers.\r
+#\r
+# URN is a human readable identifier of form:\r
+# "urn:publicid:IDN+toplevelauthority[:sub-auth.]*[\res. type]\ +object name"\r
+# For example, urn:publicid:IDN+planetlab:us:arizona+user+bakers \r
+#\r
+# PUBLIC_KEY is the public key of the principal identified by the UUID/HRN.\r
+# It is a Keypair object as defined in the cert.py module.\r
+#\r
+# It is expected that there is a one-to-one pairing between UUIDs and HRN,\r
+# but it is uncertain how this would be inforced or if it needs to be enforced.\r
+#\r
+# These fields are encoded using xmlrpc into the subjectAltName field of the\r
+# x509 certificate. Note: Call encode() once the fields have been filled in\r
+# to perform this encoding.\r
+\r
+\r
+class GID(Certificate):\r
+ uuid = None\r
+ hrn = None\r
+ urn = None\r
+\r
+ ##\r
+ # Create a new GID object\r
+ #\r
+ # @param create If true, create the X509 certificate\r
+ # @param subject If subject!=None, create the X509 cert and set the subject name\r
+ # @param string If string!=None, load the GID from a string\r
+ # @param filename If filename!=None, load the GID from a file\r
+ # @param lifeDays life of GID in days - default is 1825==5 years\r
+\r
+ def __init__(self, create=False, subject=None, string=None, filename=None, uuid=None, hrn=None, urn=None, lifeDays=1825):\r
+ \r
+ #Certificate.__init__(self, lifeDays, create, subject, string, filename)\r
+ Certificate.__init__(self, create, subject, string, filename)\r
+ if subject:\r
+ logger.debug("Creating GID for subject: %s" % subject)\r
+ if uuid:\r
+ self.uuid = int(uuid)\r
+ if hrn:\r
+ self.hrn = hrn\r
+ self.urn = hrn_to_urn(hrn, 'unknown')\r
+ if urn:\r
+ self.urn = urn\r
+ self.hrn, type = urn_to_hrn(urn)\r
+\r
+ def set_uuid(self, uuid):\r
+ if isinstance(uuid, str):\r
+ self.uuid = int(uuid)\r
+ else:\r
+ self.uuid = uuid\r
+\r
+ def get_uuid(self):\r
+ if not self.uuid:\r
+ self.decode()\r
+ return self.uuid\r
+\r
+ def set_hrn(self, hrn):\r
+ self.hrn = hrn\r
+\r
+ def get_hrn(self):\r
+ if not self.hrn:\r
+ self.decode()\r
+ return self.hrn\r
+\r
+ def set_urn(self, urn):\r
+ self.urn = urn\r
+ self.hrn, type = urn_to_hrn(urn)\r
+ \r
+ def get_urn(self):\r
+ if not self.urn:\r
+ self.decode()\r
+ return self.urn \r
+\r
+ def get_type(self):\r
+ if not self.urn:\r
+ self.decode()\r
+ _, t = urn_to_hrn(self.urn)\r
+ return t\r
+ \r
+ ##\r
+ # Encode the GID fields and package them into the subject-alt-name field\r
+ # of the X509 certificate. This must be called prior to signing the\r
+ # certificate. It may only be called once per certificate.\r
+\r
+ def encode(self):\r
+ if self.urn:\r
+ urn = self.urn\r
+ else:\r
+ urn = hrn_to_urn(self.hrn, None)\r
+ \r
+ str = "URI:" + urn\r
+\r
+ if self.uuid:\r
+ str += ", " + "URI:" + uuid.UUID(int=self.uuid).urn\r
+ \r
+ self.set_data(str, 'subjectAltName')\r
+\r
+ \r
+\r
+\r
+ ##\r
+ # Decode the subject-alt-name field of the X509 certificate into the\r
+ # fields of the GID. This is automatically called by the various get_*()\r
+ # functions in this class.\r
+\r
+ def decode(self):\r
+ data = self.get_data('subjectAltName')\r
+ dict = {}\r
+ if data:\r
+ if data.lower().startswith('uri:http://<params>'):\r
+ dict = xmlrpclib.loads(data[11:])[0][0]\r
+ else:\r
+ spl = data.split(', ')\r
+ for val in spl:\r
+ if val.lower().startswith('uri:urn:uuid:'):\r
+ dict['uuid'] = uuid.UUID(val[4:]).int\r
+ elif val.lower().startswith('uri:urn:publicid:idn+'):\r
+ dict['urn'] = val[4:]\r
+ \r
+ self.uuid = dict.get("uuid", None)\r
+ self.urn = dict.get("urn", None)\r
+ self.hrn = dict.get("hrn", None) \r
+ if self.urn:\r
+ self.hrn = urn_to_hrn(self.urn)[0]\r
+\r
+ ##\r
+ # Dump the credential to stdout.\r
+ #\r
+ # @param indent specifies a number of spaces to indent the output\r
+ # @param dump_parents If true, also dump the parents of the GID\r
+\r
+ def dump(self, *args, **kwargs):\r
+ print self.dump_string(*args,**kwargs)\r
+\r
+ def dump_string(self, indent=0, dump_parents=False):\r
+ result=" "*(indent-2) + "GID\n"\r
+ result += " "*indent + "hrn:" + str(self.get_hrn()) +"\n"\r
+ result += " "*indent + "urn:" + str(self.get_urn()) +"\n"\r
+ result += " "*indent + "uuid:" + str(self.get_uuid()) + "\n"\r
+ filename=self.get_filename()\r
+ if filename: result += "Filename %s\n"%filename\r
+\r
+ if self.parent and dump_parents:\r
+ result += " "*indent + "parent:\n"\r
+ result += self.parent.dump_string(indent+4, dump_parents)\r
+ return result\r
+\r
+ ##\r
+ # Verify the chain of authenticity of the GID. First perform the checks\r
+ # of the certificate class (verifying that each parent signs the child,\r
+ # etc). In addition, GIDs also confirm that the parent's HRN is a prefix\r
+ # of the child's HRN, and the parent is of type 'authority'.\r
+ #\r
+ # Verifying these prefixes prevents a rogue authority from signing a GID\r
+ # for a principal that is not a member of that authority. For example,\r
+ # planetlab.us.arizona cannot sign a GID for planetlab.us.princeton.foo.\r
+\r
+ def verify_chain(self, trusted_certs = None):\r
+ # do the normal certificate verification stuff\r
+ trusted_root = Certificate.verify_chain(self, trusted_certs) \r
+ \r
+ if self.parent:\r
+ # make sure the parent's hrn is a prefix of the child's hrn\r
+ if not hrn_authfor_hrn(self.parent.get_hrn(), self.get_hrn()):\r
+ raise GidParentHrn("This cert HRN %s isn't in the namespace for parent HRN %s" % (self.get_hrn(), self.parent.get_hrn()))\r
+\r
+ # Parent must also be an authority (of some type) to sign a GID\r
+ # There are multiple types of authority - accept them all here\r
+ if not self.parent.get_type().find('authority') == 0:\r
+ raise GidInvalidParentHrn("This cert %s's parent %s is not an authority (is a %s)" % (self.get_hrn(), self.parent.get_hrn(), self.parent.get_type()))\r
+\r
+ # Then recurse up the chain - ensure the parent is a trusted\r
+ # root or is in the namespace of a trusted root\r
+ self.parent.verify_chain(trusted_certs)\r
+ else:\r
+ # make sure that the trusted root's hrn is a prefix of the child's\r
+ trusted_gid = GID(string=trusted_root.save_to_string())\r
+ trusted_type = trusted_gid.get_type()\r
+ trusted_hrn = trusted_gid.get_hrn()\r
+ #if trusted_type == 'authority':\r
+ # trusted_hrn = trusted_hrn[:trusted_hrn.rindex('.')]\r
+ cur_hrn = self.get_hrn()\r
+ if not hrn_authfor_hrn(trusted_hrn, cur_hrn):\r
+ raise GidParentHrn("Trusted root with HRN %s isn't a namespace authority for this cert %s" % (trusted_hrn, cur_hrn))\r
+\r
+ # There are multiple types of authority - accept them all here\r
+ if not trusted_type.find('authority') == 0:\r
+ raise GidInvalidParentHrn("This cert %s's trusted root signer %s is not an authority (is a %s)" % (self.get_hrn(), trusted_hrn, trusted_type))\r
+\r
+ return\r
-import re
-
-from sfa.util.faults import *
-
-# for convenience and smoother translation - we should get rid of these functions eventually
-def get_leaf(hrn): return Xrn(hrn).get_leaf()
-def get_authority(hrn): return Xrn(hrn).get_authority_hrn()
-def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type)
-def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn
-
-def urn_to_sliver_id(urn, slice_id, node_id, index=0):
- urn = urn.replace('+slice+', '+sliver+')
- return ":".join([urn, str(slice_id), str(node_id), str(index)])
-
-class Xrn:
-
- ########## basic tools on HRNs
- # split a HRN-like string into pieces
- # this is like split('.') except for escaped (backslashed) dots
- # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']
- @staticmethod
- def hrn_split(hrn):
- return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ]
-
- # e.g. hrn_leaf ('a\.b.c.d') -> 'd'
- @staticmethod
- def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1]
-
- # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']
- @staticmethod
- def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1]
-
- # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'
- @staticmethod
- def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn))
-
- # e.g. escape ('a.b') -> 'a\.b'
- @staticmethod
- def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token)
- # e.g. unescape ('a\.b') -> 'a.b'
- @staticmethod
- def unescape(token): return token.replace('\\.','.')
-
- URN_PREFIX = "urn:publicid:IDN"
-
- ########## basic tools on URNs
- @staticmethod
- def urn_full (urn):
- if urn.startswith(Xrn.URN_PREFIX): return urn
- else: return Xrn.URN_PREFIX+URN
- @staticmethod
- def urn_meaningful (urn):
- if urn.startswith(Xrn.URN_PREFIX): return urn[len(Xrn.URN_PREFIX):]
- else: return urn
- @staticmethod
- def urn_split (urn):
- return Xrn.urn_meaningful(urn).split('+')
-
- ####################
- # the local fields that are kept consistent
- # self.urn
- # self.hrn
- # self.type
- # self.path
- # provide either urn, or (hrn + type)
- def __init__ (self, xrn, type=None):
- if not xrn: xrn = ""
- # user has specified xrn : guess if urn or hrn
- if xrn.startswith(Xrn.URN_PREFIX):
- self.hrn=None
- self.urn=xrn
- self.urn_to_hrn()
- else:
- self.urn=None
- self.hrn=xrn
- self.type=type
- self.hrn_to_urn()
-# happens all the time ..
-# if not type:
-# debug_logger.debug("type-less Xrn's are not safe")
-
- def get_urn(self): return self.urn
- def get_hrn(self): return self.hrn
- def get_type(self): return self.type
- def get_hrn_type(self): return (self.hrn, self.type)
-
- def _normalize(self):
- if self.hrn is None: raise SfaAPIError, "Xrn._normalize"
- if not hasattr(self,'leaf'):
- self.leaf=Xrn.hrn_split(self.hrn)[-1]
- # self.authority keeps a list
- if not hasattr(self,'authority'):
- self.authority=Xrn.hrn_auth_list(self.hrn)
-
- def get_leaf(self):
- self._normalize()
- return self.leaf
-
- def get_authority_hrn(self):
- self._normalize()
- return '.'.join( self.authority )
-
- def get_authority_urn(self):
- self._normalize()
- return ':'.join( [Xrn.unescape(x) for x in self.authority] )
-
- def urn_to_hrn(self):
- """
- compute tuple (hrn, type) from urn
- """
-
-# if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):
- if not self.urn.startswith(Xrn.URN_PREFIX):
- raise SfaAPIError, "Xrn.urn_to_hrn"
-
- parts = Xrn.urn_split(self.urn)
- type=parts.pop(2)
- # Remove the authority name (e.g. '.sa')
- if type == 'authority':
- name = parts.pop()
- # Drop the sa. This is a bad hack, but its either this
- # or completely change how record types are generated/stored
- if name != 'sa':
- type = type + "+" + name
-
- # convert parts (list) into hrn (str) by doing the following
- # 1. remove blank parts
- # 2. escape dots inside parts
- # 3. replace ':' with '.' inside parts
- # 3. join parts using '.'
- hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part])
-
- self.hrn=str(hrn)
- self.type=str(type)
-
- def hrn_to_urn(self):
- """
- compute urn from (hrn, type)
- """
-
-# if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):
- if self.hrn.startswith(Xrn.URN_PREFIX):
- raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn
-
- if self.type and self.type.startswith('authority'):
- self.authority = Xrn.hrn_split(self.hrn)
- type_parts = self.type.split("+")
- self.type = type_parts[0]
- name = 'sa'
- if len(type_parts) > 1:
- name = type_parts[1]
- else:
- self.authority = Xrn.hrn_auth_list(self.hrn)
- name = Xrn.hrn_leaf(self.hrn)
-
- authority_string = self.get_authority_urn()
-
- if self.type == None:
- urn = "+".join(['',authority_string,Xrn.unescape(name)])
- else:
- urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)])
-
- self.urn = Xrn.URN_PREFIX + urn
-
- def dump_string(self):
- result="-------------------- XRN\n"
- result += "URN=%s\n"%self.urn
- result += "HRN=%s\n"%self.hrn
- result += "TYPE=%s\n"%self.type
- result += "LEAF=%s\n"%self.get_leaf()
- result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()
- result += "AUTH(urn format)=%s\n"%self.get_authority_urn()
- return result
-
+#----------------------------------------------------------------------\r
+# Copyright (c) 2008 Board of Trustees, Princeton University\r
+#\r
+# Permission is hereby granted, free of charge, to any person obtaining\r
+# a copy of this software and/or hardware specification (the "Work") to\r
+# deal in the Work without restriction, including without limitation the\r
+# rights to use, copy, modify, merge, publish, distribute, sublicense,\r
+# and/or sell copies of the Work, and to permit persons to whom the Work\r
+# is furnished to do so, subject to the following conditions:\r
+#\r
+# The above copyright notice and this permission notice shall be\r
+# included in all copies or substantial portions of the Work.\r
+#\r
+# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS \r
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \r
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \r
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT \r
+# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \r
+# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \r
+# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS \r
+# IN THE WORK.\r
+#----------------------------------------------------------------------\r
+\r
+import re\r
+\r
+from sfa.util.faults import *\r
+\r
+# for convenience and smoother translation - we should get rid of these functions eventually \r
+def get_leaf(hrn): return Xrn(hrn).get_leaf()\r
+def get_authority(hrn): return Xrn(hrn).get_authority_hrn()\r
+def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type)\r
+def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn\r
+def hrn_authfor_hrn(parenthrn, hrn): return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn)\r
+\r
+class Xrn:\r
+\r
+ ########## basic tools on HRNs\r
+ # split a HRN-like string into pieces\r
+ # this is like split('.') except for escaped (backslashed) dots\r
+ # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']\r
+ @staticmethod\r
+ def hrn_split(hrn):\r
+ return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ]\r
+\r
+ # e.g. hrn_leaf ('a\.b.c.d') -> 'd'\r
+ @staticmethod\r
+ def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1]\r
+\r
+ # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']\r
+ @staticmethod\r
+ def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1]\r
+ \r
+ # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'\r
+ @staticmethod\r
+ def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn))\r
+ \r
+ # e.g. escape ('a.b') -> 'a\.b'\r
+ @staticmethod\r
+ def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token)\r
+\r
+ # e.g. unescape ('a\.b') -> 'a.b'\r
+ @staticmethod\r
+ def unescape(token): return token.replace('\\.','.')\r
+\r
+ # Return the HRN authority chain from top to bottom.\r
+ # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c']\r
+ @staticmethod\r
+ def hrn_auth_chain(hrn):\r
+ parts = Xrn.hrn_auth_list(hrn)\r
+ chain = []\r
+ for i in range(len(parts)):\r
+ chain.append('.'.join(parts[:i+1]))\r
+ # Include the HRN itself?\r
+ #chain.append(hrn)\r
+ return chain\r
+\r
+ # Is the given HRN a true authority over the namespace of the other\r
+ # child HRN?\r
+ # A better alternative than childHRN.startswith(parentHRN)\r
+ # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True,\r
+ # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False\r
+ # Also hrn_is_uauth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True\r
+ @staticmethod\r
+ def hrn_is_auth_for_hrn(parenthrn, hrn):\r
+ if parenthrn == hrn:\r
+ return True\r
+ for auth in Xrn.hrn_auth_chain(hrn):\r
+ if parenthrn == auth:\r
+ return True\r
+ return False\r
+\r
+ URN_PREFIX = "urn:publicid:IDN"\r
+\r
+ ########## basic tools on URNs\r
+ @staticmethod\r
+ def urn_full (urn):\r
+ if urn.startswith(Xrn.URN_PREFIX): return urn\r
+ else: return Xrn.URN_PREFIX+URN\r
+ @staticmethod\r
+ def urn_meaningful (urn):\r
+ if urn.startswith(Xrn.URN_PREFIX): return urn[len(Xrn.URN_PREFIX):]\r
+ else: return urn\r
+ @staticmethod\r
+ def urn_split (urn):\r
+ return Xrn.urn_meaningful(urn).split('+')\r
+\r
+ ####################\r
+ # the local fields that are kept consistent\r
+ # self.urn\r
+ # self.hrn\r
+ # self.type\r
+ # self.path\r
+ # provide either urn, or (hrn + type)\r
+ def __init__ (self, xrn, type=None):\r
+ if not xrn: xrn = ""\r
+ # user has specified xrn : guess if urn or hrn\r
+ if xrn.startswith(Xrn.URN_PREFIX):\r
+ self.hrn=None\r
+ self.urn=xrn\r
+ self.urn_to_hrn()\r
+ else:\r
+ self.urn=None\r
+ self.hrn=xrn\r
+ self.type=type\r
+ self.hrn_to_urn()\r
+# happens all the time ..\r
+# if not type:\r
+# debug_logger.debug("type-less Xrn's are not safe")\r
+\r
+ def get_urn(self): return self.urn\r
+ def get_hrn(self): return self.hrn\r
+ def get_type(self): return self.type\r
+ def get_hrn_type(self): return (self.hrn, self.type)\r
+\r
+ def _normalize(self):\r
+ if self.hrn is None: raise SfaAPIError, "Xrn._normalize"\r
+ if not hasattr(self,'leaf'): \r
+ self.leaf=Xrn.hrn_split(self.hrn)[-1]\r
+ # self.authority keeps a list\r
+ if not hasattr(self,'authority'): \r
+ self.authority=Xrn.hrn_auth_list(self.hrn)\r
+\r
+ def get_leaf(self):\r
+ self._normalize()\r
+ return self.leaf\r
+\r
+ def get_authority_hrn(self): \r
+ self._normalize()\r
+ return '.'.join( self.authority )\r
+ \r
+ def get_authority_urn(self): \r
+ self._normalize()\r
+ return ':'.join( [Xrn.unescape(x) for x in self.authority] )\r
+ \r
+ def urn_to_hrn(self):\r
+ """\r
+ compute tuple (hrn, type) from urn\r
+ """\r
+ \r
+# if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):\r
+ if not self.urn.startswith(Xrn.URN_PREFIX):\r
+ raise SfaAPIError, "Xrn.urn_to_hrn"\r
+\r
+ parts = Xrn.urn_split(self.urn)\r
+ type=parts.pop(2)\r
+ # Remove the authority name (e.g. '.sa')\r
+ if type == 'authority':\r
+ name = parts.pop()\r
+ # Drop the sa. This is a bad hack, but its either this\r
+ # or completely change how record types are generated/stored \r
+ if name != 'sa':\r
+ type = type + "+" + name\r
+\r
+ # convert parts (list) into hrn (str) by doing the following\r
+ # 1. remove blank parts\r
+ # 2. escape dots inside parts\r
+ # 3. replace ':' with '.' inside parts\r
+ # 3. join parts using '.' \r
+ hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part]) \r
+\r
+ self.hrn=str(hrn)\r
+ self.type=str(type)\r
+ \r
+ def hrn_to_urn(self):\r
+ """\r
+ compute urn from (hrn, type)\r
+ """\r
+\r
+# if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):\r
+ if self.hrn.startswith(Xrn.URN_PREFIX):\r
+ raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn\r
+\r
+ if self.type and self.type.startswith('authority'):\r
+ self.authority = Xrn.hrn_split(self.hrn)\r
+ type_parts = self.type.split("+")\r
+ self.type = type_parts[0]\r
+ name = 'sa'\r
+ if len(type_parts) > 1:\r
+ name = type_parts[1]\r
+ else:\r
+ self.authority = Xrn.hrn_auth_list(self.hrn)\r
+ name = Xrn.hrn_leaf(self.hrn)\r
+\r
+ authority_string = self.get_authority_urn()\r
+\r
+ if self.type == None:\r
+ urn = "+".join(['',authority_string,Xrn.unescape(name)])\r
+ else:\r
+ urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)])\r
+ \r
+ self.urn = Xrn.URN_PREFIX + urn\r
+\r
+ def dump_string(self):\r
+ result="-------------------- XRN\n"\r
+ result += "URN=%s\n"%self.urn\r
+ result += "HRN=%s\n"%self.hrn\r
+ result += "TYPE=%s\n"%self.type\r
+ result += "LEAF=%s\n"%self.get_leaf()\r
+ result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()\r
+ result += "AUTH(urn format)=%s\n"%self.get_authority_urn()\r
+ return result\r
+ \r