fix speaks for auth
[sfa.git] / sfa / trust / credential.py
index 2fd3e92..070b71b 100644 (file)
 # Credentials are signed XML files that assign a subject gid privileges to an object gid\r
 ##\r
 \r
-### $Id$\r
-### $URL$\r
-\r
 import os\r
+from types import StringTypes\r
 import datetime\r
+from StringIO import StringIO\r
 from tempfile import mkstemp\r
 from xml.dom.minidom import Document, parseString\r
-from lxml import etree\r
-from dateutil.parser import parse\r
-from StringIO import StringIO\r
 \r
-from sfa.util.faults import *\r
+HAVELXML = False\r
+try:\r
+    from lxml import etree\r
+    HAVELXML = True\r
+except:\r
+    pass\r
+\r
+from xml.parsers.expat import ExpatError\r
+\r
+from sfa.util.faults import CredentialNotVerifiable, ChildRightsNotSubsetOfParent\r
 from sfa.util.sfalogging import logger\r
-from sfa.trust.certificate import Keypair\r
+from sfa.util.sfatime import utcparse\r
 from sfa.trust.credential_legacy import CredentialLegacy\r
-from sfa.trust.rights import Right, Rights\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
+DEFAULT_CREDENTIAL_LIFETIME = 86400 * 31\r
 \r
 \r
 # TODO:\r
@@ -176,13 +181,37 @@ class Signature(object):
         self.gid = gid\r
 \r
     def decode(self):\r
-        doc = parseString(self.xml)\r
+        try:\r
+            doc = parseString(self.xml)\r
+        except ExpatError,e:\r
+            logger.log_exc ("Failed to parse credential, %s"%self.xml)\r
+            raise\r
         sig = doc.getElementsByTagName("Signature")[0]\r
-        self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))\r
-        keyinfo = sig.getElementsByTagName("X509Data")[0]\r
-        szgid = getTextNode(keyinfo, "X509Certificate")\r
-        szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid\r
-        self.set_issuer_gid(GID(string=szgid))        \r
+        ref_id = sig.getAttribute("xml:id").strip().strip("Sig_")\r
+        # The xml:id tag is optional, and could be in a \r
+        # Reference xml:id or Reference UID sub element instead\r
+        if not ref_id or ref_id == '':\r
+            reference = sig.getElementsByTagName('Reference')[0]\r
+            ref_id = reference.getAttribute('xml:id').strip().strip('Sig_')\r
+            if not ref_id or ref_id == '':\r
+                ref_id = reference.getAttribute('URI').strip().strip('#')\r
+        self.set_refid(ref_id)\r
+        keyinfos = sig.getElementsByTagName("X509Data")\r
+        gids = None\r
+        for keyinfo in keyinfos:\r
+            certs = keyinfo.getElementsByTagName("X509Certificate")\r
+            for cert in certs:\r
+                if len(cert.childNodes) > 0:\r
+                    szgid = cert.childNodes[0].nodeValue\r
+                    szgid = szgid.strip()\r
+                    szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid\r
+                    if gids is None:\r
+                        gids = szgid\r
+                    else:\r
+                        gids += "\n" + szgid\r
+        if gids is None:\r
+            raise CredentialNotVerifiable("Malformed XML: No certificate found in signature")\r
+        self.set_issuer_gid(GID(string=gids))\r
         \r
     def encode(self):\r
         self.xml = signature_template % (self.get_refid(), self.get_refid())\r
@@ -201,23 +230,29 @@ class Signature(object):
 # not be changed else the signature is no longer valid.  So, once\r
 # you have loaded an existing signed credential, do not call encode() or sign() on it.\r
 \r
-def filter_creds_by_caller(creds, caller_hrn):\r
+def filter_creds_by_caller(creds, caller_hrn_list):\r
         """\r
         Returns a list of creds who's gid caller matches the\r
         specified caller hrn\r
         """\r
         if not isinstance(creds, list): creds = [creds]\r
