source: TI12-security/trunk/python/ndg_security_test/ndg/security/test/config/attributeauthority/sitea/siteAUserRoles.py @ 6067

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg_security_test/ndg/security/test/config/attributeauthority/sitea/siteAUserRoles.py@6067
Revision 6067, 6.4 KB checked in by pjkersha, 11 years ago (diff)

Re-issue 1.3.3 release:

  • uses SQLAlchemy test user database for authz_lite integration tests
  • important fix for ndg.security.common.saml_utils.bindings.AttributeQuerySOAPBinding: set 'nameFormat' attribute not 'format' for attributes in AttributeQuery?.
Line 
1"""NDG Attribute Authority User Roles class - acts as an interface between
2the data centre's user roles configuration and the Attribute Authority
3                                                                               
4NERC Data Grid Project
5"""
6__author__ = "P J Kershaw"
7__date__ = "29/07/05"
8__copyright__ = "(C) 2009 Science and Technology Facilities Council"
9__license__ = "BSD - see LICENSE file in top-level directory"
10__contact__ = "Philip.Kershaw@stfc.ac.uk"
11__revision__ = '$Id:siteAUserRoles.py 4371 2008-10-29 09:44:51Z pjkersha $'
12
13from datetime import datetime, timedelta
14from uuid import uuid4
15
16from saml.common.xml import SAMLConstants
17from saml.saml2.core import (Assertion, Attribute, AttributeStatement, Issuer,
18                             SAMLVersion, Subject, NameID, Conditions,
19                             XSStringAttributeValue)
20
21from ndg.security.common.X509 import X500DN
22from ndg.security.server.attributeauthority import (AttributeInterface, 
23                                                    InvalidRequestorId, 
24                                                    AttributeNotKnownError, 
25                                                    AttributeReleaseDenied, 
26                                                    UserIdNotKnown)
27from ndg.security.test.unit import BaseTestCase
28
29
30class TestUserRoles(AttributeInterface):
31    """Test User Roles class dynamic import for Attribute Authority"""
32    ATTRIBUTE_NAMES = BaseTestCase.ATTRIBUTE_NAMES
33    ATTRIBUTE_VALUES = BaseTestCase.ATTRIBUTE_VALUES
34
35    SAML_ATTRIBUTE_NAMES = ATTRIBUTE_NAMES + (
36        'urn:esg:email:address',
37        'urn:esg:first:name', 
38        'urn:esg:last:name'
39    )
40   
41    SAML_ATTRIBUTE_VALUES = (
42        ATTRIBUTE_VALUES,
43        ('p.kershaw@somewhere.ac.uk',),
44        ('Philip',),
45        ('Kershaw',)
46    )
47   
48    SAML_ATTRIBUTE_FRIENDLY_NAMES = ('',)*len(ATTRIBUTE_NAMES) + (
49        "EmailAddress",
50        "FirstName",
51        "LastName"
52    )
53    SAML_ATTRIBUTE_FORMATS = (SAMLConstants.XSD_NS+"#"+\
54                              XSStringAttributeValue.TYPE_LOCAL_NAME,) * \
55                              len(SAML_ATTRIBUTE_NAMES)
56    SAML_ATTRIBUTES = []
57   
58    for name, vals, format, friendlyName in zip(SAML_ATTRIBUTE_NAMES,
59                                               SAML_ATTRIBUTE_VALUES,
60                                               SAML_ATTRIBUTE_FORMATS,
61                                               SAML_ATTRIBUTE_FRIENDLY_NAMES):
62        SAML_ATTRIBUTES.append(Attribute())
63        SAML_ATTRIBUTES[-1].name = name
64        SAML_ATTRIBUTES[-1].nameFormat = format
65        SAML_ATTRIBUTES[-1].friendlyName = friendlyName
66        for val in vals:
67            SAML_ATTRIBUTES[-1].attributeValues.append(XSStringAttributeValue())
68            SAML_ATTRIBUTES[-1].attributeValues[-1].value = val
69
70    del name, val, vals, format, friendlyName
71   
72    # 8 hours validity for issued assertions
73    SAML_ASSERTION_LIFETIME = 8*60*60
74   
75    VALID_USER_IDS = ("https://openid.localhost/philip.kershaw",
76                      BaseTestCase.OPENID_URI)
77    VALID_REQUESTOR_IDS = BaseTestCase.VALID_REQUESTOR_IDS
78   
79    ISSUER_NAME = "/O=Site A/CN=Attribute Authority"
80   
81    INSUFFICIENT_PRIVILEGES_REQUESTOR_ID = str(
82                    X500DN.fromString("/O=Site B/CN=Authorisation Service"))
83   
84    def __init__(self, propertiesFilePath=None):
85        pass
86
87    def getRoles(self, userId):
88        return TestUserRoles.ATTRIBUTE_VALUES
89
90    def getAttributes(self, attributeQuery, response):
91        '''Test Attribute Authority SAML Attribute Query interface'''
92       
93        userId = attributeQuery.subject.nameID.value
94        requestedAttributeNames = [attribute.name
95                                   for attribute in attributeQuery.attributes]
96        requestorId = X500DN.fromString(attributeQuery.issuer.value)
97       
98        if userId not in TestUserRoles.VALID_USER_IDS:
99            raise UserIdNotKnown('Subject Id "%s" is not known to this '
100                                 'authority' % userId)
101           
102        if requestorId not in TestUserRoles.VALID_REQUESTOR_IDS:
103            raise InvalidRequestorId('Requestor identity "%s" is invalid' %
104                                     requestorId)
105       
106        unknownAttrNames = [attrName for attrName in requestedAttributeNames
107                            if attrName not in 
108                            TestUserRoles.SAML_ATTRIBUTE_NAMES]
109       
110        if len(unknownAttrNames) > 0:
111            raise AttributeNotKnownError("Unknown attributes requested: %r" %
112                                         unknownAttrNames)
113           
114        if requestorId == TestUserRoles.INSUFFICIENT_PRIVILEGES_REQUESTOR_ID:
115            raise AttributeReleaseDenied("Attribute release denied for the "
116                                         'requestor "%s"' % requestorId)
117       
118        # Create a new assertion to hold the attributes to be returned
119        assertion = Assertion()
120       
121        assertion.version = SAMLVersion(SAMLVersion.VERSION_20)
122        assertion.id = str(uuid4())
123        assertion.issueInstant = response.issueInstant
124   
125        assertion.issuer = Issuer()
126        assertion.issuer.value = TestUserRoles.ISSUER_NAME
127        assertion.issuer.format = Issuer.X509_SUBJECT
128       
129        assertion.conditions = Conditions()
130        assertion.conditions.notBefore = assertion.issueInstant
131        assertion.conditions.notOnOrAfter = assertion.conditions.notBefore + \
132            timedelta(seconds=TestUserRoles.SAML_ASSERTION_LIFETIME)
133       
134        assertion.subject = Subject() 
135        assertion.subject.nameID = NameID()
136        assertion.subject.nameID.format = attributeQuery.subject.nameID.format
137        assertion.subject.nameID.value = attributeQuery.subject.nameID.value
138
139        attributeStatement = AttributeStatement()
140       
141        # Add test set of attributes
142        for name in requestedAttributeNames:
143            attributeFound = False
144            for attribute in TestUserRoles.SAML_ATTRIBUTES:
145                if attribute.name == name:
146                    attributeFound = True
147                    break
148           
149            if attributeFound:
150                attributeStatement.attributes.append(attribute)
151            else:
152                raise AttributeNotKnownError("Unknown attribute requested: %s"%
153                                             name)
154 
155        assertion.attributeStatements.append(attributeStatement)       
156        response.assertions.append(assertion)
157 
Note: See TracBrowser for help on using the repository browser.