def __init__(self, governance_controller): self.resource_policy_decision_point = dict() self.service_policy_decision_point = dict() self.empty_pdp = PDP.fromPolicySource(path.join(THIS_DIR, XACML_EMPTY_POLICY_FILENAME), ReaderFactory) self.load_common_service_policy_rules('') self.governance_controller = governance_controller #Create and register an Attribute Value derived class to handle a dict type used for the messages _className = 'Dict' + AttributeValue.CLASS_NAME_SUFFIX _classVars = {'TYPE': dict, 'IDENTIFIER': DICT_TYPE_URI} _attributeValueClass = type(_className, (AttributeValue, ), _classVars) AttributeValue.register(_attributeValueClass) attributeValueFactory.addClass(DICT_TYPE_URI, _attributeValueClass) self.DictAttributeValue = attributeValueFactory(DICT_TYPE_URI) #Create and register an Attribute Value derived class to handle any object _className = 'Object' + AttributeValue.CLASS_NAME_SUFFIX _classVars = {'TYPE': object, 'IDENTIFIER': OBJECT_TYPE_URI} _attributeValueClass = type(_className, (AttributeValue, ), _classVars) AttributeValue.register(_attributeValueClass) attributeValueFactory.addClass(OBJECT_TYPE_URI, _attributeValueClass) self.ObjectAttributeValue = attributeValueFactory(OBJECT_TYPE_URI) #Create and add new function for evaluating functions that take the message as a dict from pyon.core.governance.policy.evaluate import EvaluateCode, EvaluateFunction functionMap['urn:oasis:names:tc:xacml:1.0:function:evaluate-code'] = EvaluateCode functionMap['urn:oasis:names:tc:xacml:1.0:function:evaluate-function'] = EvaluateFunction
def load_org_policy_rules(self, rules_text): log.debug("Loading policies for org") #Simply create a new PDP object for the service #TODO - make sure this is thread safe with the evaluation that uses it. input_source = StringIO(rules_text) self.org_pdp = PDP.fromPolicySource(input_source, ReaderFactory)
def load_policy_rules(self, resource_policy, rules_text): log.debug("Loading rules for service: %s" % resource_policy) #Simply create a new PDP object for the service #TODO - make sure this is thread safe with the evaluation that uses it. input_source = StringIO(rules_text) self.policy_decision_point[resource_policy] = PDP.fromPolicySource(input_source, ReaderFactory)
def initialise(self, prefix='', **kw): '''Initialise object from keyword settings :type prefix: basestring :param prefix: prefix for configuration items :type kw: dict :param kw: configuration settings dictionary :raise SamlPepFilterConfigError: missing option setting(s) ''' # Parse other options for name in SamlPepFilter.PARAM_NAMES: paramName = prefix + name value = kw.get(paramName) if value is not None: setattr(self, name, value) elif name != self.__class__.LOCAL_POLICY_FILEPATH_PARAM_NAME: # Policy file setting is optional raise SamlPepFilterConfigError('Missing option %r' % paramName) # Parse authorisation decision query options queryPrefix = prefix + self.__class__.AUTHZ_DECISION_QUERY_PARAMS_PREFIX self.client.parseKeywords(prefix=queryPrefix, **kw) # Initialise the local PDP if self.localPolicyFilePath: self.__localPdp = PDP.fromPolicySource(self.localPolicyFilePath, XacmlPolicyReaderFactory)
def __init__(self, *args, **kwargs): self.resource_policy_decision_point = dict() self.service_policy_decision_point = dict() self.empty_pdp = PDP.fromPolicySource( path.join(THIS_DIR, XACML_EMPTY_POLICY_FILENAME), ReaderFactory) self.load_common_service_policy_rules('')
def __init__(self, governance_controller): self.resource_policy_decision_point = dict() self.service_policy_decision_point = dict() self.empty_pdp = PDP.fromPolicySource(path.join(THIS_DIR, XACML_EMPTY_POLICY_FILENAME), ReaderFactory) self.load_common_service_policy_rules('') self.governance_controller = governance_controller
def load_common_service_policy_rules(self, rules_text): self.common_service_rules = rules_text input_source = StringIO( self.create_policy_from_rules(COMMON_SERVICE_POLICY_RULES, rules_text)) self.load_common_service_pdp = PDP.fromPolicySource( input_source, ReaderFactory)
def __init__(self, *args, **kwargs): self.policy_decision_point = dict() self.org_pdp = PDP.fromPolicySource(path.join(THIS_DIR, XACML_EMPTY_POLICY_FILENAME), ReaderFactory) #Adding an not function to XACML from pyon.core.governance.policy.xacml.not_function import Not from pyon.core.governance.policy.xacml.and_function import And functionMap['urn:oasis:names:tc:xacml:ooi:function:not'] = Not functionMap['urn:oasis:names:tc:xacml:ooi:function:and'] = And
def test02_04And2ArgsTrue(self): self.pdp = PDP.fromPolicySource(XACML_ANDTEST_FILEPATH, ReaderFactory) request = self._createRequestCtx( self.__class__.RESOURCE4_ID, subjectRoles=('role1', 'role2')) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: self.failIf(result.decision != Decision.PERMIT, "Expecting Permit decision")
def test02_03And1ArgFalse(self): self.pdp = PDP.fromPolicySource(XACML_ANDTEST_FILEPATH, ReaderFactory) request = self._createRequestCtx( self.__class__.RESOURCE3_ID, subjectRoles=('role1',)) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: self.failIf(result.decision != Decision.DENY, "Expecting Deny decision")
def __init__(self, *args, **kwargs): self.policy_decision_point = dict() self.org_pdp = PDP.fromPolicySource( path.join(THIS_DIR, XACML_EMPTY_POLICY_FILENAME), ReaderFactory) #Adding an not function to XACML from pyon.core.governance.policy.xacml.not_function import Not from pyon.core.governance.policy.xacml.and_function import And functionMap['urn:oasis:names:tc:xacml:ooi:function:not'] = Not functionMap['urn:oasis:names:tc:xacml:ooi:function:and'] = And
def load_policy_rules(self, resource_id, rules_text): log.debug("Loading policies for resource: %s" % resource_id) self.clear_resource_policy(resource_id) #Simply create a new PDP object for the service #TODO - make sure this is thread safe with the evaluation that uses it. input_source = StringIO(rules_text) self.policy_decision_point[resource_id] = PDP.fromPolicySource( input_source, ReaderFactory)
def get_pdp(self, resource_id): if self.policy_decision_point.has_key(resource_id): return self.policy_decision_point[resource_id] # If a PDP does not exist for this resource - then return default. if self.default_pdp is None: # Loads a blank policy set as the default or an unknown resource_policy self.default_pdp = PDP.fromPolicySource(path.join(THIS_DIR, XACML_EMPTY_POLICY_FILENAME), ReaderFactory) return self.default_pdp
def createPDP(self): """Create PDP from ion agents policy file""" log.debug("Creating a new PDP") # TODO - May need to implement a not function here. #from pyon.core.governance.ndg_xacml.ooi_and import And #functionMap['urn:oasis:names:tc:xacml:ooi:function:and'] = And self.policy_decision_point = PDP.fromPolicySource(path.join(THIS_DIR, XACML_ION_POLICY_FILENAME), ReaderFactory) return self.policy_decision_point
def test01_01StringUrlencode(self): """Test URL encoding of a string value resulting in a permit decision. """ self.pdp = PDP.fromPolicySource(XACML_CUSTOM_FUNCTION_TEST_FILEPATH, ReaderFactory) request = self._createRequestCtx(self.__class__.RESOURCE1_ID, subjectRoles=('role1',)) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: self.failIf(result.decision != Decision.PERMIT, "Expecting Permit decision")
def load_resource_policy_rules(self, resource_key, rules_text): if not rules_text and not self.resource_policy_decision_point.has_key(resource_key): return log.info("Loading policies for resource: %s" % resource_key) self.clear_resource_policy(resource_key) #Simply create a new PDP object for the service input_source = StringIO(self.create_policy_from_rules(resource_key, rules_text)) self.resource_policy_decision_point[resource_key] = PDP.fromPolicySource(input_source, ReaderFactory)
def test01_04StringConcatenate4Values(self): """Test concatenation of 4 string values resulting in deny decision. """ self.pdp = PDP.fromPolicySource(XACML_CONCATENATE_TEST_FILEPATH, ReaderFactory) request = self._createRequestCtx(self.__class__.RESOURCE4_ID, subjectRoles=('role1',)) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: self.failIf(result.decision != Decision.DENY, "Expecting Deny decision")
def test02_02AnyUriUrlencode(self): """Test URL encoding of a URI value resulting in a deny decision. """ self.pdp = PDP.fromPolicySource(XACML_CUSTOM_FUNCTION_TEST_FILEPATH, ReaderFactory) request = self._createRequestCtx(self.__class__.RESOURCE4_ID, subjectRoles=('role1',)) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: self.failIf(result.decision != Decision.DENY, "Expecting Deny decision")
def test02_01UrlStringConcatenate2Values(self): """Test concatenation of URI and 1 string value resulting in permit decision. """ self.pdp = PDP.fromPolicySource(XACML_CONCATENATE_TEST_FILEPATH, ReaderFactory) request = self._createRequestCtx(self.__class__.RESOURCE5_ID, subjectRoles=('role1',)) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: self.failIf(result.decision != Decision.PERMIT, "Expecting Permit decision")
def get_pdp(self, resource_id): if self.policy_decision_point.has_key(resource_id): return self.policy_decision_point[resource_id] #If a PDP does not exist for this resource - then return default. if self.default_pdp is None: #Loads a blank policy set as the default or an unknown resource_policy self.default_pdp = PDP.fromPolicySource( path.join(THIS_DIR, XACML_EMPTY_POLICY_FILENAME), ReaderFactory) return self.default_pdp
def set_resource_policy_rules(self, resource_key, policy_list): log.debug("Loading policies for resource: %s" % resource_key) self.clear_resource_policy(resource_key) if not policy_list: self.resource_policy_decision_point[resource_key] = None return # Create a new PDP object for the resource rules_text = self._get_rules_text(policy_list) input_source = StringIO(self.create_resource_policy_from_rules(resource_key, rules_text)) self.resource_policy_decision_point[resource_key] = PDP.fromPolicySource(input_source, ReaderFactory)
def set_service_policy_rules(self, service_name, policy_list): log.debug("Loading policies for service: %s" % service_name) self.clear_service_policy(service_name) if not policy_list: self.service_policy_decision_point[service_name] = None return # Create a new PDP object for the service rules_text = self._get_rules_text(policy_list) input_source = StringIO(self.create_policy_from_rules(service_name, rules_text)) self.service_policy_decision_point[service_name] = PDP.fromPolicySource(input_source, ReaderFactory)
def load_service_policy_rules(self, service_name, rules_text): if not rules_text and not self.service_policy_decision_point.has_key(service_name): return log.debug("Loading policies for service: %s" % service_name) self.clear_service_policy(service_name) service_rule_set = self.common_service_rules + rules_text #Simply create a new PDP object for the service input_source = StringIO(self.create_policy_from_rules(service_name, service_rule_set)) self.service_policy_decision_point[service_name] = PDP.fromPolicySource(input_source, ReaderFactory)
def load_resource_policy_rules(self, resource_key, rules_text): if not rules_text and not self.resource_policy_decision_point.has_key( resource_key): return log.info("Loading policies for resource: %s" % resource_key) self.clear_resource_policy(resource_key) #Simply create a new PDP object for the service input_source = StringIO( self.create_policy_from_rules(resource_key, rules_text)) self.resource_policy_decision_point[ resource_key] = PDP.fromPolicySource(input_source, ReaderFactory)
def test06ExecuteConditionPermit(self): self.pdp = PDP.fromPolicySource(XACML_ATTRIBUTESELECTOR3_FILEPATH, ReaderFactory) resourceContent = self._make_resource_content_element( self.__class__.RESOURCE_CONTENT_EXECUTE) request = self._createRequestCtx( self.__class__.PUBLIC_RESOURCE_ID, resourceContent=resourceContent) request.elem = RequestElementTree.toXML(request) request.attributeSelector = EtreeXPathSelector(request.elem) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: self.failIf(result.decision != Decision.PERMIT, "Expecting permit decision")
def test01NotApplicable(self): self.pdp = PDP.fromPolicySource(XACML_ATTRIBUTESELECTOR1_FILEPATH, ReaderFactory) resourceContent = self._make_resource_content_element( self.__class__.RESOURCE_CONTENT_VERSION_100) request = self._createRequestCtx( self.__class__.NOT_APPLICABLE_RESOURCE_ID, resourceContent=resourceContent) request.elem = RequestElementTree.toXML(request) request.attributeSelector = EtreeXPathSelector(request.elem) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: self.failIf(result.decision != Decision.NOT_APPLICABLE, "Expecting not applicable decision")
def load(self): """Load Policy file, mapping file and extensions functions. In each case load only if they're set. """ # This must be called first before the policy is loaded so that any # new custom types are added before a parse is attempted. if self.xacmlExtFunc: for fn in self.xacmlExtFunc: fn() if self.policyFilePath: self.pdp = PDP.fromPolicySource(self.policyFilePath, XacmlPolicyReaderFactory) if self.pip.mappingFilePath: self.pip.readMappingFile()
def load_service_policy_rules(self, service_name, rules_text): if not rules_text and not self.service_policy_decision_point.has_key( service_name): return log.info("Loading policies for service: %s" % service_name) self.clear_service_policy(service_name) service_rule_set = self.common_service_rules + rules_text #Simply create a new PDP object for the service input_source = StringIO( self.create_policy_from_rules(service_name, service_rule_set)) self.service_policy_decision_point[ service_name] = PDP.fromPolicySource(input_source, ReaderFactory)
def setUp(self): """Use ESG sample policy""" # Add new type AttributeValueClassFactory.addClass('urn:grouprole', GroupRoleAttributeValue) # Add new parser for this type DataTypeReaderClassFactory.addReader('urn:grouprole', ETreeGroupRoleDataTypeReader) # Add extra matching and bag functions functionMap['urn:grouprole-bag'] = GroupRoleBag functionMap['urn:grouprole-at-least-one-member-of' ] = GroupRoleAtLeastOneMemberOf # Example policy with custom attribute value type used with ESGF self.pdp = PDP.fromPolicySource(XACML_ESGFTEST1_FILEPATH, ReaderFactory)
def test04Indeterminate(self): '''This should result in an indeterminate decision because the policy includes an AttributeSelector with MustBePresent="true", whereas the request context path is not found in the request XML. ''' self.pdp = PDP.fromPolicySource(XACML_ATTRIBUTESELECTOR1_FILEPATH, ReaderFactory) resourceContent = self._make_resource_content_element( self.__class__.RESOURCE_CONTENT_NO_VERSION) request = self._createRequestCtx( self.__class__.PUBLIC_RESOURCE_ID, resourceContent=resourceContent) request.elem = RequestElementTree.toXML(request) request.attributeSelector = EtreeXPathSelector(request.elem) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: self.failIf(result.decision != Decision.INDETERMINATE, "Expecting indeterminate decision")
def test10SelectAttributeDeny(self): self.pdp = PDP.fromPolicySource(XACML_ATTRIBUTESELECTOR6_FILEPATH, ReaderFactory) resourceContent = self._make_resource_content_element( self.__class__.RESOURCE_CONTENT_EXECUTE) request = self._createRequestCtx( self.__class__.PUBLIC_RESOURCE_ID, resourceContent=resourceContent) request.elem = RequestElementTree.toXML(request) request.attributeSelector = EtreeXPathSelector(request.elem) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: if Config.use_lxml: self.failIf(result.decision != Decision.DENY, "Expecting deny decision") else: self.failIf(result.decision != Decision.INDETERMINATE, "Expecting indeterminate decision")
def initialise(self, prefix='', **kw): '''Initialise object from keyword settings :type prefix: basestring :param prefix: prefix for configuration items :type kw: dict :param kw: configuration settings dictionary :raise SamlPepFilterConfigError: missing option setting(s) ''' # Parse other options for name in SamlPepFilter.PARAM_NAMES: paramName = prefix + name value = kw.get(paramName) if value is not None: setattr(self, name, value) # All but the local policy settings are manadatory elif name not in self.__class__.OPTIONAL_PARAM_NAMES: raise SamlPepFilterConfigError('Missing option %r' % paramName) # Parse authorisation decision query options - first the bindings i.e. # the connection specific settings query_binding_prefix = prefix + \ self.__class__.AUTHZ_DECISION_QUERY_BINDING_PARAMS_PREFIX self.client_binding.parseKeywords(prefix=query_binding_prefix, **kw) # ... next set constants to do with the authorisation decision queries # that will be made. Settings such as the resource URI and principle # (user being queried for) are set on a call by call basis query_prefix = prefix + \ self.__class__.AUTHZ_DECISION_QUERY_PARAMS_PREFIX self.client_query = AuthzDecisionQueryFactory.from_kw( prefix=query_prefix, **kw) # Initialise the local PDP if self.localPolicyFilePath: self.__localPdp = PDP.fromPolicySource(self.localPolicyFilePath, XacmlPolicyReaderFactory)
def test08ExecuteLxmlPermit(self): # Test with condition in XPath expression - this will only return a # permit decision when using lxml self.pdp = PDP.fromPolicySource(XACML_ATTRIBUTESELECTOR4_FILEPATH, ReaderFactory) resourceContent = self._make_resource_content_element( self.__class__.RESOURCE_CONTENT_EXECUTE) request = self._createRequestCtx( self.__class__.PUBLIC_RESOURCE_ID, resourceContent=resourceContent) request.elem = RequestElementTree.toXML(request) request.attributeSelector = EtreeXPathSelector(request.elem) response = self.pdp.evaluate(request) self.failIf(response is None, "Null response") for result in response.results: if Config.use_lxml: self.failIf(result.decision != Decision.PERMIT, "Expecting permit decision") else: log.debug("Using ElementTree: dependent on the version, this " "test may result in an indeterminate decision. " "result.decision = %s" % result.decision)
class XacmlDynamicPolicyTestCase(unittest.TestCase): """Test Dynamic creation of policy and rules from code API instead of XML policy file""" attributeValueClassFactory = AttributeValueClassFactory() def _create_policy(self): self.policy = Policy() self.policy.policyId = 'Dynamic Policy Test' self.policy.ruleCombiningAlgId = \ 'urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:permit-overrides' # Add top-level target - determines an overall match for this policy self.policy.target = Target() # Match based on resource - add a resource match to the target resource = Resource() resource_match = ResourceMatch() resource_match.matchId = "urn:oasis:names:tc:xacml:2.0:function:anyURI-regexp-match" resource_match.attributeValue = self.__class__.attributeValueClassFactory( "http://www.w3.org/2001/XMLSchema#anyURI")() resource_match.attributeValue.value = '^http://localhost/.*' resource_match.attributeDesignator = ResourceAttributeDesignator() resource_match.attributeDesignator.attributeId = "urn:oasis:names:tc:xacml:1.0:resource:resource-id" resource_match.attributeDesignator.dataType = "http://www.w3.org/2001/XMLSchema#anyURI" resource.matches.append(resource_match) self.policy.target.resources.append(resource) # Add rules denyall_rule = Rule() denyall_rule.id = 'Deny all rule' denyall_rule.effect = Effect.DENY self.policy.rules.append(denyall_rule) singlerole_rule = Rule() singlerole_rule.id = 'dataset1 rule' singlerole_rule.effect = Effect.PERMIT singlerole_rule.target = Target() resource_match1 = ResourceMatch() resource_match1.matchId = "urn:oasis:names:tc:xacml:2.0:function:anyURI-regexp-match" resource_match1.attributeValue = self.__class__.attributeValueClassFactory( "http://www.w3.org/2001/XMLSchema#anyURI")() resource_match1.attributeValue.value = '^http://localhost/dataset1/.*$' resource_match1.attributeDesignator = ResourceAttributeDesignator() resource_match1.attributeDesignator.attributeId = "urn:oasis:names:tc:xacml:1.0:resource:resource-id" resource_match1.attributeDesignator.dataType = "http://www.w3.org/2001/XMLSchema#anyURI" resource1 = Resource() resource1.matches.append(resource_match1) singlerole_rule.target.resources.append(resource1) subject_match1 = SubjectMatch() subject_match1.matchId = "urn:oasis:names:tc:xacml:1.0:function:string-equal" subject_match1.attributeValue = self.__class__.attributeValueClassFactory( "http://www.w3.org/2001/XMLSchema#string")() subject_match1.attributeValue.value = 'staff' subject_match1.attributeDesignator = SubjectAttributeDesignator() subject_match1.attributeDesignator.attributeId = ROLE_ATTRIBUTE_ID subject_match1.attributeDesignator.dataType = "http://www.w3.org/2001/XMLSchema#string" subject1 = Subject() subject1.matches.append(subject_match1) singlerole_rule.target.subjects.append(subject1) self.policy.rules.append(singlerole_rule) @staticmethod def _create_request_ctx(resourceId, includeSubject=True, subjectId=SUBJECT_ID, subjectRoles=None, roleAttributeId=ROLE_ATTRIBUTE_ID, action='read', resourceContent=None): """Create an example XACML Request Context for tests""" if subjectRoles is None: subjectRoles = ('staff',) request = Request() if includeSubject: subject = CtxSubject() openidSubjectAttribute = Attribute() openidSubjectAttribute.attributeId = "urn:esg:openid" openidSubjectAttribute.dataType = AnyUriAttributeValue.IDENTIFIER openidSubjectAttribute.attributeValues.append( AnyUriAttributeValue()) openidSubjectAttribute.attributeValues[-1].value = subjectId subject.attributes.append(openidSubjectAttribute) for role in subjectRoles: roleAttribute = Attribute() roleAttribute.attributeId = roleAttributeId roleAttribute.dataType = StringAttributeValue.IDENTIFIER roleAttribute.attributeValues.append(StringAttributeValue()) roleAttribute.attributeValues[-1].value = role subject.attributes.append(roleAttribute) request.subjects.append(subject) resource = ResourceCtx() resourceAttribute = Attribute() resource.attributes.append(resourceAttribute) resourceAttribute.attributeId = Identifiers.Resource.RESOURCE_ID resourceAttribute.dataType = AnyUriAttributeValue.IDENTIFIER resourceAttribute.attributeValues.append(AnyUriAttributeValue()) resourceAttribute.attributeValues[-1].value = resourceId resource.resourceContent = resourceContent request.resources.append(resource) request.action = Action() actionAttribute = Attribute() request.action.attributes.append(actionAttribute) actionAttribute.attributeId = Identifiers.Action.ACTION_ID actionAttribute.dataType = StringAttributeValue.IDENTIFIER actionAttribute.attributeValues.append(StringAttributeValue()) actionAttribute.attributeValues[-1].value = action request.environment = Environment() return request def _create_pdp(self): self._create_policy() self.pdp = PDP(policy=self.policy) def test01_create_policy(self): self._create_policy() def test02_create_pdp(self): self._create_pdp() def test03_test_rule(self): self._create_pdp() request = self._create_request_ctx('http://localhost/dataset1/my.nc', subjectId='http://me.openid.ac.uk', subjectRoles=('staff',)) response = self.pdp.evaluate(request) for result in response.results: self.failIf(result.decision != Decision.PERMIT, "Expecting Permit decision")
def _create_pdp(self): self._create_policy() self.pdp = PDP(policy=self.policy)
def setUp(self): print "Setting up" self.pdp = PDP.fromPolicySource(self.__class__.XACML_FILEPATH, ReaderFactory) print "Setup complete"
def get_empty_pdp(self): policy_set = self.create_policy_from_rules(EMPTY_POLICY_ID, "") input_source = StringIO(policy_set) pdp = PDP.fromPolicySource(input_source, ReaderFactory) return pdp
def _createPDPfromNdgTest1Policy(): """Create PDP from NDG test policy file""" pdp = PDP.fromPolicySource(XACML_NDGTEST1_FILEPATH, ReaderFactory) return pdp