OPA
Since Camel 4.23
Only producer is supported
The OPA component turns a Camel route into a Policy Enforcement Point (PEP) in front of Open Policy Agent, the CNCF policy engine whose policies are written in Rego. Camel builds an input document out of the Exchange, OPA evaluates the policy against it, and the resulting decision is recorded on the Exchange.
This keeps authorization out of the route: the rules live in Rego and can be updated, versioned and tested independently of the integration, instead of being hand-coded in a processor.
Maven users will need to add the following dependency to their pom.xml.
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-opa</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI Format
opa:policyPath[?options]
Where policyPath is the path of the Rego rule head to evaluate, relative to the OPA data document. For a rule named allow in a policy declaring package authz.orders, the path is authz/orders/allow, which OPA serves at /v1/data/authz/orders/allow.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The OPA component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Where to read the allow or deny verdict when the policy decision is a JSON object rather than a boolean: the name of a top-level key, or a dotted path such as result.allow for a verdict nested in the object. A decision that is a boolean is the verdict itself. Only a JSON boolean counts as a verdict: when the key is missing or holds another value, the message is denied (CamelOpaDecisionAllow=false) and a warning is logged once. | allow | String | |
Whether to evaluate the elements of a List body in one call: one input document per element, with the element as input.body and the same headers and properties for all. The verdicts are set in the CamelOpaBatchDecision header, a List of Boolean in the order of the body, and the details in CamelOpaBatchOutcomes; CamelOpaDecisionAllow is not set. An element whose evaluation failed is denied, unless failOpen is set and its decision point was unavailable. Uses the OPA batch API (/v1/batch/data), and one request per element when the server answers 404 to it. A body that is not a List fails the exchange. Only for rest mode: with evaluationMode=wasm the endpoint fails to start. | false | boolean | |
The component configuration. | OpaConfiguration | ||
The entrypoint of the WebAssembly module to evaluate in wasm mode, as named with opa build -e when the bundle was built, such as authz/orders/allow. Defaults to the policy path, which is the name opa build gives it. | String | ||
How the policy is evaluated. rest sends each decision request to an OPA server over its REST Data API. wasm evaluates the policy compiled to WebAssembly (policyBundle) in-process, with no server: serverUrl, bearerToken, opaClient, connectionTimeout, requestTimeout, sslContextParameters and healthCheckBundles are not used, failOpen only applies to borrowTimeout, and batch is not supported (the endpoint fails to start). Enum values:
| rest | String | |
Whether to send the message body to OPA in input.body of the input document. A string, number, boolean, Map or List is sent as it is, any other body as its string form. A stream body is read for this, so enable stream caching to keep it readable for the rest of the route. In batch mode each element of the List body is always sent as input.body, whatever this option. Not used when inputExpression is set. | false | boolean | |
Comma-separated list of the message header names (case-insensitive) to send to OPA in input.headers of the input document. The default * sends every header except Authorization, Proxy-Authorization, Cookie and Set-Cookie, which carry a caller credential and are sent only when named in the list. The CamelOpa decision headers are never sent. A value that is not a string, number, boolean, Map or List is sent as its string form. Not used when inputExpression is set. | * | String | |
Comma-separated list of the exchange property names (case-insensitive) to send to OPA in input.properties of the input document, or * for all custom exchange properties; the internal properties of Camel are never sent. Not set by default, so no properties are sent. Use it to give the policy the identity that an earlier authentication step stored as an exchange property, such as CamelKeycloakTokenSubject, rather than a header that the caller can set. Not used when inputExpression is set. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
The policy compiled to WebAssembly, for wasm mode: the location of the bundle.tar.gz that opa build -t wasm produces, or of a bare .wasm module, with a file:, classpath: (the default when there is no prefix), http: or https: prefix. Required when evaluationMode=wasm. A bundle also carries its data.json, which the policy reads as data; a bare module has no data. | String | ||
The base URL of the OPA server, without the /v1/data suffix. Each policy decision is requested with a POST to this URL followed by /v1/data/ and the policy path, and the readiness check probes /health on it. Only used in rest mode, and not used when opaClient is set. | String | ||
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
How long, in milliseconds, an evaluation in wasm mode waits for a free WebAssembly policy instance (see poolSize). When none is free in time, the evaluation fails with OpaPolicyEvaluationException, or the message proceeds when failOpen is set. | 30000 | long | |
How long, in milliseconds, to wait for the connection to the OPA server to be established, in rest mode. When it runs out, the evaluation fails with OpaPolicyEvaluationException, or the message proceeds when failOpen is set. Not used when opaClient is set. | 10000 | long | |
Whether the readiness check of the OPA server also requires that OPA has activated its configured bundles: it probes /health?bundles=true instead of /health. It does not enable the health check, change the policy evaluation or ensure a particular policy revision. Not used in wasm mode or when opaClient is set. | false | boolean | |
An expression that builds the complete OPA input document, in place of the default one (headers, properties, body, exchangeId and routeId), so includeHeaders, includeProperties and includeBody are not used. The result must convert to a JSON object: a Map, a JSON object node or a POJO. Any other result (null, a scalar, an array or a stream) fails the evaluation with OpaPolicyEvaluationException, also when failOpen is set. In batch mode the expression is evaluated once per element, on a copy of the exchange with the element as the body. | Expression | ||
Autowired An OPAClient of the OPA Java SDK to send the policy decision requests with, in place of the client the endpoint creates. When set, serverUrl, bearerToken, connectionTimeout, requestTimeout and sslContextParameters are not used, and no readiness check is registered. When a single OPAClient is in the registry, it is used automatically. Not used in wasm mode. | OPAClient | ||
How often, in milliseconds, to read the policyBundle again in wasm mode, to pick up a changed policy or data. When the content changed, the new policy is loaded and replaces the active one; when it fails to load, the active policy stays. 0 disables the reload. | 0 | long | |
How many WebAssembly policy instances to pool in wasm mode. An instance is not thread-safe, so each evaluation borrows one: this limits how many messages are evaluated at the same time. Must be at least 1. | 8 | int | |
How long, in milliseconds, to wait for the complete response of the OPA server to a decision request, in rest mode. When it runs out, the evaluation fails with OpaPolicyEvaluationException, or the message proceeds when failOpen is set. Not used when opaClient is set. | 30000 | long | |
Used for enabling or disabling all consumer based health checks from this component. | true | boolean | |
Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | boolean | |
The bearer token for an OPA server that has API authentication enabled. It is sent in the Authorization header, after Bearer, with each policy decision request and with the readiness check. Only used in rest mode, and not used when opaClient is set. | String | ||
Whether to let the message proceed when the policy decision point is unavailable: in rest mode the OPA server cannot be reached, connectionTimeout or requestTimeout runs out, or the server (or a gateway in front of it) answers 429, 502, 503 or 504; in wasm mode no policy instance is free within borrowTimeout. The message then proceeds with CamelOpaDecisionAllow=true and CamelOpaDecisionFailedOpen=true. It never applies when the decision point answered, nor to an input document that cannot be built: an undefined decision, a rejected request (400, or another 4xx such as for a wrong bearer token) and an error evaluating the policy (500) always fail the evaluation with OpaPolicyEvaluationException. Disabled by default, so an unavailable decision point fails the evaluation too. Do not enable this in production. | false | boolean | |
TLS configuration for the HTTPS connection to the OPA server in rest mode, for example to trust a server certificate from a private CA, or to present a client certificate to a server that requires mutual TLS. Also used by the readiness check. When not set, the global SSL context parameters are used if useGlobalSslContextParameters is enabled, otherwise the JVM default. Not used when opaClient is set. | SSLContextParameters | ||
Whether to use the global SSL context parameters of the CamelContext for the connection to the OPA server, for an endpoint that has no sslContextParameters. Only used in rest mode. | false | boolean |
Endpoint Options
The OPA endpoint is configured using URI syntax:
opa:policyPath
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required Path of the policy decision to evaluate, relative to the OPA data document: the package path and the rule name, separated by slashes. For a rule named allow in a policy with package authz.orders, this is authz/orders/allow; a leading slash is ignored. It is set on the endpoint only and never taken from a message header, so a message cannot choose the policy that judges it. In wasm mode it is also the default entrypoint. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Where to read the allow or deny verdict when the policy decision is a JSON object rather than a boolean: the name of a top-level key, or a dotted path such as result.allow for a verdict nested in the object. A decision that is a boolean is the verdict itself. Only a JSON boolean counts as a verdict: when the key is missing or holds another value, the message is denied (CamelOpaDecisionAllow=false) and a warning is logged once. | allow | String | |
Whether to evaluate the elements of a List body in one call: one input document per element, with the element as input.body and the same headers and properties for all. The verdicts are set in the CamelOpaBatchDecision header, a List of Boolean in the order of the body, and the details in CamelOpaBatchOutcomes; CamelOpaDecisionAllow is not set. An element whose evaluation failed is denied, unless failOpen is set and its decision point was unavailable. Uses the OPA batch API (/v1/batch/data), and one request per element when the server answers 404 to it. A body that is not a List fails the exchange. Only for rest mode: with evaluationMode=wasm the endpoint fails to start. | false | boolean | |
The entrypoint of the WebAssembly module to evaluate in wasm mode, as named with opa build -e when the bundle was built, such as authz/orders/allow. Defaults to the policy path, which is the name opa build gives it. | String | ||
How the policy is evaluated. rest sends each decision request to an OPA server over its REST Data API. wasm evaluates the policy compiled to WebAssembly (policyBundle) in-process, with no server: serverUrl, bearerToken, opaClient, connectionTimeout, requestTimeout, sslContextParameters and healthCheckBundles are not used, failOpen only applies to borrowTimeout, and batch is not supported (the endpoint fails to start). Enum values:
| rest | String | |
Whether to send the message body to OPA in input.body of the input document. A string, number, boolean, Map or List is sent as it is, any other body as its string form. A stream body is read for this, so enable stream caching to keep it readable for the rest of the route. In batch mode each element of the List body is always sent as input.body, whatever this option. Not used when inputExpression is set. | false | boolean | |
Comma-separated list of the message header names (case-insensitive) to send to OPA in input.headers of the input document. The default * sends every header except Authorization, Proxy-Authorization, Cookie and Set-Cookie, which carry a caller credential and are sent only when named in the list. The CamelOpa decision headers are never sent. A value that is not a string, number, boolean, Map or List is sent as its string form. Not used when inputExpression is set. | * | String | |
Comma-separated list of the exchange property names (case-insensitive) to send to OPA in input.properties of the input document, or * for all custom exchange properties; the internal properties of Camel are never sent. Not set by default, so no properties are sent. Use it to give the policy the identity that an earlier authentication step stored as an exchange property, such as CamelKeycloakTokenSubject, rather than a header that the caller can set. Not used when inputExpression is set. | String | ||
The policy compiled to WebAssembly, for wasm mode: the location of the bundle.tar.gz that opa build -t wasm produces, or of a bare .wasm module, with a file:, classpath: (the default when there is no prefix), http: or https: prefix. Required when evaluationMode=wasm. A bundle also carries its data.json, which the policy reads as data; a bare module has no data. | String | ||
The base URL of the OPA server, without the /v1/data suffix. Each policy decision is requested with a POST to this URL followed by /v1/data/ and the policy path, and the readiness check probes /health on it. Only used in rest mode, and not used when opaClient is set. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
How long, in milliseconds, an evaluation in wasm mode waits for a free WebAssembly policy instance (see poolSize). When none is free in time, the evaluation fails with OpaPolicyEvaluationException, or the message proceeds when failOpen is set. | 30000 | long | |
How long, in milliseconds, to wait for the connection to the OPA server to be established, in rest mode. When it runs out, the evaluation fails with OpaPolicyEvaluationException, or the message proceeds when failOpen is set. Not used when opaClient is set. | 10000 | long | |
Whether the readiness check of the OPA server also requires that OPA has activated its configured bundles: it probes /health?bundles=true instead of /health. It does not enable the health check, change the policy evaluation or ensure a particular policy revision. Not used in wasm mode or when opaClient is set. | false | boolean | |
An expression that builds the complete OPA input document, in place of the default one (headers, properties, body, exchangeId and routeId), so includeHeaders, includeProperties and includeBody are not used. The result must convert to a JSON object: a Map, a JSON object node or a POJO. Any other result (null, a scalar, an array or a stream) fails the evaluation with OpaPolicyEvaluationException, also when failOpen is set. In batch mode the expression is evaluated once per element, on a copy of the exchange with the element as the body. | Expression | ||
Autowired An OPAClient of the OPA Java SDK to send the policy decision requests with, in place of the client the endpoint creates. When set, serverUrl, bearerToken, connectionTimeout, requestTimeout and sslContextParameters are not used, and no readiness check is registered. When a single OPAClient is in the registry, it is used automatically. Not used in wasm mode. | OPAClient | ||
How often, in milliseconds, to read the policyBundle again in wasm mode, to pick up a changed policy or data. When the content changed, the new policy is loaded and replaces the active one; when it fails to load, the active policy stays. 0 disables the reload. | 0 | long | |
How many WebAssembly policy instances to pool in wasm mode. An instance is not thread-safe, so each evaluation borrows one: this limits how many messages are evaluated at the same time. Must be at least 1. | 8 | int | |
How long, in milliseconds, to wait for the complete response of the OPA server to a decision request, in rest mode. When it runs out, the evaluation fails with OpaPolicyEvaluationException, or the message proceeds when failOpen is set. Not used when opaClient is set. | 30000 | long | |
The bearer token for an OPA server that has API authentication enabled. It is sent in the Authorization header, after Bearer, with each policy decision request and with the readiness check. Only used in rest mode, and not used when opaClient is set. | String | ||
Whether to let the message proceed when the policy decision point is unavailable: in rest mode the OPA server cannot be reached, connectionTimeout or requestTimeout runs out, or the server (or a gateway in front of it) answers 429, 502, 503 or 504; in wasm mode no policy instance is free within borrowTimeout. The message then proceeds with CamelOpaDecisionAllow=true and CamelOpaDecisionFailedOpen=true. It never applies when the decision point answered, nor to an input document that cannot be built: an undefined decision, a rejected request (400, or another 4xx such as for a wrong bearer token) and an error evaluating the policy (500) always fail the evaluation with OpaPolicyEvaluationException. Disabled by default, so an unavailable decision point fails the evaluation too. Do not enable this in production. | false | boolean | |
TLS configuration for the HTTPS connection to the OPA server in rest mode, for example to trust a server certificate from a private CA, or to present a client certificate to a server that requires mutual TLS. Also used by the readiness check. When not set, the global SSL context parameters are used if useGlobalSslContextParameters is enabled, otherwise the JVM default. Not used when opaClient is set. | SSLContextParameters |
Message Headers
The OPA component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelOpaDecisionAllow (producer) Constant: | The verdict of the policy evaluation: true when the policy allowed the message, or when it proceeded because of failOpen; false when the policy denied it, or when the decision has no boolean verdict at allowKey. A value the incoming message carries is removed before the evaluation, and the header is not set when the evaluation fails, nor in batch mode. | Boolean | |
| Constant: | The policy decision as OPA returned it (the value of the rule, such as a Boolean or a Map), for policies that return more than a verdict, such as deny reasons, obligations or row filters. Null when the message proceeded because of failOpen. Not set in batch mode. | Object | |
| Constant: | The policy path that was evaluated. Set by the component for observability; it is not read as an input and cannot be used to select a different policy. | String | |
CamelOpaDecisionFailedOpen (producer) Constant: | Set to true only when the exchange proceeded because failOpen is enabled and the policy could not be evaluated - nothing authorized it. Absent on every decision an actual policy made, so a route or an audit trail can tell the two apart rather than seeing the same CamelOpaDecisionAllow=true for both. For a batch, set when any element proceeded because failOpen was enabled; CamelOpaBatchOutcomes identifies the elements. | Boolean | |
CamelOpaBatchDecision (producer) Constant: | The verdicts of a batch evaluation (batch=true): a List of Boolean with one verdict per element of the List body, in the same order. An element whose evaluation failed is false, unless failOpen is set and its decision point was unavailable. A value the incoming message carries is removed before the evaluation. | List | |
CamelOpaBatchOutcomes (producer) Constant: | The outcome of each element of a batch evaluation (batch=true): an immutable List of OpaBatchOutcome in the order of the List body, each with allowed (the verdict that applies), decision (the Boolean verdict of the policy, or null when none was obtained), failureCategory (NONE, UNAVAILABLE, EVALUATION_ERROR, MISSING_RESULT or INTERRUPTED) and failedOpen. Holds no exception or error message. | List | |
CamelAuthenticationFailurePolicyId (producer) Constant: | The simple class name of the OpaSecurityPolicy that denied the message, or that could not evaluate the policy. The OpaSecurityPolicy sets it before it throws a CamelAuthorizationException, so an onException handler can read it; the opa endpoint does not set it. | String |
Message Body
The message body at each side of the OPA component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Producer input |
| Not read unless includeBody=true: then a String, number, boolean, Map or List goes into the input document as it is, and another body as its string form (a POJO as its toString). With batch=true a List, one input document per element: another body fails.
|
Producer output |
| The body is kept: the verdict is in the CamelOpaDecisionAllow header and the decision document in CamelOpaDecision, or with batch=true a List of Boolean per element in CamelOpaBatchDecision. |
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Usage
The component is used in one of two ways, depending on whether a denied message should be filtered out or should stop the route.
As a producer, deciding with a filter
The producer evaluates the policy and records the verdict in the CamelOpaDecisionAllow header, leaving the message body untouched. The route then decides what to do with it:
-
Java
-
YAML
from("platform-http:/orders")
.to("opa:authz/orders/allow")
.filter(header(OpaConstants.DECISION_ALLOW).isEqualTo(true))
.to("direct:handleOrder"); - route:
from:
uri: platform-http:/orders
steps:
- to:
uri: opa:authz/orders/allow
- filter:
expression:
simple:
expression: "${header.CamelOpaDecisionAllow} == true"
steps:
- to:
uri: direct:handleOrder This is the right shape when a denied message is simply not routed further, or when the route wants to inspect the full decision document — a policy that returns obligations, row filters or deny reasons rather than a plain boolean puts them in the CamelOpaDecision header.
As a security policy, enforcing on a route segment
OpaSecurityPolicy is an AuthorizationPolicy, so it can wrap part of a route. A deny throws a CamelAuthorizationException and the wrapped part never runs, which makes it composable with onException:
-
Java
-
YAML
OpaSecurityPolicy opaPolicy = new OpaSecurityPolicy("http://localhost:8181", "authz/orders/allow");
from("platform-http:/orders")
.policy(opaPolicy)
.to("direct:handleOrder"); - beans:
- name: opaPolicy
type: org.apache.camel.component.opa.security.OpaSecurityPolicy
properties:
serverUrl: http://localhost:8181
policyPath: authz/orders/allow
- route:
from:
uri: platform-http:/orders
steps:
- policy:
ref: opaPolicy
steps:
- to:
uri: direct:handleOrder The decision headers are set here too, so an onException(CamelAuthorizationException.class) handler can read CamelOpaDecision to build a meaningful error response.
The policy can also evaluate a WebAssembly bundle in-process, which is the mode to prefer for a hot path such as authorizing an AI tool call, where a network hop per decision is not wanted:
-
Java
-
YAML
OpaSecurityPolicy opaPolicy = new OpaSecurityPolicy();
opaPolicy.setPolicyPath("authz/orders/allow");
opaPolicy.setEvaluationMode("wasm");
opaPolicy.setPolicyBundle("classpath:orders-bundle.tar.gz");
from("platform-http:/orders")
.policy(opaPolicy)
.to("direct:handleOrder"); - beans:
- name: opaPolicy
type: org.apache.camel.component.opa.security.OpaSecurityPolicy
properties:
policyPath: authz/orders/allow
evaluationMode: wasm
policyBundle: classpath:orders-bundle.tar.gz
- route:
from:
uri: platform-http:/orders
steps:
- policy:
ref: opaPolicy
steps:
- to:
uri: direct:handleOrder The decision contract is identical to rest mode - the same CamelOpaDecision headers, and a CamelAuthorizationException on a deny - so a route need not know which engine evaluated it. serverUrl, bearerToken and the readiness check do not apply in wasm mode; the Evaluation modes section below covers building a bundle and what each mode gives up.
The input document
Camel sends OPA an input document shaped like this:
{
"headers": { "user": "alice", "CamelHttpMethod": "POST" },
"properties": { "CamelKeycloakTokenSubject": "alice" },
"body": "...",
"exchangeId": "1767DC33923810E-0000000000000000",
"routeId": "orders"
} so a policy reads it as:
package authz.orders
default allow := false
allow if {
input.headers.CamelHttpMethod == "GET"
} The component’s integration test runs a real OPA server against authz.rego, which is a worked example of both a plain boolean rule and a decision object with deny reasons; OpaIT alongside it shows the matching routes end to end.
headers carries every message header by default, with one exception: the headers that carry a caller credential verbatim — Authorization, Proxy-Authorization, Cookie and Set-Cookie — are withheld from the wildcard. OPA’s decision logging ships the whole input document, frequently to a remote collector, so the wildcard should not quietly export credentials off the box. A policy that genuinely needs one can still have it by naming the header: includeHeaders=Authorization,user sends it. Matching is case-insensitive, so authorization is withheld too. Set includeHeaders to a comma-separated list of names when the policy only needs a few of them.
Prefer includeProperties for identity: a token that an earlier step has already verified belongs there, as Authorizing an identity describes, rather than handing the raw credential to the policy to re-check.
body is not sent unless includeBody is enabled: bodies can be large or streaming, and most authorization decisions do not need them. When you do enable it on a streaming body, enable stream caching so the body is still readable by the rest of the route.
properties is empty unless you ask for it — see Authorizing an identity below.
Header and body values that are not JSON-native are converted to their string form. That conversion is shallow: a Map or List value is passed through as-is, so anything non-JSON-native nested inside it is left for the OPA SDK’s serializer to render. A policy that reads nested structures should not assume the same string conversion applies at depth.
The component’s own CamelOpa* decision headers are never sent back to OPA, so a policy cannot be shown a verdict that an inbound message claimed for itself.
Custom input expressions
Set inputExpression=#domainInput to evaluate a configured Camel Expression bean that produces the complete policy input. This replaces the default envelope in both REST and WASM modes, and also applies to OpaSecurityPolicy. The expression result may be a Map, an object JSON node, or a POJO supported by the component’s Jackson JSON mapping. Nested maps, lists and POJOs are normalized to JSON-native values; a top-level JSON string is not parsed implicitly. Null, scalar, array and streaming results fail closed before the policy engine is called, even when failOpen=true.
For example, take the verified identity from an exchange property the route set after authentication, and only the domain payload from the body:
-
Java
-
XML
-
YAML
context.getRegistry().bind("domainInput", new ExpressionAdapter() {
@Override
public Object evaluate(Exchange exchange) {
return Map.of("subject", exchange.getProperty("verifiedSubject"),
"order", exchange.getMessage().getBody());
}
});
from("direct:orders")
.to("opa:authz/orders/allow?inputExpression=#domainInput"); <!-- a small Expression class of the application, with the evaluate(Exchange) method of the Java tab -->
<bean id="domainInput" class="com.example.orders.DomainInputExpression"/>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:orders"/>
<to uri="opa:authz/orders/allow?inputExpression=#domainInput"/>
</route>
</camelContext> - beans:
# a small Expression class of the application, with the evaluate(Exchange) method of the Java tab
- name: domainInput
type: com.example.orders.DomainInputExpression
- route:
from:
uri: direct:orders
steps:
- to:
uri: opa:authz/orders/allow
parameters:
inputExpression: "#domainInput" The body comes from the sender. Do not make it the whole input, and never let it supply the identity or role fields the policy reads: a sender who posts {"subject": "admin"} would write straight into them. Take the identity from an exchange property the route verified, as Authorizing an identity describes, and put the sender’s data under a key of its own. |
The includeHeaders, includeProperties and includeBody options configure only the default envelope; they do not add or filter fields in a custom input. The expression decides what to include, so select verified identity and application data deliberately. The default envelope withholds the headers that carry a credential verbatim (Authorization, Proxy-Authorization, Cookie and Set-Cookie); a custom expression gets none of that protection, so copy headers selectively and leave those out. Decision headers are still cleared before mapping. Custom expression beans must support concurrent evaluation. For a single exchange the expression runs on the live exchange, so a header or property it sets stays on the exchange; in batch mode it runs on a copy, as described below.
In batch mode, the expression is evaluated once per element against an exchange copy whose body is that element. Headers and properties remain available to the expression, while the route’s original List body is preserved. The expression must produce one JSON object per element; a mapping failure stops the batch before calling OPA. The component does not consume streams automatically. If an expression explicitly reads a stream, configure stream caching or handle its lifetime in the route.
Reading the verdict
CamelOpaDecision holds the decision document exactly as OPA returned it. CamelOpaDecisionAllow holds the boolean verdict read out of it:
-
a decision that is a boolean is the verdict;
-
a decision that is an object is searched for the
allowKeyentry (allowby default), which must itself be a boolean.allowKeyaccepts a dotted path, soallowKey=result.allowreads a verdict nested inside the document as{"result": {"allow": true}}; -
anything else cannot be read as a verdict and counts as a deny, with the raw document still available for the route to inspect. That case is logged at WARN rather than DEBUG: a document that arrived but could not be read is a configuration problem, and from
CamelOpaDecisionAllowalone it is indistinguishable from a genuine denial.
Both headers are written on every evaluation, so a verdict set by an inbound message never survives into the route.
Batch evaluation
A route that splits a payload and authorizes each element pays one OPA round-trip per element. Set batch=true and hand the producer a List instead: it builds one input document per element - each element as the body, sharing the exchange’s headers and properties - and evaluates them in a single call through OPA’s batch API (the SDK falls back to sequential requests when the server does not implement it).
-
Java
-
YAML
from("direct:orders")
// the body is a List of orders to authorize
.to("opa:authz/orders/allow?batch=true")
// CamelOpaBatchDecision is now a List<Boolean> parallel to the body
.process(dropTheDeniedOrders); - route:
from:
uri: direct:orders
steps:
# the body is a List of orders to authorize
- to:
uri: opa:authz/orders/allow
parameters:
batch: true
# CamelOpaBatchDecision is now a List<Boolean> parallel to the body
- process:
ref: dropTheDeniedOrders The per-element verdicts arrive in CamelOpaBatchDecision, a List<Boolean> parallel to the input list: element i is allowed when entry i is true. Neither CamelOpaDecisionAllow nor CamelOpaDecision is set in batch mode - there is no single verdict, and no single decision document - and both are cleared on entry like the other decision headers, so a value an inbound message supplied never survives. CamelOpaPolicyPath is set, to the same value a single evaluation records, so tooling can read it either way.
Fail-closed applies per element: an element whose evaluation failed is denied (false) while every other element decides normally; failOpen allows it only when its decision point was unavailable (see Failure handling). The batch is never denied as a whole because one element failed, nor allowed because most of it succeeded. A call that fails entirely - the server could not be reached at all - fails the exchange rather than denying each element: it carries no verdict at all, not a list of false. Under failOpen a call that could not reach the server allows every element instead.
CamelOpaBatchOutcomes provides an immutable List<OpaBatchOutcome> in the same order, while CamelOpaBatchDecision keeps its existing Boolean-list contract. Each outcome has:
| Property | Meaning |
|---|---|
| Whether the element may proceed, including an explicit fail-open result. |
| The normalized Boolean policy verdict, or |
|
|
|
|
These outcomes contain no exception objects or failure messages. A genuine policy denial has decision=false, failureCategory=NONE and failedOpen=false. An unavailable element allowed under failOpen has allowed=true, decision=null, failureCategory=UNAVAILABLE and failedOpen=true. CamelOpaDecisionFailedOpen=true marks a batch whenever any element failed open; inspect the outcomes to identify which ones. A call that could not reach the server at all is reported like an element whose own decision point was unavailable: under failOpen every element is UNAVAILABLE and failedOpen=true, and the outcomes do not say which of the two happened, since the route proceeds the same way in both cases. Empty batches return empty verdict and outcome lists. A whole-batch failure that fails closed carries neither list. The outcome header and aggregate marker are cleared before every evaluation, including a subsequent single-element evaluation.
batch requires evaluationMode=rest: it saves the per-element HTTP round-trip, which has no meaning for in-process wasm evaluation, and the endpoint rejects the combination at startup.
Authorizing an identity
The component decides; it does not authenticate. Establish who the caller is first, then let the policy authorize the identity that step produced.
The catch is that Camel’s authentication components deliberately keep the identity they verified in exchange properties rather than in headers — camel-keycloak stores the access token and its subject that way and its preferPropertyOverHeader option defaults to true, precisely because a header can be set by the caller. So the identity you want to authorize is usually not in the header map.
Name those properties in includeProperties and they arrive in the input document under properties:
-
Java
-
YAML
from("platform-http:/orders")
.policy(keycloakPolicy) // authenticates, stores the subject as a property
.to("opa:authz/orders/allow?includeProperties=CamelKeycloakTokenSubject")
.filter(header(OpaConstants.DECISION_ALLOW).isEqualTo(true))
.to("direct:handleOrder"); - route:
from:
uri: platform-http:/orders
steps:
# authenticates, and stores the subject as a property
- policy:
ref: keycloakPolicy
steps:
- to:
uri: opa:authz/orders/allow
parameters:
includeProperties: CamelKeycloakTokenSubject
- filter:
expression:
simple:
expression: "${header.CamelOpaDecisionAllow} == true"
steps:
- to:
uri: direct:handleOrder and the policy reads them the same way it reads headers:
allow if {
input.properties.CamelKeycloakTokenSubject == "alice"
} includeProperties takes a comma-separated list, or * for all of them, and matches names case-insensitively. Unlike includeHeaders it is empty by default: exchange properties are mostly used to carry state between processors, so sending them all would be noise the policy has to wade through. Only custom properties are sent — Camel’s own internal exchange properties are never included.
Prefer this over copying the identity into a header before the opa: endpoint. A header is exactly the channel the authentication step treated as untrusted, so moving a verified identity into one to get it past this component undoes the check that produced it.
OpaSecurityPolicy takes the same option through setIncludeProperties.
Evaluation modes
By default the component calls a running OPA server over its Data API (evaluationMode=rest). It can instead evaluate a WebAssembly bundle in-process:
-
Java
-
YAML
from("platform-http:/orders")
.to("opa:authz/orders/allow?evaluationMode=wasm&policyBundle=classpath:bundle.tar.gz") - route:
from:
uri: platform-http:/orders
steps:
- to:
uri: opa:authz/orders/allow
parameters:
evaluationMode: wasm
policyBundle: classpath:bundle.tar.gz Build the bundle with OPA’s compiler — note that -e names an entrypoint, which is fixed at build time and is not the same thing as a data path:
opa build -t wasm -e authz/orders/allow policy.rego policyBundle accepts a file:, classpath: or http: location holding either the bundle.tar.gz that opa build emits or a bare .wasm. entrypoint defaults to the endpoint’s policy path, which is the name opa build gives it. evaluationMode accepts only rest and wasm; anything else is rejected when the endpoint is created, rather than quietly falling back to a server call that ignores policyBundle.
Prefer the bundle.tar.gz. A policy that reads data. decides from the *data document, and opa build packs that beside the module as data.json — a bare .wasm carries the rules but not the data, so such a policy evaluates against an empty data document and typically denies everything. Given the bundle, the component applies its data to every evaluation, so the decision matches what a server loading the same bundle would return:
# roles.rego reads data.admins, which lives in data.json next to it
opa build -t wasm -e authz/orders/allow roles.rego data.json Data that is not part of the bundle — what a server would receive through its Data API at runtime — has no equivalent in wasm mode. A policy depending on it needs evaluationMode=rest.
Prefer classpath: or file: for a bundle shipped with the application, which is what a build-time artefact usually is. The bundle is fetched when the endpoint starts, so an http: location makes startup depend on a server being reachable; since Camel 4.23 that fetch is bounded by camel.resource.http.connect-timeout and camel.resource.http.read-timeout, so an unresponsive server fails the route rather than stalling CamelContext startup indefinitely.
Which to choose:
rest | wasm | |
|---|---|---|
Policy source | a server, centrally managed | a bundle built with your application |
Updates | bundle polling, live | rebuild and redeploy |
Decision logs | yes | none |
Latency | a network round-trip per exchange | in-process |
Unreachable decision point | a real failure mode | cannot happen |
serverUrl and bearerToken have no meaning in wasm mode — there is no server to address or authenticate to, and the endpoint warns at startup if either was set — and no health check is registered, because there is nothing to probe. An absent health check is not a healthy one. failOpen still applies: a wasm pool can stay busy past borrowTimeout, and failOpen governs whether that denies the exchange or lets it through, as it does for an unreachable server in rest mode.
The decision contract is identical in both modes: the same headers, the same allowKey handling, and an undefined decision fails closed the same way. A route does not need to know which engine evaluated it.
Evaluation instances carry mutable state and are not thread-safe, so wasm mode pools them; poolSize (default 8) bounds how many exchanges evaluate at once. An exchange that arrives when all of them are busy waits for one, up to borrowTimeout (default 30s), and then fails rather than waiting indefinitely — an authorization decision that never arrives is not better than one that is denied, and it is much harder to diagnose. That failure is an evaluation failure, not a deny, so it fails closed or proceeds under failOpen like any other.
Size poolSize for the concurrency the route actually sees. A policy that takes a long time to evaluate holds its instance for that whole time, so the two options trade against each other: raise poolSize when many exchanges evaluate at once, and borrowTimeout when a single evaluation is legitimately slow. A policy that can run long enough to matter is usually better served by evaluationMode=rest, where the decision point is a separate process that a timeout can abandon.
Connecting to the server
In rest mode the component talks to OPA over HTTP, and both waits are bounded:
-
connectionTimeout(default 10s) — establishing the connection. -
requestTimeout(default 30s) — receiving the complete response for each HTTP request, including its body.
Receiving response headers does not end the request deadline: a server that sends headers and then stalls while writing the decision still times out. SDK retries, when applicable, make separate HTTP requests with the same limit.
Neither is optional in practice. A refused connection fails immediately, but a server that accepts and then stops answering — wedged, mid-restart, or behind a load balancer holding the socket — would otherwise park the routing thread indefinitely. For a component that fails closed that is worse than a denial: it never reaches the point of deciding. A timeout is treated as a failure to reach a verdict, so it denies, or proceeds if failOpen is set, like any other such failure.
TLS is configured with sslContextParameters, the usual JSSE utility:
-
Java
-
YAML
from("platform-http:/orders")
.to("opa:authz/orders/allow?serverUrl=https://opa:8181&sslContextParameters=#opaTls") - route:
from:
uri: platform-http:/orders
steps:
- to:
uri: opa:authz/orders/allow
parameters:
serverUrl: https://opa:8181
sslContextParameters: "#opaTls" Set useGlobalSslContextParameters=true on the component to pick up the context-wide configuration instead. OpaSecurityPolicy is a bean rather than an endpoint of the component, so the component’s option does not reach it: set useGlobalSslContextParameters, or sslContextParameters, on the policy itself.
That is what lets a workload present a client certificate to an OPA server requiring mutual TLS — a SPIFFE X.509-SVID, for example, so the application authenticates to the policy decision point as itself rather than relying on network position:
-
Java
-
YAML
SpiffeSSLContextParameters spiffe = new SpiffeSSLContextParameters();
// the SPIFFE ID the OPA server presents: the handshake fails for any other
spiffe.setAcceptedSpiffeIds("spiffe://example.org/opa");
context.getRegistry().bind("opaTls", spiffe); - beans:
- name: opaTls
type: org.apache.camel.component.spiffe.SpiffeSSLContextParameters
properties:
# the SPIFFE ID the OPA server presents: the handshake fails for any other
acceptedSpiffeIds: spiffe://example.org/opa SpiffeSSLContextParameters must be told which peers to accept: it refuses to build a context with neither acceptedSpiffeIds nor acceptAnySpiffeId, so a route referencing it would not start. Prefer naming the OPA server’s ID, as above, over acceptAnySpiffeId, which accepts any server the trust bundle vouches for. The Workload API is found through spiffeSocketPath, or the SPIFFE_ENDPOINT_SOCKET environment variable when that is not set; the SPIFFE component page describes the rest of its options.
None of this applies in wasm mode, where there is no server to reach.
Static data in pooled WASM instances
Each WASM pool instance prepares its fixed entrypoint and bundled data once when created. New inputs reuse that instance’s static data while the SDK resets transient input allocations for each evaluation. Instances are never shared concurrently. An evaluation failure discards the instance, and its replacement loads the same configured entrypoint and data before use. Large static data therefore adds initialization work per instance, rather than being parsed again for every exchange.
Reloading a WASM policy
A WASM endpoint or security policy keeps the policy module and its bundled data together as one immutable snapshot. By default it loads the configured resource at startup only. Set policyReloadInterval to a positive duration in milliseconds to poll that resource using a Camel-managed scheduler, for example:
.to("opa:authz/allow?evaluationMode=wasm&policyBundle=file:/etc/policies/bundle.tar.gz&policyReloadInterval=5000") The same policyReloadInterval property is available on OpaSecurityPolicy. A shared security policy polls while at least one guarded route is running and stops polling when the last guarded route stops. Reload reads only the operator-configured resource; it does not read or download policy on each exchange. Publish resource updates atomically, such as by renaming a completed file over the configured file.
For explicit reload, call reloadPolicy() on the started OpaEndpoint or OpaSecurityPolicy. It returns true after publishing changed content, false for unchanged content, and throws if loading or validation fails. The replacement is loaded, initialized with its configured entrypoint and data, and warmed before it becomes visible. Exchanges already using the previous snapshot finish with that snapshot, which closes after they drain. New exchanges use the replacement without waiting for those exchanges to finish. Stopping cancels the watcher and prevents an in-flight reload from publishing.
getPolicyReloadStatus() exposes the active SHA-256 revision of the module and data, the time of the last successful check (the initial load, a published reload, or a poll that found the content unchanged), and the time and exception class name of the last failed reload, which stay visible after later successful checks. Failure diagnostics exclude exception messages and resource contents. A failed reload retains the last validated snapshot. Content that loads but fails validation or compilation is not built again by a poll until it changes, so one broken file logs one warning, while a resource that cannot be read at all is retried on every poll; an explicit reloadPolicy() always tries. Operators should monitor failures because retained policy can become stale. Reload and this option apply only to WASM evaluation; REST policy deployment remains managed by the OPA server.
Failure handling
The component fails closed. If the policy cannot be evaluated at all — the OPA server is unreachable, times out, or answers with an error — the producer throws an OpaPolicyEvaluationException and OpaSecurityPolicy throws a CamelAuthorizationException; in neither case does the message proceed as allowed. This is deliberately different from a deny, which is a decision rather than a failure, so a route can tell "denied" from "no policy decision point available".
Setting failOpen=true reverses this, but only for a policy decision point that is unavailable:
-
in
restmode, the OPA server cannot be reached or times out (seeconnectionTimeoutandrequestTimeout), or a gateway in front of it answers502,503,504or429; -
in
wasmmode, no evaluation instance frees up withinborrowTimeout.
A decision point that answered still fails closed, because each of these answers is a policy saying no or a request that could never be decided, not an outage:
-
an undefined decision - for example
opa:authz/allowagainst a policy with nodefault allow := false, for an input the rule does not match; -
a rejected request -
400, or any other4xxsuch as a missing or expiredbearerToken(401/403) or a wrongpolicyPathprefix (404); -
an error evaluating the policy against this input - OPA answers
500, as for a conflict between rule outputs; -
an input document that cannot be serialized.
The input document is built from the message, so a sender can influence all of these. Were they covered, a crafted message could turn a policy’s "no" into "yes". failOpen exists for development and for non-critical policies, and should not be enabled in production.
An exchange that proceeds that way carries CamelOpaDecisionFailedOpen=true. CamelOpaDecisionAllow is true in both cases, and on its own it cannot tell "a policy allowed this" from "no policy ran and we were told to proceed" — which is exactly the distinction an audit trail needs. The marker is set only on the fail-open path, so a route can branch on it and an operator can alert on its presence:
-
Java
-
YAML
from("platform-http:/orders")
.to("opa:authz/orders/allow?failOpen=true")
.choice()
.when(header(OpaConstants.DECISION_FAILED_OPEN).isEqualTo(true))
.to("log:unauthorized?level=WARN")
.end()
.to("direct:orders") - route:
from:
uri: platform-http:/orders
steps:
- to:
uri: opa:authz/orders/allow
parameters:
failOpen: true
- choice:
when:
- expression:
simple:
expression: "${header.CamelOpaDecisionFailedOpen} == true"
steps:
- to:
uri: log:unauthorized
parameters:
level: WARN
- to:
uri: direct:orders Like the other decision headers it is cleared before every evaluation, so a message cannot arrive claiming CamelOpaDecisionFailedOpen=false and disguise an unauthorized exchange as one a policy allowed.
Note that OPA reports an undefined decision — no rule matched and the policy declares no default — as an error rather than as a deny, so it fails closed as well. Give every decision rule a default, as in the example above, so the policy always returns a verdict.
Health check
Each check owns its HTTP client and releases it when the check stops. The five-second health deadline includes the complete response body; a stalled body reports DOWN and the outstanding request is cancelled.
Because the component fails closed, an OPA server that cannot be reached fails every exchange through the route. The producer registers a readiness check that probes the server’s /health endpoint, so an unavailable policy decision point shows up in the health registry rather than only in the error logs once traffic starts failing.
Camel disables producer health checks by default; turn them on with camel.health.producersEnabled=true, or per component with healthCheckProducerEnabled. The check reports DOWN with the underlying reason — an unreachable server and a server answering its health endpoint with an error are reported differently, so a deny is never confused with an outage.
Set healthCheckBundles=true on the endpoint or OpaSecurityPolicy bean to request /health?bundles=true. OPA then includes activation/readiness of its configured bundles and discovery in the server’s health result. This is useful when a server starts downloading bundles after startup: a reachable server can otherwise report healthy before it has activated its policy bundle. The default remains the basic /health check. This option does not itself enable producer health checks or change policy evaluation.
For example, with producer checks enabled:
.to("opa:authz/orders/allow?healthCheckBundles=true") For a policy bean:
- beans:
- name: opaPolicy
type: org.apache.camel.component.opa.security.OpaSecurityPolicy
properties:
serverUrl: http://localhost:8181
policyPath: authz/orders/allow
healthCheckBundles: true Bundle-aware readiness follows OPA’s health semantics. It does not verify a particular bundle revision, guarantee policy freshness, or validate business permissions for a message. It is unused in wasm mode, with an injected opaClient, or when the corresponding health check is disabled.
OpaSecurityPolicy registers an equivalent check, under an id starting security-policy:opa-. It is arguably the more important of the two: a denied producer merely records a verdict the route can inspect, while the policy throws CamelAuthorizationException and stops the exchange, so an unreachable server there fails every message outright. That is why the policy’s check is on by default rather than opt-in like the producer’s. Set healthCheckEnabled=false on the policy for a route that should stay ready regardless — one running failOpen, say — in preference to hiding the check with camel.health.exclude-pattern. A policy running failOpen marks the exchanges it let through with CamelOpaDecisionFailedOpen, exactly as the producer does; the evaluator is shared, so everything in Failure handling about that header applies to .policy(…) too.
Neither check is registered when an opaClient was injected: that client may point anywhere and neither the endpoint nor the policy has a way to ask it where, so probing the configured serverUrl would report on a server they may never talk to. The endpoint check is also skipped when no serverUrl was given, and in wasm mode, where the policy is evaluated in-process and there is no server to probe.
Security notes
-
The policy path comes from the endpoint only. It is deliberately not overridable by a message header, so an inbound message cannot pick which policy judges it.
-
OPA is a trusted component, typically running as a sidecar reachable only from the application. When it is not, put the connection on a trusted network and authenticate to it with
bearerToken. -
The component decides; it does not authenticate. Establish who the caller is first — with SPIFFE workload identity, a verified JWT, or the surrounding transport’s authentication — and hand the policy that identity through
includePropertiesrather than through a header, as Authorizing an identity explains.
Authorization observations
See Authorization observations for optional decision events, low-cardinality metrics and verified-identity composition examples. Observations preserve the component’s existing decision headers and error handling.