Search in sources :

Example 1 with LimitsCheckingJSONObject

use of org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject in project core by authzforce.

the class XacmlJsonTest method test.

@Test(dataProvider = "getTestDirectories")
public void test(final Path testDirectoryPath, final String reqFilterId) throws Exception {
    LOGGER.debug("******************************");
    LOGGER.debug("Starting PDP test in directory '{}'", testDirectoryPath);
    // Response file
    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 JSONObject expectedResponse;
    if (Files.exists(expectedRespFilepath)) {
        try (final BufferedReader reader = Files.newBufferedReader(expectedRespFilepath, StandardCharsets.UTF_8)) {
            expectedResponse = new LimitsCheckingJSONObject(reader, MAX_JSON_STRING_LENGTH, MAX_JSON_CHILDREN_COUNT, MAX_JSON_DEPTH);
            if (!expectedResponse.has("Response")) {
                throw new IllegalArgumentException("Invalid XACML JSON Response file: " + expectedRespFilepath + ". Expected root key: \"Response\"");
            }
            XacmlJsonUtils.RESPONSE_SCHEMA.validate(expectedResponse);
        }
    } 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 Path reqFilepath = testDirectoryPath.resolve(REQUEST_FILENAME_SUFFIX);
    // If no Request file, it is just a static policy syntax error check
    final JSONObject request;
    if (Files.exists(reqFilepath)) {
        try (InputStream inputStream = new FileInputStream(reqFilepath.toFile())) {
            request = new JSONObject(new JSONTokener(inputStream));
            if (!request.has("Request")) {
                throw new IllegalArgumentException("Invalid XACML JSON Request file: " + reqFilepath + ". Expected root key: \"Request\"");
            }
            try {
                XacmlJsonUtils.REQUEST_SCHEMA.validate(request);
            } catch (ValidationException 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, ENABLE_XPATH, optAttributeProviderConfFile, reqFilterId, BaseXacmlJsonResultPostprocessor.DefaultFactory.ID);
            } else {
                final Path rootPolicyFile = testDirectoryPath.resolve(ROOT_POLICY_FILENAME_SUFFIX);
                pdpEngineConf = TestUtils.newPdpEngineConfiguration(rootPolicyFile, ENABLE_XPATH, optAttributeProviderConfFile, reqFilterId, BaseXacmlJsonResultPostprocessor.DefaultFactory.ID);
            }
        } 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 (final PdpEngineInoutAdapter<JSONObject, JSONObject> pdp = PdpEngineXacmlJsonAdapters.newXacmlJsonInoutAdapter(pdpEngineConf)) {
        if (request == null) {
            // this is a policy syntax error check and we didn't found the syntax error as
            // expected
            org.junit.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.
                 */
            org.junit.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 JSONObject actualResponse = pdp.evaluate(request);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Response that is received from the PDP :  {}", actualResponse);
            }
            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) PdpEngineConfiguration(org.ow2.authzforce.core.pdp.impl.PdpEngineConfiguration) ValidationException(org.everit.json.schema.ValidationException) JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) LimitsCheckingJSONObject(org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject) LimitsCheckingJSONObject(org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject) Test(org.testng.annotations.Test)

Example 2 with LimitsCheckingJSONObject

use of org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject in project restful-pdp by authzforce.

the class XacmlRestProfileJaxRsTest method testInvalidPdpRequest.

@Test
public void testInvalidPdpRequest() throws IOException {
    // Request body (invalid according to JSON schema)
    final String reqLocation = "src/test/resources/server/IIA001/Request-missing-category-id.json";
    try (InputStream reqIn = new FileInputStream(reqLocation)) {
        final JSONObject jsonRequest = new LimitsCheckingJSONObject(new InputStreamReader(reqIn, StandardCharsets.UTF_8), MAX_JSON_STRING_LENGTH, MAX_JSON_CHILDREN_COUNT, MAX_JSON_DEPTH);
        if (!jsonRequest.has("Request")) {
            throw new IllegalArgumentException("Invalid XACML JSON Request file: " + reqLocation + ". Expected root key: \"Request\"");
        }
        /*
			 * No preliminary request schema validation this time, let the server reject it
			 */
        // send request
        final WebClient client = WebClient.create("http://localhost:" + port + "/services", Collections.singletonList(new JsonRiJaxrsProvider()));
        final Response actualResponse = client.path("pdp").type("application/xacml+json").accept("application/xacml+json").post(jsonRequest);
        // check response
        Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), actualResponse.getStatus());
    }
}
Also used : Response(javax.ws.rs.core.Response) JSONObject(org.json.JSONObject) LimitsCheckingJSONObject(org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject) InputStreamReader(java.io.InputStreamReader) JsonRiJaxrsProvider(org.ow2.authzforce.jaxrs.util.JsonRiJaxrsProvider) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) LimitsCheckingJSONObject(org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject) WebClient(org.apache.cxf.jaxrs.client.WebClient) FileInputStream(java.io.FileInputStream) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 3 with LimitsCheckingJSONObject

use of org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject in project restful-pdp by authzforce.

the class XacmlRestProfileJaxRsTest method testPdpRequest.