+        if not isinstance(caller_hrn_list, list): \r
+            caller_hrn_list = [caller_hrn_list]\r
         caller_creds = []\r
         for cred in creds:\r
             try:\r
                 tmp_cred = Credential(string=cred)\r
-                if tmp_cred.get_gid_caller().get_hrn() == caller_hrn:\r
+                if tmp_cred.get_cred_type() != Credential.SFA_CREDENTIAL_TYPE:\r
+                    continue\r
+                if tmp_cred.get_gid_caller().get_hrn() in caller_hrn_list:\r
                     caller_creds.append(cred)\r
             except: pass\r
         return caller_creds\r
 \r
 class Credential(object):\r
 \r
+    SFA_CREDENTIAL_TYPE = "geni_sfa"\r
+\r
     ##\r
     # Create a Credential object\r
     #\r
@@ -239,6 +274,7 @@ class Credential(object):
         self.xml = None\r
         self.refid = None\r
         self.legacy = None\r
+        self.cred_type = Credential.SFA_CREDENTIAL_TYPE\r
 \r
         # Check if this is a legacy credential, translate it if so\r
         if string or filename:\r
@@ -261,11 +297,26 @@ class Credential(object):
             if os.path.isfile(path + '/' + 'xmlsec1'):\r
                 self.xmlsec_path = path + '/' + 'xmlsec1'\r
                 break\r
+        if not self.xmlsec_path:\r
+            logger.warn("Could not locate binary for xmlsec1 - SFA will be unable to sign stuff !!")\r
+\r
+    def get_cred_type(self): \r
+        return self.cred_type\r
 \r
     def get_subject(self):\r
         if not self.gidObject:\r
             self.decode()\r
-        return self.gidObject.get_subject()   \r
+        return self.gidObject.get_subject()\r
+\r
+    # sounds like this should be __repr__ instead ??\r
+    def get_summary_tostring(self):\r
+        if not self.gidObject:\r
+            self.decode()\r
+        obj = self.gidObject.get_printable_subject()\r
+        caller = self.gidCaller.get_printable_subject()\r
+        exp = self.get_expiration()\r
+        # Summarize the rights too? The issuer?\r
+        return "[ Grant %s rights on %s until %s ]" % (caller, obj, exp)\r
 \r
     def get_signature(self):\r
         if not self.signature:\r
@@ -343,25 +394,28 @@ class Credential(object):
         if not self.gidObject:\r
             self.decode()\r
         return self.gidObject\r
-\r
-\r
             \r
     ##\r
-    # Expiration: an absolute UTC time of expiration (as either an int or datetime)\r
+    # Expiration: an absolute UTC time of expiration (as either an int or string or datetime)\r
     # \r
     def set_expiration(self, expiration):\r
-        if isinstance(expiration, int):\r
+        if isinstance(expiration, (int, float)):\r
             self.expiration = datetime.datetime.fromtimestamp(expiration)\r
-        else:\r
+        elif isinstance (expiration, datetime.datetime):\r
             self.expiration = expiration\r
-            \r
+        elif isinstance (expiration, StringTypes):\r
+            self.expiration = utcparse (expiration)\r
+        else:\r
+            logger.error ("unexpected input type in Credential.set_expiration")\r
+\r
 \r
     ##\r
-    # get the lifetime of the credential (in datetime format)\r
+    # get the lifetime of the credential (always in datetime format)\r
 \r
     def get_expiration(self):\r
         if not self.expiration:\r
             self.decode()\r
+        # at this point self.expiration is normalized as a datetime - DON'T call utcparse again\r
         return self.expiration\r
 \r
     ##\r
@@ -378,8 +432,7 @@ class Credential(object):
         if isinstance(privs, str):\r
             self.privileges = Rights(string = privs)\r
         else:\r
-            self.privileges = privs\r
-        \r
+            self.privileges = privs        \r
 \r
     ##\r
     # return the privileges as a Rights object\r
