Search in sources :

Example 1 with XmlnsFilteringParser

use of org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser in project core by authzforce.

the class XacmlXmlPdpTest method test.

@Test
public void test() throws IllegalArgumentException, IOException, JAXBException {
    LOGGER.debug("******************************");
    LOGGER.debug("Starting PDP test of directory '{}'", testDirPath);
    final String testResourceLocationPrefix = testDirPath + "/";
    // Parse request
    final Request request;
    // if no Request file, it is just a static policy syntax error check
    final Path reqFilepath = Paths.get(testResourceLocationPrefix + REQUEST_FILENAME);
    final XmlnsFilteringParser unmarshaller = XACML_PARSER_FACTORY.getInstance();
    if (Files.exists(reqFilepath)) {
        request = TestUtils.createRequest(reqFilepath, unmarshaller);
        LOGGER.debug("XACML Request sent to the PDP: {}", request);
    } else {
        request = null;
        // do nothing except logging -> request = null
        LOGGER.debug("Request file '{}' does not exist -> Static policy syntax error check (Request/Response ignored)", reqFilepath);
    }
    /*
		 * 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 + POLICIES_DIR_NAME);
    final Optional<Path> optPoliciesDir;
    final Path rootPolicyFile;
    if (Files.isDirectory(policiesDir)) {
        optPoliciesDir = Optional.of(policiesDir);
        rootPolicyFile = policiesDir.resolve(ROOT_POLICY_FILENAME);
    } else {
        optPoliciesDir = Optional.empty();
        rootPolicyFile = Paths.get(testResourceLocationPrefix + ROOT_POLICY_FILENAME);
    }
    /*
		 * Create PDP
		 */
    PdpEngineInoutAdapter<Request, Response> pdp = null;
    final Path pdpConfFile = Paths.get(testResourceLocationPrefix + PDP_CONF_FILENAME);
    try {
        final PdpEngineConfiguration pdpEngineConf;
        if (Files.notExists(pdpConfFile)) {
            LOGGER.debug("No PDP configuration file found at location: '{}'. Using minimal PDP instead (returned by TestUtils.getPDPNewInstance(policy) ).", pdpConfFile);
            pdpEngineConf = optPoliciesDir.isPresent() ? TestUtils.newPdpEngineConfiguration(TestUtils.getPolicyRef(rootPolicyFile), optPoliciesDir.get(), false, Optional.empty(), null, null) : TestUtils.newPdpEngineConfiguration(rootPolicyFile, false, Optional.empty(), null, null);
        } else {
            /*
				 * PDP configuration filename found in test directory -> create PDP from it
				 */
            // final String pdpExtXsdLocation = testResourceLocationPrefix + PDP_EXTENSION_XSD_FILENAME;
            File pdpExtXsdFile = null;
            try {
                pdpExtXsdFile = ResourceUtils.getFile(PDP_EXTENSION_XSD_LOCATION);
            } catch (final FileNotFoundException e) {
                LOGGER.debug("No PDP extension configuration file '{}' found -> JAXB-bound PDP extensions not allowed.", PDP_EXTENSION_XSD_LOCATION);
            }
            try {
                /*
					 * Load the PDP configuration from the configuration, and optionally, the PDP extension XSD if this file exists, and the XML catalog required to resolve these extension XSDs
					 */
                pdpEngineConf = pdpExtXsdFile == null ? PdpEngineConfiguration.getInstance(pdpConfFile.toString()) : PdpEngineConfiguration.getInstance(pdpConfFile.toString(), XML_CATALOG_LOCATION, PDP_EXTENSION_XSD_LOCATION);
            } catch (final IOException e) {
                throw new RuntimeException("Error parsing PDP configuration from file '" + pdpConfFile + "' with extension XSD '" + PDP_EXTENSION_XSD_LOCATION + "' and XML catalog file '" + XML_CATALOG_LOCATION + "'", e);
            }
        }
        pdp = PdpEngineAdapters.newXacmlJaxbInoutAdapter(pdpEngineConf);
        if (request == null) {
            /*
				 * This is a policy syntax error check, and we didn't find the syntax error as expected
				 */
            Assert.fail("Failed to find syntax error as expected in policy(ies) located in directory: " + testDirPath);
        } else {
            // Parse expected response
            final Response expectedResponse = TestUtils.createResponse(Paths.get(testResourceLocationPrefix + EXPECTED_RESPONSE_FILENAME), unmarshaller);
            final Response response = pdp.evaluate(request, null);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("XACML Response received from the PDP: {}", TestUtils.printResponse(response));
            }
            TestUtils.assertNormalizedEquals(testResourceLocationPrefix, expectedResponse, response);
            LOGGER.debug("Finished PDP test of directory '{}'", testDirPath);
        }
    } catch (final IllegalArgumentException e) {
        // we found syntax error in policy
        if (request == null) {
            // this is a policy syntax error check, and we found the syntax error as
            // expected -> success
            LOGGER.debug("Successfully found syntax error as expected in policy(ies) located in directory: {}", testDirPath, e);
        } else {
            throw e;
        }
    } finally {
        if (pdp != null) {
            pdp.close();
        }
    }
}
Also used : XmlnsFilteringParser(org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser) PdpEngineConfiguration(org.ow2.authzforce.core.pdp.impl.PdpEngineConfiguration) Request(oasis.names.tc.xacml._3_0.core.schema.wd_17.Request) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Response(oasis.names.tc.xacml._3_0.core.schema.wd_17.Response) File(java.io.File) Test(org.junit.Test)

