use of oasis.names.tc.xacml._3_0.core.schema.wd_17.Policy in project core by authzforce.
the class MongoDbPolicyProvider method getPolicy.
@Override
public StaticTopLevelPolicyElementEvaluator getPolicy(final String policyId, final Optional<PolicyVersionPatterns> policyPolicyVersionPatterns) throws IndeterminateEvaluationException {
/*
* TODO: use a policy cache and check it before requesting the database.
*/
final PolicyQueryResult xmlParsingResult = getJaxbPolicyElement(XACML3_POLICY_TYPE_ID, policyId, policyPolicyVersionPatterns);
if (xmlParsingResult == null) {
return null;
}
final PolicyPojo policyPOJO = xmlParsingResult.policyPojo;
final Object jaxbPolicyOrPolicySetObj = xmlParsingResult.resultJaxbObj;
final Map<String, String> nsPrefixUriMap = xmlParsingResult.xmlnsToPrefixMap;
if (!(jaxbPolicyOrPolicySetObj instanceof Policy)) {
throw new IndeterminateEvaluationException("PolicyProvider " + id + ": 'content' of the policy document " + policyPOJO + " retrieved from database is not consistent with its 'type' (expected: Policy). Actual content type: " + jaxbPolicyOrPolicySetObj.getClass() + " (corrupted database?).", XacmlStatusCode.PROCESSING_ERROR.value());
}
final Policy jaxbPolicy = (Policy) jaxbPolicyOrPolicySetObj;
final String contentPolicyId = jaxbPolicy.getPolicyId();
if (!contentPolicyId.equals(policyPOJO.getId())) {
throw new IndeterminateEvaluationException("PolicyProvider " + id + ": PolicyId in 'content' of the policy document " + policyPOJO + " retrieved from database is not consistent with 'id'. Actual PolicyId: " + contentPolicyId + " (corrupted database?).", XacmlStatusCode.PROCESSING_ERROR.value());
}
final String contentPolicyVersion = jaxbPolicy.getVersion();
if (!contentPolicyVersion.equals(policyPOJO.getVersion())) {
throw new IndeterminateEvaluationException("PolicyProvider " + id + ": Version in 'content' of the policy document " + policyPOJO + " retrieved from database is not consistent with 'version'. Actual Version: " + contentPolicyVersion + " (corrupted database?).", XacmlStatusCode.PROCESSING_ERROR.value());
}
try {
/*
XPath compiler shall be initialized in PolicyEvaluators#getInstance(...) based on PolicyDefaults/XPathVersion if present
*/
return PolicyEvaluators.getInstance(jaxbPolicy, expressionFactory, combiningAlgRegistry, Optional.empty(), nsPrefixUriMap);
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid Policy in 'content' of the policy document " + policyPOJO + " retrieved from database", e);
}
}
use of oasis.names.tc.xacml._3_0.core.schema.wd_17.Policy in project core by authzforce.
the class PdpGetStaticApplicablePoliciesTest method test.
@Test
public void test() throws IllegalArgumentException, IOException, URISyntaxException, JAXBException {
final String testResourceLocationPrefix = TEST_RESOURCES_DIRECTORY_LOCATION + "/";
/*
* Policies
*
* If there is a "$TEST_DIR/$POLICIES_DIR_NAME" directory, then load all policies from there, including root policy from "$TEST_DIR/$POLICIES_DIR_NAME/$ROOT_POLICY_FILENAME" Else load only the
* root policy from "$TEST_DIR/$ROOT_POLICY_FILENAME"
*/
final Path policiesDir = Paths.get(testResourceLocationPrefix + XacmlXmlPdpTest.POLICIES_DIR_NAME);
final Optional<Path> optPoliciesDir;
final Path rootPolicyFile;
if (Files.isDirectory(policiesDir)) {
optPoliciesDir = Optional.of(policiesDir);
rootPolicyFile = policiesDir.resolve(XacmlXmlPdpTest.ROOT_POLICY_FILENAME);
} else {
optPoliciesDir = Optional.empty();
rootPolicyFile = Paths.get(testResourceLocationPrefix + XacmlXmlPdpTest.ROOT_POLICY_FILENAME);
}
/*
* Create PDP
*/
final PdpEngineConfiguration pdpEngineConf = optPoliciesDir.isPresent() ? TestUtils.newPdpEngineConfiguration(TestUtils.getPolicyRef(rootPolicyFile), optPoliciesDir.get(), false, Optional.empty(), null, null) : TestUtils.newPdpEngineConfiguration(rootPolicyFile, false, Optional.empty(), null, null);
try (final PdpEngineInoutAdapter<Request, Response> pdp = PdpEngineAdapters.newXacmlJaxbInoutAdapter(pdpEngineConf)) {
final Iterable<PrimaryPolicyMetadata> staticApplicablePolicies = pdp.getApplicablePolicies();
assertNotNull("One of the policies may not be statically resolved", staticApplicablePolicies);
final Iterator<PrimaryPolicyMetadata> staticApplicablePoliciesIterator = pdp.getApplicablePolicies().iterator();
assertTrue("No root policy in PDP's applicable policies (statically resolved)", staticApplicablePoliciesIterator.hasNext());
assertEquals("Invalid root policy in PDP's applicable policies (statically resolved)", ROOT_POLICYSET_METADATA, staticApplicablePoliciesIterator.next());
for (final PrimaryPolicyMetadata expectedRefPolicyMeta : REF_POLICYSET_METADATA_SET) {
assertTrue("No (more) referenced policy in PDP's applicable policies (statically resolved) although expected", staticApplicablePoliciesIterator.hasNext());
assertEquals("Invalid referenced policy in PDP's applicable policies (statically resolved)", expectedRefPolicyMeta, staticApplicablePoliciesIterator.next());
}
}
}
use of oasis.names.tc.xacml._3_0.core.schema.wd_17.Policy in project core by authzforce.
the class CoreStaticPolicyProvider method getInstance.
/**
* Creates an instance from policy locations
*
* @param providerParams location of Policy(Set) elements (JAXB) to be parsed for future reference by Policy(Set)IdReferences
* @param ignoreOldPolicyVersions for any given policy ID, ignore all versions except the last one if there are multiple versions of the policy
* @param xacmlParserFactory XACML parser factory for parsing any XACML Policy(Set)
* @param maxPolicySetRefDepth maximum allowed depth of PolicySet reference chain (via PolicySetIdReference): PolicySet1 -> PolicySet2 -> ...; a strictly negative value means no limit
* @param combiningAlgRegistry registry of policy/rule combining algorithms
* @param expressionFactory Expression factory for parsing Expressions used in the policy(set)
* @param otherPolicyProvider other (supporting) policy provider, used to resolve policy references that do not match any of {@code providerParams}
* @return instance of this class
* @throws java.lang.IllegalArgumentException if {@code policyURLs == null || policyURLs.length == 0 || xacmlParserFactory == null || expressionFactory == null || combiningAlgRegistry == null}; or one of {@code policyURLs} is
* null or is not a valid XACML Policy(Set) or conflicts with another because it has same Policy(Set)Id and Version. Beware that the Policy(Set)Issuer is ignored from this check!
*/
public static CoreStaticPolicyProvider getInstance(final List<StaticPolicyProviderInParam> providerParams, final boolean ignoreOldPolicyVersions, final XmlnsFilteringParserFactory xacmlParserFactory, final int maxPolicySetRefDepth, final ExpressionFactory expressionFactory, final CombiningAlgRegistry combiningAlgRegistry, final Optional<StaticPolicyProvider> otherPolicyProvider) throws IllegalArgumentException {
if (providerParams == null || providerParams.isEmpty()) {
throw ILLEGAL_POLICY_URLS_ARGUMENT_EXCEPTION;
}
if (xacmlParserFactory == null) {
throw ILLEGAL_XACML_PARSER_FACTORY_ARGUMENT_EXCEPTION;
}
if (expressionFactory == null) {
throw ILLEGAL_EXPRESSION_FACTORY_ARGUMENT_EXCEPTION;
}
if (combiningAlgRegistry == null) {
throw ILLEGAL_COMBINING_ALG_REGISTRY_ARGUMENT_EXCEPTION;
}
final XmlnsFilteringParser xacmlParser;
try {
xacmlParser = xacmlParserFactory.getInstance();
} catch (final JAXBException e) {
throw new IllegalArgumentException("Failed to create JAXB unmarshaller for XML Policy(Set)", e);
}
final Table<String, PolicyVersion, StaticTopLevelPolicyElementEvaluator> updatablePolicyTable = HashBasedTable.create();
final Table<String, PolicyVersion, PolicyWithNamespaces<PolicySet>> updatablePolicySetTable = HashBasedTable.create();
int providerParamIndex = 0;
for (final StaticPolicyProviderInParam providerParam : providerParams) {
if (providerParam == null) {
throw new IllegalArgumentException("Policy provider parameter #" + providerParamIndex + " undefined");
}
final Object jaxbPolicyOrPolicySetObj;
if (providerParam instanceof XacmlPolicyParam) {
jaxbPolicyOrPolicySetObj = ((XacmlPolicyParam) providerParam).policy;
} else {
final URL policyURL = ((PolicyLocationParam) providerParam).policyLocation;
try {
jaxbPolicyOrPolicySetObj = xacmlParser.parse(policyURL);
} catch (final JAXBException e) {
throw new IllegalArgumentException("Failed to unmarshall Policy(Set) XML document from policy location: " + policyURL, e);
}
}
final ImmutableMap<String, String> nsPrefixUriMap = xacmlParser.getNamespacePrefixUriMap();
if (jaxbPolicyOrPolicySetObj instanceof Policy) {
final Policy jaxbPolicy = (Policy) jaxbPolicyOrPolicySetObj;
final String policyId = jaxbPolicy.getPolicyId();
final String policyVersionStr = jaxbPolicy.getVersion();
final PolicyVersion policyVersion = new PolicyVersion(policyVersionStr);
if (ignoreOldPolicyVersions) {
final Map<PolicyVersion, StaticTopLevelPolicyElementEvaluator> updatablePolicyVersions = updatablePolicyTable.row(policyId);
// Empty map returned if no mappings
final boolean isOld = updatablePolicyVersions.keySet().parallelStream().anyMatch(v -> policyVersion.compareTo(v) <= 0);
if (isOld) {
// skip
continue;
}
/*
* Else replace/overwrite with this new version (make sure it is the only one), so empty the row first
*/
updatablePolicyVersions.clear();
}
final StaticTopLevelPolicyElementEvaluator policyEvaluator;
try {
/*
XPath compiler shall be initialized in PolicyEvaluators#getInstance(...) based on PolicyDefaults/XPathVersion if present
*/
policyEvaluator = PolicyEvaluators.getInstance(jaxbPolicy, expressionFactory, combiningAlgRegistry, Optional.empty(), nsPrefixUriMap);
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid Policy with PolicyId=" + policyId + ", Version=" + policyVersionStr, e);
}
final StaticTopLevelPolicyElementEvaluator previousValue = updatablePolicyTable.put(policyId, policyVersion, policyEvaluator);
if (previousValue != null) {
throw new IllegalArgumentException("Policy conflict: two policies with same PolicyId=" + policyId + ", Version=" + policyVersionStr);
}
} else if (jaxbPolicyOrPolicySetObj instanceof PolicySet) {
final PolicySet jaxbPolicySet = (PolicySet) jaxbPolicyOrPolicySetObj;
final String policyId = jaxbPolicySet.getPolicySetId();
final String policyVersionStr = jaxbPolicySet.getVersion();
final PolicyVersion policyVersion = new PolicyVersion(policyVersionStr);
if (ignoreOldPolicyVersions) {
final Map<PolicyVersion, PolicyWithNamespaces<PolicySet>> updatablePolicyVersions = updatablePolicySetTable.row(policyId);
// Empty map returned if no mapping
final boolean isOld = updatablePolicyVersions.keySet().parallelStream().anyMatch(v -> policyVersion.compareTo(v) <= 0);
if (isOld) {
// skip
continue;
}
/*
* Else replace/overwrite with this new version (make sure it is the only one), so empty the row first
*/
updatablePolicyVersions.clear();
}
final PolicyWithNamespaces<PolicySet> previousValue = updatablePolicySetTable.put(policyId, policyVersion, new PolicyWithNamespaces<>(jaxbPolicySet, nsPrefixUriMap));
if (previousValue != null) {
throw new IllegalArgumentException("Policy conflict: two PolicySets with same PolicySetId=" + policyId + ", Version=" + policyVersionStr);
}
/*
* PolicySets cannot be parsed before we have collected them all, because each PolicySet may refer to others via PolicySetIdReferences
*/
} else {
throw new IllegalArgumentException("Unexpected element found as root of the policy document: " + jaxbPolicyOrPolicySetObj.getClass().getSimpleName());
}
providerParamIndex++;
}
final PolicyMap<StaticTopLevelPolicyElementEvaluator> policyMap = new PolicyMap<>(updatablePolicyTable.rowMap());
final PolicyMap<PolicyWithNamespaces<PolicySet>> policySetMap = new PolicyMap<>(updatablePolicySetTable.rowMap());
return new CoreStaticPolicyProvider(policyMap, policySetMap, maxPolicySetRefDepth, expressionFactory, combiningAlgRegistry, otherPolicyProvider);
}
use of oasis.names.tc.xacml._3_0.core.schema.wd_17.Policy in project core by authzforce.
the class CoreStaticPolicyProvider method getInstance.
/**
* Creates an instance from XACML/JAXB Policy(Set) elements
*
* @param jaxbPolicies XACML Policies
* @param jaxbPolicySets XACML PolicySets
* @param maxPolicySetRefDepth maximum allowed depth of PolicySet reference chain (via PolicySetIdReference): PolicySet1 -> PolicySet2 -> ...
* @param combiningAlgRegistry registry of policy/rule combining algorithms
* @param expressionFactory Expression factory for parsing Expressions used in the policy(set)
* @param otherPolicyProvider other (supporting) policy provider, used to resolve policy references that match neither {@code jaxbPolicies} nor {@code jaxbPolicySets}
* @return instance of this module
* @throws java.lang.IllegalArgumentException if both {@code jaxbPolicies} and {@code jaxbPolicySets} are null/empty, or expressionFactory/combiningAlgRegistry undefined; or one of the Policy(Set)s is not valid or conflicts
* with another because it has same Policy(Set)Id and Version.
*/
public static CoreStaticPolicyProvider getInstance(final List<PolicyWithNamespaces<Policy>> jaxbPolicies, final List<PolicyWithNamespaces<PolicySet>> jaxbPolicySets, final int maxPolicySetRefDepth, final ExpressionFactory expressionFactory, final CombiningAlgRegistry combiningAlgRegistry, final Optional<StaticPolicyProvider> otherPolicyProvider) throws IllegalArgumentException {
if ((jaxbPolicies == null || jaxbPolicies.isEmpty()) && (jaxbPolicySets == null || jaxbPolicySets.isEmpty())) {
throw NO_POLICY_ARG_EXCEPTION;
}
if (expressionFactory == null) {
throw ILLEGAL_EXPRESSION_FACTORY_ARGUMENT_EXCEPTION;
}
if (combiningAlgRegistry == null) {
throw ILLEGAL_COMBINING_ALG_REGISTRY_ARGUMENT_EXCEPTION;
}
final PolicyMap<StaticTopLevelPolicyElementEvaluator> policyMap;
if (jaxbPolicies == null) {
policyMap = new PolicyMap<>(Collections.emptyMap());
} else {
final Table<String, PolicyVersion, StaticTopLevelPolicyElementEvaluator> updatablePolicyTable = HashBasedTable.create();
for (final PolicyWithNamespaces<Policy> jaxbPolicyWithNs : jaxbPolicies) {
final Policy jaxbPolicy = jaxbPolicyWithNs.policy;
final String policyId = jaxbPolicy.getPolicyId();
final String policyVersion = jaxbPolicy.getVersion();
final StaticTopLevelPolicyElementEvaluator policyEvaluator;
try {
/*
XPath compiler shall be initialized in PolicyEvaluators#getInstance(...) based on PolicyDefaults/XPathVersion if present
*/
policyEvaluator = PolicyEvaluators.getInstance(jaxbPolicy, expressionFactory, combiningAlgRegistry, Optional.empty(), jaxbPolicyWithNs.nsPrefixUriMap);
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid Policy with PolicyId=" + policyId + ", Version=" + policyVersion, e);
}
final StaticTopLevelPolicyElementEvaluator previousValue = updatablePolicyTable.put(policyId, new PolicyVersion(policyVersion), policyEvaluator);
if (previousValue != null) {
throw new IllegalArgumentException("Policy conflict: two <Policy>s with same PolicyId=" + policyId + ", Version=" + policyVersion);
}
}
policyMap = new PolicyMap<>(updatablePolicyTable.rowMap());
}
final PolicyMap<PolicyWithNamespaces<PolicySet>> jaxbPolicySetMap;
if (jaxbPolicySets == null) {
jaxbPolicySetMap = new PolicyMap<>(Collections.emptyMap());
} else {
final Table<String, PolicyVersion, PolicyWithNamespaces<PolicySet>> updatablePolicySetTable = HashBasedTable.create();
for (final PolicyWithNamespaces<PolicySet> jaxbPolicySetWithNs : jaxbPolicySets) {
final PolicySet jaxbPolicySet = jaxbPolicySetWithNs.policy;
final String policyId = jaxbPolicySet.getPolicySetId();
final String policyVersion = jaxbPolicySet.getVersion();
// check if any version of the same policy exist in the map
final PolicyWithNamespaces<PolicySet> previousValue = updatablePolicySetTable.put(policyId, new PolicyVersion(policyVersion), jaxbPolicySetWithNs);
if (previousValue != null) {
throw new IllegalArgumentException("Policy conflict: two PolicySets with same PolicySetId=" + policyId + ", Version=" + policyVersion);
}
/*
* PolicySets cannot be parsed before we have collected them all, because each PolicySet may refer to others via PolicySetIdReferences
*/
}
jaxbPolicySetMap = new PolicyMap<>(updatablePolicySetTable.rowMap());
}
return new CoreStaticPolicyProvider(policyMap, jaxbPolicySetMap, maxPolicySetRefDepth, expressionFactory, combiningAlgRegistry, otherPolicyProvider);
}
use of oasis.names.tc.xacml._3_0.core.schema.wd_17.Policy in project java-bigqueryconnection by googleapis.
the class ConnectionServiceClientTest method getIamPolicyTest.
@Test
public void getIamPolicyTest() throws Exception {
Policy expectedResponse = Policy.newBuilder().setVersion(351608024).addAllBindings(new ArrayList<Binding>()).setEtag(ByteString.EMPTY).build();
mockConnectionService.addResponse(expectedResponse);
ResourceName resource = ConnectionName.of("[PROJECT]", "[LOCATION]", "[CONNECTION]");
GetPolicyOptions options = GetPolicyOptions.newBuilder().build();
Policy actualResponse = client.getIamPolicy(resource, options);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockConnectionService.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0));
Assert.assertEquals(resource.toString(), actualRequest.getResource());
Assert.assertEquals(options, actualRequest.getOptions());
Assert.assertTrue(channelProvider.isHeaderSent(ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
Aggregations