@@ -417,12 +470,19 @@ class Credential(object):
         doc = Document()\r
         signed_cred = doc.createElement("signed-credential")\r
 \r
-# PG adds these. It would be nice to be consistent.\r
-# But it's kind of odd for PL to use PG schemas that talk\r
-# about tickets, and the PG CM policies.\r
-# Note the careful addition of attributes from the parent below...\r
-#        signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")\r
-#        signed_cred.setAttribute("xsinoNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
+# Declare namespaces\r
+# Note that credential/policy.xsd are really the PG schemas\r
+# in a PL namespace.\r
+# Note that delegation of credentials between the 2 only really works\r
+# cause those schemas are identical.\r
+# Also note these PG schemas talk about PG tickets and CM policies.\r
+        signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")\r
+        # FIXME: See v2 schema at www.geni.net/resources/credential/2/credential.xsd\r
+        signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.planet-lab.org/resources/sfa/credential.xsd")\r
+        signed_cred.setAttribute("xsi:schemaLocation", "http://www.planet-lab.org/resources/sfa/ext/policy/1 http://www.planet-lab.org/resources/sfa/ext/policy/1/policy.xsd")\r
+\r
+# PG says for those last 2:\r
+#        signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
 #        signed_cred.setAttribute("xsi:schemaLocation", "http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd")\r
 \r
         doc.appendChild(signed_cred)  \r
@@ -441,7 +501,10 @@ class Credential(object):
         if not self.expiration:\r
             self.set_expiration(datetime.datetime.utcnow() + datetime.timedelta(seconds=DEFAULT_CREDENTIAL_LIFETIME))\r
         self.expiration = self.expiration.replace(microsecond=0)\r
-        append_sub(doc, cred, "expires", self.expiration.isoformat())\r
+        if self.expiration.tzinfo is not None and self.expiration.tzinfo.utcoffset(self.expiration) is not None:\r
+            # TZ aware. Make sure it is UTC\r
+            self.expiration = self.expiration.astimezone(tz.tzutc())\r
+        append_sub(doc, cred, "expires", self.expiration.strftime('%Y-%m-%dT%H:%M:%SZ')) # RFC3339\r
         privileges = doc.createElement("privileges")\r
         cred.appendChild(privileges)\r
 \r
@@ -459,13 +522,34 @@ class Credential(object):
             # If the root node is a signed-credential (it should be), then\r
             # get all its attributes and attach those to our signed_cred\r
             # node.\r
-            # Specifically, PG adds attributes for namespaces (which is reasonable),\r
+            # Specifically, PG and PLadd attributes for namespaces (which is reasonable),\r
             # and we need to include those again here or else their signature\r
             # no longer matches on the credential.\r
             # We expect three of these, but here we copy them all:\r
 #        signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")\r
-#        signed_cred.setAttribute("xsinoNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
+# and from PG (PL is equivalent, as shown above):\r
+#        signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
 #        signed_cred.setAttribute("xsi:schemaLocation", "http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd")\r
+\r
+            # HOWEVER!\r
+            # PL now also declares these, with different URLs, so\r
+            # the code notices those attributes already existed with\r
+            # different values, and complains.\r
+            # This happens regularly on delegation now that PG and\r
+            # PL both declare the namespace with different URLs.\r
+            # If the content ever differs this is a problem,\r
+            # but for now it works - different URLs (values in the attributes)\r
+            # but the same actual schema, so using the PG schema\r
+            # on delegated-to-PL credentials works fine.\r
+\r
+            # Note: you could also not copy attributes\r
+            # which already exist. It appears that both PG and PL\r
+            # will actually validate a slicecred with a parent\r
+            # signed using PG namespaces and a child signed with PL\r
+            # namespaces over the whole thing. But I don't know\r
+            # if that is a bug in xmlsec1, an accident since\r
+            # the contents of the schemas are the same,\r
+            # or something else, but it seems odd. And this works.\r
             parentRoot = sdoc.documentElement\r
             if parentRoot.tagName == "signed-credential" and parentRoot.hasAttributes():\r
                 for attrIx in range(0, parentRoot.attributes.length):\r