Example 2 with XmlnsFilteringParser

use of org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser in project core by authzforce.

the class MongoDbPolicyProviderTest method testPdpInstantiationWithMongoDBBasedPolicyProvider.

@Test
public void testPdpInstantiationWithMongoDBBasedPolicyProvider() throws IllegalArgumentException, IOException, JAXBException {
    final XmlnsFilteringParser xacmlParser = XacmlJaxbParsingUtils.getXacmlParserFactory(false).getInstance();
    final Request req = TestUtils.createRequest(Paths.get("target/test-classes/org/ow2/authzforce/core/pdp/testutil/test/request.xml"), xacmlParser);
    final Response expectedResp = TestUtils.createResponse(Paths.get("target/test-classes/org/ow2/authzforce/core/pdp/testutil/test/response.xml"), xacmlParser);
    final Response actualResp;
    try (final PdpEngineInoutAdapter<Request, Response> pdpEngine = PdpEngineAdapters.newXacmlJaxbInoutAdapter(PdpEngineConfiguration.getInstance("classpath:org/ow2/authzforce/core/pdp/testutil/test/pdp.xml", "classpath:catalog.xml", "classpath:pdp-ext.xsd"))) {
        actualResp = pdpEngine.evaluate(req);
    }
    TestUtils.assertNormalizedEquals("", expectedResp, actualResp);
}
Also used : Response(oasis.names.tc.xacml._3_0.core.schema.wd_17.Response) XmlnsFilteringParser(org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser) Request(oasis.names.tc.xacml._3_0.core.schema.wd_17.Request) XacmlXmlPdpTest(org.ow2.authzforce.core.pdp.testutil.XacmlXmlPdpTest)

Example 3 with XmlnsFilteringParser

use of org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser 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);
}
Also used : Policy(oasis.names.tc.xacml._3_0.core.schema.wd_17.Policy) java.util(java.util) org.ow2.authzforce.core.pdp.api.policy(org.ow2.authzforce.core.pdp.api.policy) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) HashBasedTable(com.google.common.collect.HashBasedTable) CombiningAlgRegistry(org.ow2.authzforce.core.pdp.api.combining.CombiningAlgRegistry) EnvironmentProperties(org.ow2.authzforce.core.pdp.api.EnvironmentProperties) Matcher(java.util.regex.Matcher) Policy(oasis.names.tc.xacml._3_0.core.schema.wd_17.Policy) Path(java.nio.file.Path) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) XmlnsFilteringParser(org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) IndeterminateEvaluationException(org.ow2.authzforce.core.pdp.api.IndeterminateEvaluationException) ResourceUtils(org.springframework.util.ResourceUtils) PolicySet(oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySet) Stream(java.util.stream.Stream) ExpressionFactory(org.ow2.authzforce.core.pdp.api.expression.ExpressionFactory) XmlnsFilteringParserFactory(org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParserFactory) Paths(java.nio.file.Paths) Entry(java.util.Map.Entry) Pattern(java.util.regex.Pattern) Table(com.google.common.collect.Table) URL(java.net.URL) PolicySet(oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySet) XmlnsFilteringParser(org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser) JAXBException(javax.xml.bind.JAXBException) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 4 with XmlnsFilteringParser

