Changeset 7413
- Timestamp:
- 02/09/10 09:28:06 (10 years ago)
- Location:
- TI12-security/trunk/NDGSecurity/python
- Files:
-
- 6 edited
- 1 moved
Legend:
- Unmodified
- Added
- Removed
-
TI12-security/trunk/NDGSecurity/python/ndg_security_server/ndg/security/server/wsgi/authz/pep.py
r7364 r7413 20 20 AuthzDecisionQuerySslSOAPBinding 21 21 22 from ndg.xacml import core as _xacmlCore 22 from ndg.xacml.core import Identifiers as XacmlIdentifiers 23 from ndg.xacml.core import context as _xacmlCtx 24 from ndg.xacml.core.attribute import Attribute as XacmlAttribute 25 from ndg.xacml.core.attributevalue import ( 26 AttributeValueClassFactory as XacmlAttributeValueClassFactory, 27 AttributeValue as XacmlAttributeValue) 28 from ndg.xacml.core.context.result import Decision as XacmlDecision 23 29 from ndg.xacml.core.context.pdp import PDP 24 from ndg.xacml.core import context as _xacmlCtx 25 from ndg.xacml.parsers.etree.factory import ReaderFactory as \ 26 XacmlPolicyReaderFactory 30 from ndg.xacml.parsers.etree.factory import ( 31 ReaderFactory as XacmlPolicyReaderFactory) 27 32 28 33 from ndg.security.server.wsgi.session import (SessionMiddlewareBase, … … 56 61 SESSION_KEY_PARAM_NAME = 'sessionKey' 57 62 CACHE_DECISIONS_PARAM_NAME = 'cacheDecisions' 58 LOCAL_P DP_FILEPATH_PARAM_NAME = 'localPolicyFilePath'63 LOCAL_POLICY_FILEPATH_PARAM_NAME = 'localPolicyFilePath' 59 64 60 65 CREDENTIAL_WALLET_SESSION_KEYNAME = \ … … 67 72 SESSION_KEY_PARAM_NAME, 68 73 CACHE_DECISIONS_PARAM_NAME, 69 LOCAL_P DP_FILEPATH_PARAM_NAME74 LOCAL_POLICY_FILEPATH_PARAM_NAME 70 75 ) 76 77 XACML_ATTRIBUTEVALUE_CLASS_FACTORY = XacmlAttributeValueClassFactory() 78 71 79 __slots__ = ( 72 80 '_app', '__client', '__session', '__localPdp' … … 201 209 setattr(self, name, value) 202 210 203 elif value != self.__class__.LOCAL_PDP_FILEPATH_PARAM_NAME:211 elif name != self.__class__.LOCAL_POLICY_FILEPATH_PARAM_NAME: 204 212 # Policy file setting is optional 205 213 raise SamlPepFilterConfigError('Missing option %r' % paramName) … … 260 268 """ 261 269 request = webob.Request(environ) 270 requestURI = request.url 262 271 263 272 # Apply local PDP if set 264 if self.__localPdp is not None: 265 self.__localPdp.evaluate() 273 if not self.isApplicableRequest(requestURI): 274 # The local PDP has returned a decision that the requested URI is 275 # not applicable and so the authorisation service need not be 276 # invoked. This step is an efficiency measure to avoid multiple 277 # callouts to the authorisation service for resources which 278 # obviously don't need any restrictions 279 return self._app(environ, start_response) 266 280 267 281 # Check for cached decision 268 282 if self.cacheDecisions: 269 assertions = self._retrieveCachedAssertions(request .url)283 assertions = self._retrieveCachedAssertions(requestURI) 270 284 else: 271 285 assertions = None … … 284 298 # Record the result in the user's session to enable later 285 299 # interrogation by any result handler Middleware 286 self.s etSession(self.client.query, samlAuthzResponse)300 self.saveResultCtx(self.client.query, samlAuthzResponse) 287 301 288 302 … … 317 331 318 332 response = webob.Response() 333 response.status = httplib.FORBIDDEN 319 334 response.body = ('An error occurred retrieving an access decision ' 320 335 'for %r for user %r' % ( … … 374 389 self.session.save() 375 390 376 def s etSession(self, request, response, save=True):391 def saveResultCtx(self, request, response, save=True): 377 392 """Set PEP context information in the Beaker session using standard key 378 393 names. This is a snapshot of the last request and the response … … 398 413 self.session.save() 399 414 400 def enforceFromLocalPdp(self, subjectId, resourceURI): 415 PDP_DENY_RESPONSES = ( 416 XacmlDecision.DENY_STR, XacmlDecision.INDETERMINATE_STR 417 ) 418 419 def isApplicableRequest(self, resourceURI): 401 420 """A local PDP can filter out some requests to avoid the need to call 402 421 out to the authorisation service 403 """ 404 xacmlRequest = self._createXacmlRequestCtx(subjectId, resourceURI) 422 423 @param resourceURI: URI of requested resource 424 @type resourceURI: basestring 425 """ 426 if self.__localPdp is None: 427 log.debug("No Local PDP set: passing on request to main " 428 "authorisation service...") 429 return True 430 431 xacmlRequest = self._createXacmlRequestCtx(resourceURI) 405 432 xacmlResponse = self.__localPdp.evaluate(xacmlRequest) 433 for result in xacmlResponse.results: 434 if result.decision.value != XacmlDecision.NOT_APPLICABLE_STR: 435 log.debug("Local PDP returned %s decision, passing request on " 436 "to main authorisation service ...", 437 result.decision.value) 438 return True 439 440 return False 406 441 407 442 def _createXacmlRequestCtx(self, resourceURI): 443 """Wrapper to create a request context for a local PDP - see 444 isApplicableRequest 445 446 @param resourceURI: URI of requested resource 447 @type resourceURI: basestring 448 """ 408 449 request = _xacmlCtx.request.Request() 409 450 410 451 resource = _xacmlCtx.request.Resource() 411 resourceAttribute = _xacmlCore.attribute.Attribute()452 resourceAttribute = XacmlAttribute() 412 453 resource.attributes.append(resourceAttribute) 413 454 414 resourceAttribute.attributeId = \ 415 _xacmlCore.Identifiers.Resource.RESOURCE_ID 416 417 resourceAttribute.dataType = AnyUriAttributeValue.IDENTIFIER 418 resourceAttribute.attributeValues.append(AnyUriAttributeValue()) 455 resourceAttribute.attributeId = XacmlIdentifiers.Resource.RESOURCE_ID 456 457 XacmlAnyUriAttributeValue = \ 458 self.__class__.XACML_ATTRIBUTEVALUE_CLASS_FACTORY( 459 XacmlAttributeValue.ANY_TYPE_URI) 460 461 resourceAttribute.dataType = XacmlAnyUriAttributeValue.IDENTIFIER 462 resourceAttribute.attributeValues.append(XacmlAnyUriAttributeValue()) 419 463 resourceAttribute.attributeValues[-1].value = resourceURI 420 464 -
TI12-security/trunk/NDGSecurity/python/ndg_security_server/ndg/security/server/xacml/ctx_handler/saml_ctx_handler.py
r7364 r7413 25 25 from ndg.xacml.core import context as _xacmlContext 26 26 from ndg.xacml.core.attribute import Attribute as XacmlAttribute 27 from ndg.xacml.core.attributevalue import AttributeValueClassFactory as \ 28 XacmlAttributeValueClassFactory 27 from ndg.xacml.core.attributevalue import ( 28 AttributeValueClassFactory as XacmlAttributeValueClassFactory, 29 AttributeValue as XacmlAttributeValue) 29 30 from ndg.xacml.parsers.etree.factory import ReaderFactory as \ 30 31 XacmlPolicyReaderFactory … … 377 378 378 379 XacmlAnyUriAttributeValue = xacmlAttributeValueFactory( 379 'http://www.w3.org/2001/XMLSchema#anyURI')380 XacmlAttributeValue.ANY_TYPE_URI) 380 381 381 382 openidSubjectAttribute.dataType = XacmlAnyUriAttributeValue.IDENTIFIER … … 389 390 390 391 XacmlStringAttributeValue = xacmlAttributeValueFactory( 391 'http://www.w3.org/2001/XMLSchema#string')392 XacmlAttributeValue.STRING_TYPE_URI) 392 393 393 394 xacmlRequest.subjects.append(xacmlSubject) -
TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/__init__.py
r7358 r7413 13 13 import logging 14 14 import socket 15 15 16 logging.basicConfig() 16 17 log = logging.getLogger(__name__) -
TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/wsgi/authz/request-filter.xml
r7364 r7413 35 35 </Resources> 36 36 </Target> 37 <Rule RuleId="Catch all" Effect="Deny"></Rule> 37 38 </Policy> -
TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/wsgi/authz/saml-test.ini
r7354 r7413 24 24 pep.authzServiceURI = https://localhost:9443/authorisation-service 25 25 pep.cacheDecisions = True 26 pep.localPolicyFilePath = %(here)s/request-filter.xml 26 27 27 28 # Settings for Policy Information Point used by the Policy Decision Point to -
TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/wsgi/authz/test_authz.py
r7287 r7413 15 15 import unittest 16 16 import os 17 import time 17 18 from urlparse import urlunsplit 18 19 19 20 from os import path 20 21 from ConfigParser import SafeConfigParser 22 from urllib2 import URLError 23 24 from uuid import uuid4 25 from datetime import datetime, timedelta 21 26 22 27 import paste.fixture 23 28 from paste.deploy import loadapp 29 30 from ndg.saml.saml2.core import (SAMLVersion, Subject, NameID, Issuer, 31 AuthzDecisionQuery, AuthzDecisionStatement, 32 Status, StatusCode, StatusMessage, 33 DecisionType, Action, Conditions, Assertion) 34 from ndg.saml.xml.etree import (AuthzDecisionQueryElementTree, 35 ResponseElementTree) 24 36 25 37 from ndg.security.test.unit import BaseTestCase … … 30 42 HTTPRedirectPEPResultHandlerMiddleware 31 43 from ndg.security.server.wsgi.authz.pep import SamlPepFilterConfigError 32 33 34 from uuid import uuid435 from datetime import datetime, timedelta36 37 from ndg.saml.saml2.core import (SAMLVersion, Subject, NameID, Issuer,38 AuthzDecisionQuery, AuthzDecisionStatement,39 Status, StatusCode, StatusMessage,40 DecisionType, Action, Conditions, Assertion)41 from ndg.saml.xml.etree import (AuthzDecisionQueryElementTree,42 ResponseElementTree)43 44 44 45 … … 155 156 156 157 def __call__(self, environ, start_response): 157 158 response = self.__class__.RESPONSE 158 159 if environ['PATH_INFO'] == '/test_401': 159 160 status = "401 Unauthorized" … … 172 173 elif environ['PATH_INFO'] == '/test_accessGrantedToSecuredURI': 173 174 status = "200 OK" 175 176 elif environ['PATH_INFO'].startswith('/layout'): 177 status = "200 OK" 178 response += ("\n\nAny calls to this path or sub-path should be " 179 "publicly accessible") 174 180 else: 175 181 status = "404 Not found" … … 177 183 start_response(status, 178 184 [('Content-length', 179 str(len( TestAuthZMiddleware.RESPONSE))),185 str(len(response))), 180 186 ('Content-type', 'text/plain')]) 181 187 … … 216 222 217 223 self.startAuthorisationService() 218 224 219 225 220 226 class SamlPepFilterTestCase(BaseAuthzFilterTestCase): … … 272 278 273 279 def test05Catch401WithNotLoggedInAndSecuredURI(self): 274 # AuthZ middleware grants access because the URI requested has no275 # subject restriction set in the policy rule280 # User is not logged in and a secured resource has been requested so 401 281 # response is returned 276 282 277 283 # AuthZ middleware checks for username key in session set by AuthN 278 284 # handler 279 extra_environ ={self.__class__.SESSION_KEYNAME:BeakerSessionStub()}285 extra_environ = {self.__class__.SESSION_KEYNAME: BeakerSessionStub()} 280 286 response = self.app.get('/test_accessDeniedToSecuredURI', 281 287 extra_environ=extra_environ, … … 284 290 285 291 def test06AccessDeniedForSecuredURI(self): 286 287 292 # User is logged in but doesn't have the required credentials for 288 293 # access … … 298 303 print response 299 304 300 def test07AccessGrantedForSecuredURI(self): 301 305 def test07AccessGrantedForSecuredURI(self): 302 306 # User is logged in and has credentials for access to a URI secured 303 307 # by the policy file … … 313 317 self.assert_(TestAuthZMiddleware.RESPONSE in response) 314 318 print response 315 319 320 def test08LocalPolicyFiltersOutRequest(self): 321 # The local PDP filters out the incoming request as not applicable so 322 # that the authorisation service is never invoked. 323 extra_environ = {self.__class__.SESSION_KEYNAME: BeakerSessionStub()} 324 response = self.app.get('/layout/my.css', extra_environ=extra_environ, 325 status=200) 326 self.assert_(response.body) 327 316 328 317 329 class PEPResultHandlerTestCase(BaseAuthzFilterTestCase):
Note: See TracChangeset
for help on using the changeset viewer.