@@ -475,9 +559,9 @@ class Credential(object):
                     # Below throws InUse exception if we forgot to clone the attribute first\r
                     oldAttr = signed_cred.setAttributeNode(attr.cloneNode(True))\r
                     if oldAttr and oldAttr.value != attr.value:\r
-                        msg = "Delegating cred from owner %s to %s over %s replaced attribute %s value %s with %s" % (self.parent.gidCaller.get_urn(), self.gidCaller.get_urn(), self.gidObject.get_urn(), oldAttr.name, oldAttr.value, attr.value)\r
-                        logger.error(msg)\r
-                        raise CredentialNotVerifiable("Can't encode new valid delegated credential: %s" % msg)\r
+                        msg = "Delegating cred from owner %s to %s over %s:\n - Replaced attribute %s value '%s' with '%s'" % (self.parent.gidCaller.get_urn(), self.gidCaller.get_urn(), self.gidObject.get_urn(), oldAttr.name, oldAttr.value, attr.value)\r
+                        logger.warn(msg)\r
+                        #raise CredentialNotVerifiable("Can't encode new valid delegated credential: %s" % msg)\r
 \r
             p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)\r
             p = doc.createElement("parent")\r
@@ -497,7 +581,7 @@ class Credential(object):
                 signatures.appendChild(ele)\r
                 \r
         # Get the finished product\r
-        self.xml = doc.toxml()\r
+        self.xml = doc.toxml("utf-8")\r
 \r
 \r
     def save_to_random_tmp_file(self):       \r
@@ -576,7 +660,11 @@ class Credential(object):
     # you have loaded an existing signed credential, do not call encode() or sign() on it.\r
 \r
     def sign(self):\r
-        if not self.issuer_privkey or not self.issuer_gid:\r
+        if not self.issuer_privkey:\r
+            logger.warn("Cannot sign credential (no private key)")\r
+            return\r
+        if not self.issuer_gid:\r
+            logger.warn("Cannot sign credential (no issuer gid)")\r
             return\r
         doc = parseString(self.get_xml())\r
         sigs = doc.getElementsByTagName("signatures")[0]\r
@@ -588,7 +676,7 @@ class Credential(object):
         sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)\r
         sigs.appendChild(sig_ele)\r
 \r
-        self.xml = doc.toxml()\r
+        self.xml = doc.toxml("utf-8")\r
 \r
 \r
         # Split the issuer GID into multiple certificates if it's a chain\r
@@ -605,8 +693,10 @@ class Credential(object):
         # Call out to xmlsec1 to sign it\r
         ref = 'Sig_%s' % self.get_refid()\r
         filename = self.save_to_random_tmp_file()\r
-        signed = os.popen('%s --sign --node-id "%s" --privkey-pem %s,%s %s' \\r
-                 % (self.xmlsec_path, ref, self.issuer_privkey, ",".join(gid_files), filename)).read()\r
+        command='%s --sign --node-id "%s" --privkey-pem %s,%s %s' \\r
+            % (self.xmlsec_path, ref, self.issuer_privkey, ",".join(gid_files), filename)\r
+#        print 'command',command\r
+        signed = os.popen(command).read()\r
         os.remove(filename)\r
 \r
         for gid_file in gid_files:\r
@@ -621,7 +711,7 @@ class Credential(object):
         # Update signatures\r
         self.decode()       \r
 \r
-        \r
+\r
     ##\r
     # Retrieve the attributes of the credential from the XML.\r
     # This is automatically called by the various get_* methods of\r
@@ -636,36 +726,66 @@ class Credential(object):
 \r
         # Is this a signed-cred or just a cred?\r
         if len(signed_cred) > 0:\r
-            cred = signed_cred[0].getElementsByTagName("credential")[0]\r
+            creds = signed_cred[0].getElementsByTagName("credential")\r
             signatures = signed_cred[0].getElementsByTagName("signatures")\r
             if len(signatures) > 0:\r
                 sigs = signatures[0].getElementsByTagName("Signature")\r
         else:\r
