Skip to content

Latest commit

 

History

History
456 lines (344 loc) · 16.9 KB

README.md

File metadata and controls

456 lines (344 loc) · 16.9 KB

OPA Java SDK

License Maven Central Version

Important

The documentation for this SDK lives at https://docs.styra.com/sdk, with reference documentation available at https://styrainc.github.io/opa-java/javadoc, and development documentation at https://styrainc.github.io/opa-java/

You can use the Styra OPA SDK to connect to Open Policy Agent and Enterprise OPA deployments.

SDK Installation

This package is published on Maven Central as com.styra/opa. The Maven Central page includes up-to-date instructions to add it as a dependency to your Java project, tailored for a variety of build systems including Maven and Gradle.

If you wish to build from source and publish the SDK artifact to your local Maven repository (on your filesystem) then use the following command (after cloning the git repo locally):

On Linux/MacOS:

./gradlew publishToMavenLocal -Pskip.signing

On Windows:

gradlew.bat publishToMavenLocal -Pskip.signing

SDK Example Usage (high-level)

package org.example;

import com.styra.opa.OPAClient;
import com.styra.opa.OPAException;

import java.util.Map;
import java.util.List;

import static java.util.Map.entry;

public class App {
    public static void main(String[] args) throws Exception {
        // Create an OPA instance, this handles any state needed for interacting
        // with OPA, and can be re-used for multiple requests if needed.
        String opaURL = "http://localhost:8181";
        OPAClient opa = new OPAClient(opaURL);

        // This will be the input to our policy.
        java.util.Map<String,Object> input = java.util.Map.ofEntries(
            entry("subject", "alice"),
            entry("action", "read"),
            entry("resource", "/finance/reports/fy2038_budget.csv")
        );

        // We will read the list of policy violations, and whether the request
        // is allowed or not into these.
        java.util.List<Object> violations;
        boolean allowed;

        // Perform the request against OPA.
        try {
            allowed = opa.check("policy/allow", input);
            violations = opa.evaluate("policy/violations", input);
        } catch (OPAException e ) {
            // Note that OPAException usually wraps other exception types, in
            // case you need to do more complex error handling.
            System.out.println("exception while making request against OPA: " + e);
            throw e; // crash the program
        }

        System.out.println("allowed: " + allowed);
        System.out.println("violations: " + violations);
    }
}

Note

For low-level SDK usage, see the sections below.


OPA OpenApi SDK (low-level)

Summary

For more information about the API: Enterprise OPA documentation

Table of Contents

SDK Example Usage

Example 1

package hello.world;

import com.styra.opa.openapi.OpaApiClient;
import com.styra.opa.openapi.models.errors.ClientError;
import com.styra.opa.openapi.models.errors.ServerError;
import com.styra.opa.openapi.models.operations.ExecuteDefaultPolicyWithInputResponse;
import com.styra.opa.openapi.models.shared.GzipAcceptEncoding;
import com.styra.opa.openapi.models.shared.Input;
import com.styra.opa.openapi.models.shared.Security;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws ClientError, ServerError, Exception {

        OpaApiClient sdk = OpaApiClient.builder()
                .security(Security.builder()
                    .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                    .build())
            .build();

        ExecuteDefaultPolicyWithInputResponse res = sdk.executeDefaultPolicyWithInput()
                .pretty(false)
                .acceptEncoding(GzipAcceptEncoding.GZIP)
                .input(Input.of(4963.69d))
                .call();

        if (res.result().isPresent()) {
            // handle response
        }
    }
}

Example 2

package hello.world;