use of org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser in project core by authzforce.

the class ConformanceV3FromV2 method test.

@Test
public void test() throws Exception {
    LOGGER.debug("******************************");
    LOGGER.debug("Starting PDP test in directory: '{}'", testDirectoryPath);
    // Response file
    final XmlnsFilteringParser respUnmarshaller = xacmlParserFactory.getInstance();
    final Path expectedRespFilepath = testDirectoryPath.resolve(EXPECTED_RESPONSE_FILENAME_SUFFIX);
    // If no Response file, it is just a static policy or request syntax error check
    final Response expectedResponse;
    if (Files.exists(expectedRespFilepath)) {
        expectedResponse = TestUtils.createResponse(expectedRespFilepath, respUnmarshaller);
    } else {
        expectedResponse = null;
        // Do nothing except logging -> request = null
        LOGGER.debug("Response file '{}' does not exist -> Static Policy/Request syntax error check", expectedRespFilepath);
    }
    // Request file
    final XmlnsFilteringParser reqUnmarshaller = xacmlParserFactory.getInstance();
    final Path reqFilepath = testDirectoryPath.resolve(REQUEST_FILENAME_SUFFIX);
    // If no Request file, it is just a static policy syntax error check
    final Request request;
    if (Files.exists(reqFilepath)) {
        try {
            request = TestUtils.createRequest(reqFilepath, reqUnmarshaller);
        } catch (final JAXBException e) {
            // we found a syntax error in request
            if (expectedResponse == null) {
                // this is a Request syntax error check and we found the syntax error as
                // expected -> success
                LOGGER.debug("Successfully found syntax error as expected in Request located at: {}", reqFilepath);
                return;
            }
            // Unexpected error
            throw e;
        }
    } else {
        request = null;
        // do nothing except logging -> request = null
        LOGGER.debug("Request file '{}' does not exist -> Static policy syntax error check (Request/Response ignored)", reqFilepath);
    }
    /*
		 * Create PDP
		 */
    final PdpEngineConfiguration pdpEngineConf;
    final Path pdpConfFile = testDirectoryPath.resolve(PDP_CONF_FILENAME);
    if (Files.notExists(pdpConfFile)) {
        /*
			 * Policies directory. If it exists, root Policy file is expected to be in there. This is the case for IIE*** conformance tests
			 */
        final Path policiesDir = testDirectoryPath.resolve(POLICIES_DIRNAME_SUFFIX);
        /*
			Attribute Provider config
			 */
        final Path attributeProviderConfFile = testDirectoryPath.resolve(ATTRIBUTE_PROVIDER_FILENAME_SUFFIX);
        final Optional<Path> optAttributeProviderConfFile = Files.isRegularFile(attributeProviderConfFile) ? Optional.of(attributeProviderConfFile) : Optional.empty();
        try {
            if (Files.isDirectory(policiesDir)) {
                final Path rootPolicyFile = policiesDir.resolve(ROOT_POLICY_FILENAME_SUFFIX);
                pdpEngineConf = TestUtils.newPdpEngineConfiguration(TestUtils.getPolicyRef(rootPolicyFile), policiesDir, enableXPath, optAttributeProviderConfFile, this.reqFilterId, null);
            } else {
                final Path rootPolicyFile = testDirectoryPath.resolve(ROOT_POLICY_FILENAME_SUFFIX);
                pdpEngineConf = TestUtils.newPdpEngineConfiguration(rootPolicyFile, enableXPath, optAttributeProviderConfFile, this.reqFilterId, null);
            }
        } catch (final IllegalArgumentException e) {
            // we found syntax error in policy
            if (request == null) {
                // this is a policy syntax error check and we found the syntax error as
                // expected -> success
                LOGGER.debug("Successfully found syntax error as expected in policy(ies) with path: {}*", testDirectoryPath);
                return;
            }
            // Unexpected error
            throw e;
        }
    } else {
        /*
			 * PDP configuration filename found in test directory -> create PDP from it
			 */
        // final String pdpExtXsdLocation = testResourceLocationPrefix + PDP_EXTENSION_XSD_FILENAME;
        File pdpExtXsdFile = null;
        try {
            pdpExtXsdFile = ResourceUtils.getFile(PDP_EXTENSION_XSD_LOCATION);
        } catch (final FileNotFoundException e) {
            LOGGER.debug("No PDP extension configuration file '{}' found -> JAXB-bound PDP extensions not allowed.", PDP_EXTENSION_XSD_LOCATION);
        }
        try {
            /*
				 * Load the PDP configuration from the configuration, and optionally, the PDP extension XSD if this file exists, and the XML catalog required to resolve these extension XSDs
				 */
            pdpEngineConf = pdpExtXsdFile == null ? PdpEngineConfiguration.getInstance(pdpConfFile.toString()) : PdpEngineConfiguration.getInstance(pdpConfFile.toString(), XML_CATALOG_LOCATION, PDP_EXTENSION_XSD_LOCATION);
        } catch (final IOException e) {
            throw new RuntimeException("Error parsing PDP configuration from file '" + pdpConfFile + "' with extension XSD '" + PDP_EXTENSION_XSD_LOCATION + "' and XML catalog file '" + XML_CATALOG_LOCATION + "'", e);
        }
    }
    try (PdpEngineInoutAdapter<Request, Response> pdp = PdpEngineAdapters.newXacmlJaxbInoutAdapter(pdpEngineConf)) {
        if (request == null) {
            // this is a policy syntax error check and we didn't found the syntax error as
            // expected
            Assert.fail("Failed to find syntax error as expected in policy(ies)  with path: " + testDirectoryPath + "*");
        } else if (expectedResponse == null) {
            /*
				 * No expected response, so it is not a PDP evaluation test, but request or policy syntax error check. We got here, so request and policy OK. This is unexpected.
				 */
            Assert.fail("Missing response file '" + expectedRespFilepath + "' or failed to find syntax error as expected in either request located at '" + reqFilepath + "' or policy(ies) with path '" + testDirectoryPath + "*'");
        } else {
            // this is an evaluation test with request/response (not a policy syntax check)
            LOGGER.debug("Request that is sent to the PDP: {}", request);
            final Response actualResponse = pdp.evaluate(request, reqUnmarshaller.getNamespacePrefixUriMap());
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Response that is received from the PDP :  {}", TestUtils.printResponse(actualResponse));
            }
            TestUtils.assertNormalizedEquals("Test failed for directory " + testDirectoryPath, expectedResponse, actualResponse);
        }
    } catch (final IllegalArgumentException e) {
        // we found syntax error in policy
        if (request == null) {
            // this is a policy syntax error check and we found the syntax error as
            // expected -> success
            LOGGER.debug("Successfully found syntax error as expected in policy(ies) with path: {}*", testDirectoryPath);
            return;
        }
        // Unexpected error
        throw e;
    }
}
Also used : Path(java.nio.file.Path) XmlnsFilteringParser(org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser) PdpEngineConfiguration(org.ow2.authzforce.core.pdp.impl.PdpEngineConfiguration) JAXBException(javax.xml.bind.JAXBException) Request(oasis.names.tc.xacml._3_0.core.schema.wd_17.Request) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Response(oasis.names.tc.xacml._3_0.core.schema.wd_17.Response) File(java.io.File) Test(org.junit.Test)