-            cred = doc.getElementsByTagName("credential")[0]\r
+            creds = doc.getElementsByTagName("credential")\r
         \r
+        if creds is None or len(creds) == 0:\r
+            # malformed cred file\r
+            raise CredentialNotVerifiable("Malformed XML: No credential tag found")\r
 \r
-        self.set_refid(cred.getAttribute("xml:id"))\r
-        self.set_expiration(parse(getTextNode(cred, "expires")))\r
-        self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))\r
-        self.gidObject = GID(string=getTextNode(cred, "target_gid"))   \r
+        # Just take the first cred if there are more than one\r
+        cred = creds[0]\r
 \r
+        self.set_refid(cred.getAttribute("xml:id"))\r
+        self.set_expiration(utcparse(getTextNode(cred, "expires")))\r
+\r
+#        import traceback\r
+#        stack = traceback.extract_stack()\r
+\r
+        og = getTextNode(cred, "owner_gid")\r
+        # ABAC creds will have this be None and use this method\r
+#        if og is None:\r
+#            found = False\r
+#            for frame in stack:\r
+#                if 'super(ABACCredential, self).decode()' in frame:\r
+#                    found = True\r
+#                    break\r
+#            if not found:\r
+#                raise CredentialNotVerifiable("Malformed XML: No owner_gid found")\r
+        self.gidCaller = GID(string=og)\r
+        tg = getTextNode(cred, "target_gid")\r
+#        if tg is None:\r
+#            found = False\r
+#            for frame in stack:\r
+#                if 'super(ABACCredential, self).decode()' in frame:\r
+#                    found = True\r
+#                    break\r
+#            if not found:\r
+#                raise CredentialNotVerifiable("Malformed XML: No target_gid found")\r
+        self.gidObject = GID(string=tg)\r
 \r
         # Process privileges\r
-        privs = cred.getElementsByTagName("privileges")[0]\r
         rlist = Rights()\r
-        for priv in privs.getElementsByTagName("privilege"):\r
-            kind = getTextNode(priv, "name")\r
-            deleg = str2bool(getTextNode(priv, "can_delegate"))\r
-            if kind == '*':\r
-                # Convert * into the default privileges for the credential's type\r
-                # Each inherits the delegatability from the * above\r
-                _ , type = urn_to_hrn(self.gidObject.get_urn())\r
-                rl = rlist.determine_rights(type, self.gidObject.get_urn())\r
-                for r in rl.rights:\r
-                    r.delegate = deleg\r
-                    rlist.add(r)\r
-            else:\r
-                rlist.add(Right(kind.strip(), deleg))\r
+        priv_nodes = cred.getElementsByTagName("privileges")\r
+        if len(priv_nodes) > 0:\r
+            privs = priv_nodes[0]\r
+            for priv in privs.getElementsByTagName("privilege"):\r
+                kind = getTextNode(priv, "name")\r
+                deleg = str2bool(getTextNode(priv, "can_delegate"))\r
+                if kind == '*':\r
+                    # Convert * into the default privileges for the credential's type\r
+                    # Each inherits the delegatability from the * above\r
+                    _ , type = urn_to_hrn(self.gidObject.get_urn())\r
+                    rl = determine_rights(type, self.gidObject.get_urn())\r
+                    for r in rl.rights:\r
+                        r.delegate = deleg\r
+                        rlist.add(r)\r
+                else:\r
+                    rlist.add(Right(kind.strip(), deleg))\r
         self.set_privileges(rlist)\r
 \r
 \r
@@ -673,13 +793,15 @@ class Credential(object):
         parent = cred.getElementsByTagName("parent")\r
         if len(parent) > 0:\r
             parent_doc = parent[0].getElementsByTagName("credential")[0]\r