import com.styra.opa.openapi.OpaApiClient;
import com.styra.opa.openapi.models.errors.ClientError1;
import com.styra.opa.openapi.models.errors.ServerError;
import com.styra.opa.openapi.models.operations.ExecutePolicyWithInputRequest;
import com.styra.opa.openapi.models.operations.ExecutePolicyWithInputRequestBody;
import com.styra.opa.openapi.models.operations.ExecutePolicyWithInputResponse;
import com.styra.opa.openapi.models.shared.Input;
import com.styra.opa.openapi.models.shared.Security;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws ClientError1, ServerError, Exception {

        OpaApiClient sdk = OpaApiClient.builder()
                .security(Security.builder()
                    .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                    .build())
            .build();

        ExecutePolicyWithInputRequest req = ExecutePolicyWithInputRequest.builder()
                .path("app/rbac")
                .requestBody(ExecutePolicyWithInputRequestBody.builder()
                    .input(Input.of(false))
                    .build())
                .build();

        ExecutePolicyWithInputResponse res = sdk.executePolicyWithInput()
                .request(req)
                .call();

        if (res.successfulPolicyResponse().isPresent()) {
            // handle response
        }
    }
}

Example 3

package hello.world;

import com.styra.opa.openapi.OpaApiClient;
import com.styra.opa.openapi.models.errors.BatchServerError;
import com.styra.opa.openapi.models.errors.ClientError1;
import com.styra.opa.openapi.models.operations.ExecuteBatchPolicyWithInputRequest;
import com.styra.opa.openapi.models.operations.ExecuteBatchPolicyWithInputRequestBody;
import com.styra.opa.openapi.models.operations.ExecuteBatchPolicyWithInputResponse;
import com.styra.opa.openapi.models.shared.Input;
import com.styra.opa.openapi.models.shared.Security;
import java.lang.Exception;
import java.util.Map;

public class Application {

    public static void main(String[] args) throws ClientError1, BatchServerError, Exception {

        OpaApiClient sdk = OpaApiClient.builder()
                .security(Security.builder()
                    .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                    .build())
            .build();

        ExecuteBatchPolicyWithInputRequest req = ExecuteBatchPolicyWithInputRequest.builder()
                .path("app/rbac")
                .requestBody(ExecuteBatchPolicyWithInputRequestBody.builder()
                    .inputs(Map.ofEntries(
                        Map.entry("key", Input.of("<value>"))))
                    .build())
                .build();

        ExecuteBatchPolicyWithInputResponse res = sdk.executeBatchPolicyWithInput()
                .request(req)
                .call();

        if (res.batchSuccessfulPolicyEvaluation().isPresent()) {
            // handle response
        }
    }
}

Available Resources and Operations

Available methods

Server Selection

Select Server by Index

You can override the default server globally by passing a server index to the serverIndex builder method when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:

# Server Variables
0 http://localhost:8181 None

Example

package hello.world;

import com.styra.opa.openapi.OpaApiClient;
import com.styra.opa.openapi.models.errors.ClientError;
import com.styra.opa.openapi.models.errors.ServerError;
import com.styra.opa.openapi.models.operations.ExecuteDefaultPolicyWithInputResponse;
import com.styra.opa.openapi.models.shared.GzipAcceptEncoding;
import com.styra.opa.openapi.models.shared.Input;
import com.styra.opa.openapi.models.shared.Security;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws ClientError, ServerError, Exception {

        OpaApiClient sdk = OpaApiClient.builder()
                .serverIndex(0)
                .security(Security.builder()
                    .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                    .build())
            .build();

        ExecuteDefaultPolicyWithInputResponse res = sdk.executeDefaultPolicyWithInput()
                .pretty(false)
                .acceptEncoding(GzipAcceptEncoding.GZIP)
                .input(Input.of(4963.69d))
                .call();

        if (res.result().isPresent()) {
            // handle response
        }
    }
}

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the serverURL builder method when initializing the SDK client instance. For example:

package hello.world;