Example 5 with XmlnsFilteringParser

use of org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser in project core by authzforce.

the class MongoDbPolicyProvider method getJaxbPolicyElement.

private PolicyQueryResult getJaxbPolicyElement(final String policyTypeId, final String policyId, final Optional<PolicyVersionPatterns> policyPolicyVersionPatterns) throws IndeterminateEvaluationException {
    final Optional<PolicyVersionPattern> versionPattern;
    if (policyPolicyVersionPatterns.isPresent()) {
        /*
			 * TODO: the following code does not support LatestVersion and EarliestVersion patterns. Beware that comparing versions (XACML VersionType) to each other - and also comparing literal
			 * version to version pattern (XACML VersionMatchType) - is NOT the same as sorting strings in lexicographical order or matching standard regular expressions. Indeed, in XACML, a version
			 * (VersionType) is a sequence/array of decimal numbers actually, therefore it relies on number comparison; and version pattern use wildcard characters '*' and '+' with a special meaning
			 * that is different from PCRE or other regex engines.
			 */
        final PolicyVersionPatterns nonNullPolicyPolicyVersionPatterns = policyPolicyVersionPatterns.get();
        if (nonNullPolicyPolicyVersionPatterns.getEarliestVersionPattern().isPresent()) {
            throw new IllegalArgumentException("PolicyProvider '" + id + "': EarliestVersion in input policy reference is not supported");
        }
        if (nonNullPolicyPolicyVersionPatterns.getLatestVersionPattern().isPresent()) {
            throw new IllegalArgumentException("PolicyProvider '" + id + "': LatestVersion in input policy reference is not supported");
        }
        versionPattern = nonNullPolicyPolicyVersionPatterns.getVersionPattern();
    } else {
        versionPattern = Optional.empty();
    }
    final PolicyPojo policyPOJO;
    /*
		 * TODO: the following code will get any policy version that matches the policy type, id and optional VersionMatch. It may be smarter to always get the latest if there are multiple matches.
		 * But this adds complexity as mentioned in previous TODO comment.
		 */
    if (versionPattern.isPresent()) {
        final PolicyVersionPattern nonNullVersionPattern = versionPattern.get();
        final PolicyVersion versionLiteral = nonNullVersionPattern.toLiteral();
        if (versionLiteral != null) {
            policyPOJO = policyCollection.findOne("{type: #, id: #, version: #}", policyTypeId, policyId, versionLiteral.toString()).as(PolicyPojo.class);
        } else {
            /*
				 * versionPattern is not a literal/constant version (contains wildcard '*' or '+') -> convert to PCRE regex for MongoDB server-side evaluation
				 */
            final String regex = "^" + nonNullVersionPattern.toRegex() + "$";
            policyPOJO = policyCollection.findOne("{type: #, id: #, version: { $regex: # }}", policyTypeId, policyId, regex).as(PolicyPojo.class);
        }
    } else {
        // no version pattern specified
        policyPOJO = policyCollection.findOne("{type: #, id: #}", policyTypeId, policyId).as(PolicyPojo.class);
    }
    if (policyPOJO == null) {
        return null;
    }
    final XmlnsFilteringParser xacmlParser;
    try {
        xacmlParser = xacmlParserFactory.getInstance();
    } catch (final JAXBException e) {
        throw new IndeterminateEvaluationException(jaxbUnmarshallerCreationErrStatus, e);
    }
    final InputSource xmlInputSrc = new InputSource(new StringReader(policyPOJO.getContent()));
    final Object resultJaxbObj;
    try {
        /*
			 * TODO: support more efficient formats of XML content, e.g. gzipped XML, Fast Infoset, EXI.
			 */
        resultJaxbObj = xacmlParser.parse(xmlInputSrc);
    } catch (final JAXBException e) {
        throw new IndeterminateEvaluationException("PolicyProvider " + id + ": failed to parse Policy(Set) XML document from 'content' value of the policy document " + policyPOJO + " retrieved from database", XacmlStatusCode.PROCESSING_ERROR.value(), e);
    }
    return new PolicyQueryResult(policyPOJO, resultJaxbObj, xacmlParser.getNamespacePrefixUriMap());
}
Also used : XmlnsFilteringParser(org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser) InputSource(org.xml.sax.InputSource) JAXBException(javax.xml.bind.JAXBException) IndeterminateEvaluationException(org.ow2.authzforce.core.pdp.api.IndeterminateEvaluationException) StringReader(java.io.StringReader)

Aggregations

XmlnsFilteringParser (org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser)7 Response (oasis.names.tc.xacml._3_0.core.schema.wd_17.Response)5 JAXBException (javax.xml.bind.JAXBException)4 Request (oasis.names.tc.xacml._3_0.core.schema.wd_17.Request)4 FileNotFoundException (java.io.FileNotFoundException)3 IOException (java.io.IOException)3 Test (org.junit.Test)3 PdpEngineConfiguration (org.ow2.authzforce.core.pdp.impl.PdpEngineConfiguration)3 File (java.io.File)2 Path (java.nio.file.Path)2 IndeterminateEvaluationException (org.ow2.authzforce.core.pdp.api.IndeterminateEvaluationException)2 DOMResponse (com.att.research.xacml.std.dom.DOMResponse)1 HashBasedTable (com.google.common.collect.HashBasedTable)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Table (com.google.common.collect.Table)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 StringReader (java.io.StringReader)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1