-            parent_xml = parent_doc.toxml()\r
+            parent_xml = parent_doc.toxml("utf-8")\r
+            if parent_xml is None or parent_xml.strip() == "":\r
+                raise CredentialNotVerifiable("Malformed XML: Had parent tag but it is empty")\r
             self.parent = Credential(string=parent_xml)\r
             self.updateRefID()\r
 \r
         # Assign the signatures to the credentials\r
         for sig in sigs:\r
-            Sig = Signature(string=sig.toxml())\r
+            Sig = Signature(string=sig.toxml("utf-8"))\r
 \r
             for cur_cred in self.get_credential_list():\r
                 if cur_cred.get_refid() == Sig.get_refid():\r
@@ -702,6 +824,7 @@ class Credential(object):
     # . 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
@@ -721,15 +844,15 @@ class Credential(object):
             self.decode()\r
 \r
         # validate against RelaxNG schema\r
-        if not self.legacy:\r
+        if HAVELXML and not self.legacy:\r
             if schema and os.path.exists(schema):\r
                 tree = etree.parse(StringIO(self.xml))\r
                 schema_doc = etree.parse(schema)\r
                 xmlschema = etree.XMLSchema(schema_doc)\r
                 if not xmlschema.validate(tree):\r
                     error = xmlschema.error_log.last_error\r
-                    message = "%s (line %s)" % (error.message, error.line)\r
-                    raise CredentialNotVerifiable(message)        \r
+                    message = "%s: %s (line %s)" % (self.get_summary_tostring(), error.message, error.line)\r
+                    raise CredentialNotVerifiable(message)\r
 \r
         if trusted_certs_required and trusted_certs is None:\r
             trusted_certs = []\r
@@ -760,8 +883,8 @@ class Credential(object):
             return True\r
         \r
         # make sure it is not expired\r
-        if self.get_expiration().replace(tzinfo=None) < datetime.datetime.utcnow():\r
-            raise CredentialNotVerifiable("Credential expired at %s" % self.expiration.isoformat())\r
+        if self.get_expiration() < datetime.datetime.utcnow():\r
+            raise CredentialNotVerifiable("Credential %s expired at %s" % (self.get_summary_tostring(), self.expiration.isoformat()))\r
 \r
         # Verify the signatures\r
         filename = self.save_to_random_tmp_file()\r
@@ -769,7 +892,7 @@ class Credential(object):
             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
@@ -801,15 +924,16 @@ class Credential(object):
                     mstart = mstart + 4\r
                     mend = verified.find('\\', mstart)\r
                     msg = verified[mstart:mend]\r
-                raise CredentialNotVerifiable("xmlsec1 error verifying cred using Signature ID %s: %s %s" % (ref, msg, verified.strip()))\r
+                raise CredentialNotVerifiable("xmlsec1 error verifying cred %s using Signature ID %s: %s %s" % (self.get_summary_tostring(), ref, msg, verified.strip()))\r
         os.remove(filename)\r
 \r
         # Verify the parents (delegation)\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
@@ -827,31 +951,71 @@ class Credential(object):
         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
+        if root_cred.get_signature() is None:\r
+            # malformed\r
+            raise CredentialNotVerifiable("Could not verify credential owned by %s for object %s. Cred has no signature" % (self.gidCaller.get_urn(), self.gidObject.get_urn()))\r
+\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
+        # 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
+\r
+        # Note that if verify() gave us no trusted_gids then this\r
+        # call will fail. So skip it if we have no trusted_gids\r
+        if trusted_gids and len(trusted_gids) > 0:\r
+            root_cred_signer.verify_chain(trusted_gids)\r
+        else:\r
+            logger.debug("No trusted gids. Cannot verify that cred signer is signed by a trusted authority. Skipping that check.")\r
 \r
-        # See if it the signer is an authority over the domain of the target\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
-            #sfa_logger.debug('Cred signer is an 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
@@ -876,23 +1040,23 @@ class Credential(object):
         # make sure the rights given to the child are a subset of the\r
         # parents rights (and check delegate bits)\r
         if not parent_cred.get_privileges().is_superset(self.get_privileges()):\r