@Test
public void testPdpRequest() throws IOException {
    // Request body
    final String reqLocation = "src/test/resources/IIA001/Request.json";
    final JSONObject jsonRequest = new LimitsCheckingJSONObject(new FileReader(reqLocation, StandardCharsets.UTF_8), MAX_JSON_STRING_LENGTH, MAX_JSON_CHILDREN_COUNT, MAX_JSON_DEPTH);
    if (!jsonRequest.has("Request")) {
        throw new IllegalArgumentException("Invalid XACML JSON Request file: " + reqLocation + ". Expected root key: \"Request\"");
    }
    XacmlJsonUtils.REQUEST_SCHEMA.validate(jsonRequest);
    // expected response
    final String respLocation = "src/test/resources/IIA001/Response.json";
    final JSONObject expectedResponse = new LimitsCheckingJSONObject(new FileReader(respLocation, StandardCharsets.UTF_8), MAX_JSON_STRING_LENGTH, MAX_JSON_CHILDREN_COUNT, MAX_JSON_DEPTH);
    if (!expectedResponse.has("Response")) {
        throw new IllegalArgumentException("Invalid XACML JSON Response file: " + respLocation + ". Expected root key: \"Response\"");
    }
    XacmlJsonUtils.RESPONSE_SCHEMA.validate(expectedResponse);
    // send request
    final WebClient client = WebClient.create(ENDPOINT_ADDRESS, Collections.singletonList(new JsonRiJaxrsProvider()));
    final JSONObject actualResponse = client.path("pdp").type("application/xacml+json").accept("application/xacml+json").post(jsonRequest, JSONObject.class);
    // check response
    Assert.assertTrue(expectedResponse.similar(actualResponse), "JSON response does not match expected one.");
}
Also used : JSONObject(org.json.JSONObject) LimitsCheckingJSONObject(org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject) JsonRiJaxrsProvider(org.ow2.authzforce.jaxrs.util.JsonRiJaxrsProvider) LimitsCheckingJSONObject(org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject) FileReader(java.io.FileReader) WebClient(org.apache.cxf.jaxrs.client.WebClient)

Example 4 with LimitsCheckingJSONObject

use of org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject in project restful-pdp by authzforce.

the class XacmlRestProfileJaxRsTest method testPdpRequest.

// @Autowired
// private TestRestTemplate restTemplate;
@Test
public void testPdpRequest() throws IOException {
    // Request body
    final String reqLocation = "src/test/resources/server/IIA001/Request.json";
    try (InputStream reqIn = new FileInputStream(reqLocation)) {
        final JSONObject jsonRequest = new LimitsCheckingJSONObject(new InputStreamReader(reqIn, StandardCharsets.UTF_8), MAX_JSON_STRING_LENGTH, MAX_JSON_CHILDREN_COUNT, MAX_JSON_DEPTH);
        if (!jsonRequest.has("Request")) {
            throw new IllegalArgumentException("Invalid XACML JSON Request file: " + reqLocation + ". Expected root key: \"Request\"");
        }
        XacmlJsonUtils.REQUEST_SCHEMA.validate(jsonRequest);
        // expected response
        final String respLocation = "src/test/resources/server/IIA001/Response.json";
        try (final InputStream respIn = new FileInputStream(respLocation)) {
            final JSONObject expectedResponse = new LimitsCheckingJSONObject(new InputStreamReader(respIn, StandardCharsets.UTF_8), MAX_JSON_STRING_LENGTH, MAX_JSON_CHILDREN_COUNT, MAX_JSON_DEPTH);
            if (!expectedResponse.has("Response")) {
                throw new IllegalArgumentException("Invalid XACML JSON Response file: " + respLocation + ". Expected root key: \"Response\"");
            }
            XacmlJsonUtils.RESPONSE_SCHEMA.validate(expectedResponse);
            // send request
            final WebClient client = WebClient.create("http://localhost:" + port + "/services", Collections.singletonList(new JsonRiJaxrsProvider()));
            final JSONObject actualResponse = client.path("pdp").type("application/xacml+json").accept("application/xacml+json").post(jsonRequest, JSONObject.class);
            // check response
            Assert.assertTrue(expectedResponse.similar(actualResponse));
        }
    }
}
Also used : JSONObject(org.json.JSONObject) LimitsCheckingJSONObject(org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject) InputStreamReader(java.io.InputStreamReader) JsonRiJaxrsProvider(org.ow2.authzforce.jaxrs.util.JsonRiJaxrsProvider) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) LimitsCheckingJSONObject(org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject) WebClient(org.apache.cxf.jaxrs.client.WebClient) FileInputStream(java.io.FileInputStream) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Aggregations

JSONObject (org.json.JSONObject)4 LimitsCheckingJSONObject (org.ow2.authzforce.xacml.json.model.LimitsCheckingJSONObject)4 WebClient (org.apache.cxf.jaxrs.client.WebClient)3 JsonRiJaxrsProvider (org.ow2.authzforce.jaxrs.util.JsonRiJaxrsProvider)3 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2 Test (org.junit.Test)2 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)2 FileReader (java.io.FileReader)1 Path (java.nio.file.Path)1 Response (javax.ws.rs.core.Response)1 ValidationException (org.everit.json.schema.ValidationException)1 JSONTokener (org.json.JSONTokener)1 PdpEngineConfiguration (org.ow2.authzforce.core.pdp.impl.PdpEngineConfiguration)1 Test (org.testng.annotations.Test)1