import com.styra.opa.openapi.OpaApiClient;
import com.styra.opa.openapi.models.errors.ClientError;
import com.styra.opa.openapi.models.errors.ServerError;
import com.styra.opa.openapi.models.operations.ExecuteDefaultPolicyWithInputResponse;
import com.styra.opa.openapi.models.shared.GzipAcceptEncoding;
import com.styra.opa.openapi.models.shared.Input;
import com.styra.opa.openapi.models.shared.Security;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws ClientError, ServerError, Exception {

        OpaApiClient sdk = OpaApiClient.builder()
                .serverURL("http://localhost:8181")
                .security(Security.builder()
                    .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                    .build())
            .build();

        ExecuteDefaultPolicyWithInputResponse res = sdk.executeDefaultPolicyWithInput()
                .pretty(false)
                .acceptEncoding(GzipAcceptEncoding.GZIP)
                .input(Input.of(4963.69d))
                .call();

        if (res.result().isPresent()) {
            // handle response
        }
    }
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.

By default, an API error will throw a models/errors/SDKError exception. When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the executeDefaultPolicyWithInput method throws the following exceptions:

Error Type Status Code Content Type
models/errors/ClientError 400, 404 application/json
models/errors/ServerError 500 application/json
models/errors/SDKError 4XX, 5XX */*

Example

package hello.world;

import com.styra.opa.openapi.OpaApiClient;
import com.styra.opa.openapi.models.errors.ClientError;
import com.styra.opa.openapi.models.errors.ServerError;
import com.styra.opa.openapi.models.operations.ExecuteDefaultPolicyWithInputResponse;
import com.styra.opa.openapi.models.shared.GzipAcceptEncoding;
import com.styra.opa.openapi.models.shared.Input;
import com.styra.opa.openapi.models.shared.Security;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws ClientError, ServerError, Exception {

        OpaApiClient sdk = OpaApiClient.builder()
                .security(Security.builder()
                    .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                    .build())
            .build();

        ExecuteDefaultPolicyWithInputResponse res = sdk.executeDefaultPolicyWithInput()
                .pretty(false)
                .acceptEncoding(GzipAcceptEncoding.GZIP)
                .input(Input.of(4963.69d))
                .call();

        if (res.result().isPresent()) {
            // handle response
        }
    }
}

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
bearerAuth http HTTP Bearer

You can set the security parameters through the security builder method when initializing the SDK client instance. For example:

package hello.world;

import com.styra.opa.openapi.OpaApiClient;
import com.styra.opa.openapi.models.errors.ClientError;
import com.styra.opa.openapi.models.errors.ServerError;
import com.styra.opa.openapi.models.operations.ExecuteDefaultPolicyWithInputResponse;
import com.styra.opa.openapi.models.shared.GzipAcceptEncoding;
import com.styra.opa.openapi.models.shared.Input;
import com.styra.opa.openapi.models.shared.Security;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws ClientError, ServerError, Exception {

        OpaApiClient sdk = OpaApiClient.builder()
                .security(Security.builder()
                    .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
                    .build())
            .build();

        ExecuteDefaultPolicyWithInputResponse res = sdk.executeDefaultPolicyWithInput()
                .pretty(false)
                .acceptEncoding(GzipAcceptEncoding.GZIP)
                .input(Input.of(4963.69d))
                .call();

        if (res.result().isPresent()) {
            // handle response
        }
    }
}

Development

This repository includes components generated by Speakeasy based on this OpenAPI spec, as well as human authored code that simplifies usage. The Speakeasy generated code resides in the com.styra.opa.sdk package and offers the greatest level of control, but is more verbose and complicated. The hand written com.styra.opa package offers a simplified API designed to make using the OPA REST API straightforward for common use cases.

Build Instructions

To build the SDK, use ./gradlew build, the resulting JAR will be placed in ./build/libs/api.jar.

To build the documentation site, including JavaDoc, run ./scripts/build_docs.sh OUTPUT_DIR. You should replace OUTPUT_DIR with a directory on your local system where you would like the generated docs to be placed. You can also preview the documentation site ephemerally using ./scripts/serve_docs.sh, which will serve the docs on http://localhost:8000 until you use Ctrl+C to exit the script.

To run the unit tests, you can use ./gradlew test.

To run the linter, you can use ./gradlew lint

Community

For questions, discussions and announcements related to Styra products, services and open source projects, please join the Styra community on Slack!