-            raise ChildRightsNotSubsetOfParent(("Parent cred ref %s rights " % self.parent.get_refid()) + \r
-                self.parent.get_privileges().save_to_string() + (" not superset of delegated cred ref %s rights " % self.get_refid()) +\r
+            raise ChildRightsNotSubsetOfParent(("Parent cred ref %s rights " % parent_cred.get_refid()) +\r
+                self.parent.get_privileges().save_to_string() + (" not superset of delegated cred %s ref %s rights " % (self.get_summary_tostring(), self.get_refid())) +\r
                 self.get_privileges().save_to_string())\r
 \r
         # make sure my target gid is the same as the parent's\r
         if not parent_cred.get_gid_object().save_to_string() == \\r
            self.get_gid_object().save_to_string():\r
-            raise CredentialNotVerifiable("Target gid not equal between parent and child")\r
+            raise CredentialNotVerifiable("Delegated cred %s: Target gid not equal between parent and child. Parent %s" % (self.get_summary_tostring(), parent_cred.get_summary_tostring()))\r
 \r
         # make sure my expiry time is <= my parent's\r
         if not parent_cred.get_expiration() >= self.get_expiration():\r
-            raise CredentialNotVerifiable("Delegated credential expires after parent")\r
+            raise CredentialNotVerifiable("Delegated credential %s expires after parent %s" % (self.get_summary_tostring(), parent_cred.get_summary_tostring()))\r
 \r
         # make sure my signer is the parent's caller\r
         if not parent_cred.get_gid_caller().save_to_string(False) == \\r
            self.get_signature().get_issuer_gid().save_to_string(False):\r
-            raise CredentialNotVerifiable("Delegated credential not signed by parent caller")\r
+            raise CredentialNotVerifiable("Delegated credential %s not signed by parent %s's caller" % (self.get_summary_tostring(), parent_cred.get_summary_tostring()))\r
                 \r
         # Recurse\r
         if parent_cred.parent:\r
@@ -932,7 +1096,7 @@ class Credential(object):
     # only informative\r
     def get_filename(self):\r
         return getattr(self,'filename',None)\r
\r
+\r
     ##\r
     # Dump the contents of a credential to stdout in human-readable format\r
     #\r
@@ -941,7 +1105,7 @@ class Credential(object):
         print self.dump_string(*args, **kwargs)\r
 \r
 \r
-    def dump_string(self, dump_parents=False):\r
+    def dump_string(self, dump_parents=False, show_xml=False):\r
         result=""\r
         result += "CREDENTIAL %s\n" % self.get_subject()\r
         filename=self.get_filename()\r
@@ -953,8 +1117,11 @@ class Credential(object):
             result += gidCaller.dump_string(8, dump_parents)\r
 \r
         if self.get_signature():\r
-            print "  gidIssuer:"\r
-            self.get_signature().get_issuer_gid().dump(8, dump_parents)\r
+            result += "  gidIssuer:\n"\r
+            result += self.get_signature().get_issuer_gid().dump_string(8, dump_parents)\r
+\r
+        if self.expiration:\r
+            result += "  expiration: " + self.expiration.isoformat() + "\n"\r
 \r
         gidObject = self.get_gid_object()\r
         if gidObject:\r
@@ -963,6 +1130,18 @@ class Credential(object):
 \r
         if self.parent and dump_parents:\r
             result += "\nPARENT"\r
-            result += self.parent.dump(True)\r
+            result += self.parent.dump_string(True)\r
+\r
+        if show_xml and HAVELXML:\r
+            try:\r
+                tree = etree.parse(StringIO(self.xml))\r
+                aside = etree.tostring(tree, pretty_print=True)\r
+                result += "\nXML:\n\n"\r
+                result += aside\r
+                result += "\nEnd XML\n"\r
+            except:\r
+                import traceback\r
+                print "exc. Credential.dump_string / XML"\r
+                traceback.print_exc()\r
 \r
         return result\r