This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new b10327304f15 CAMEL-26845: Observe authorization outcomes with bounded
metrics (#29837)
b10327304f15 is described below
commit b10327304f15638f52157e48259aa523645e6d01
Author: Andrea Cosentino <[email protected]>
AuthorDate: Mon Nov 23 12:13:19 2026 +0100
CAMEL-26845: Observe authorization outcomes with bounded metrics (#29837)
Add immutable authorization decision events and optional Micrometer
observations for OPA, OpenFGA and
SPIFFE, without retaining exchanges, identities or payloads. Metrics use
bounded decision dimensions plus
configured Camel context/category tags.
Events are dispatched with the standard EventHelper with warning isolation,
independent notifier opt-outs
are preserved, OPA batch counts are derived from structured outcomes, and
final JWT-policy verdicts are
covered once. Reload-wrapper engine/pool-wait reporting, input-mapping
failures and native batch duplicate
counts are observed; mutations and streaming queries produce no events.
Main/Spring Boot metrics
autoconfiguration and authorization-meter shutdown/dev-console integration
remain separate follow-up work.
Co-authored-by: Codex <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Signed-off-by: Andrea Cosentino <[email protected]>
---
.../camel/catalog/docs/micrometer-component.adoc | 7 +
.../apache/camel/catalog/docs/opa-component.adoc | 7 +
.../camel/catalog/docs/openfga-component.adoc | 7 +
.../camel/catalog/docs/spiffe-component.adoc | 7 +
.../src/main/docs/micrometer-component.adoc | 7 +
.../MicrometerAuthorizationEventNotifier.java | 63 ++++++
.../MicrometerAuthorizationEventNotifierTest.java | 78 +++++++
.../camel-opa/src/main/docs/opa-component.adoc | 7 +
.../camel/component/opa/OpaPolicyEvaluator.java | 93 +++++++-
.../component/opa/OpaReloadableWasmEvaluator.java | 15 +-
.../camel/component/opa/OpaWasmEvaluator.java | 23 +-
.../opa/OpaAuthorizationObservationTest.java | 244 +++++++++++++++++++++
.../org/apache/camel/component/opa/OpaWasmIT.java | 31 +++
.../src/main/docs/openfga-component.adoc | 7 +
.../camel/component/openfga/OpenFgaAuthorizer.java | 28 ++-
.../camel/component/openfga/OpenFgaProducer.java | 46 +++-
.../OpenFgaAuthorizationObservationTest.java | 211 ++++++++++++++++++
components/camel-spiffe/pom.xml | 6 +
.../src/main/docs/spiffe-component.adoc | 7 +
.../spiffe/SpiffeJwtSecurityProcessor.java | 11 +-
.../camel/component/spiffe/SpiffeJwtValidator.java | 43 ++++
.../component/spiffe/SpiffeSecurityProcessor.java | 23 ++
.../spiffe/SpiffeAuthorizationObservationTest.java | 185 ++++++++++++++++
.../java/org/apache/camel/support/EventHelper.java | 38 ++++
.../security/AuthorizationDecisionEvent.java | 234 ++++++++++++++++++++
.../support/security/AuthorizationObservation.java | 187 ++++++++++++++++
.../security/AuthorizationObservationTest.java | 172 +++++++++++++++
docs/user-manual/modules/ROOT/nav.adoc | 1 +
.../ROOT/pages/authorization-observability.adoc | 171 +++++++++++++++
29 files changed, 1947 insertions(+), 12 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/micrometer-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/micrometer-component.adoc
index 0e04a150e170..ac48ca86cf57 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/micrometer-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/micrometer-component.adoc
@@ -983,6 +983,13 @@ camel.metrics.binders=processor,jvm-info,file-descriptor
----
+=== Authorization observations
+
+See xref:manual::authorization-observability.adoc[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.
+
=== Using Camel Micrometer with Spring Boot
When you use `camel-micrometer-starter` with Spring Boot, then Spring Boot
autoconfiguration will automatically enable metrics capture if a
`io.micrometer.core.instrument.MeterRegistry` is available.
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/opa-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/opa-component.adoc
index 5d37f259b00d..1120f8935b23 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/opa-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/opa-component.adoc
@@ -866,3 +866,10 @@ where the policy is evaluated in-process and there is no
server to probe.
* 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 `includeProperties` rather than through a header, as
<<authorizing-an-identity>> explains.
+
+== Authorization observations
+
+See xref:manual::authorization-observability.adoc[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.
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/openfga-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/openfga-component.adoc
index 74720cb2391c..c262e7a9af2c 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/openfga-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/openfga-component.adoc
@@ -959,3 +959,10 @@ YAML::
uri: direct:serveOrder
----
====
+
+== Authorization observations
+
+See xref:manual::authorization-observability.adoc[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.
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spiffe-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spiffe-component.adoc
index e15b62e8b0b6..50cf86c81e04 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spiffe-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spiffe-component.adoc
@@ -668,3 +668,10 @@ No token, private key, certificate contents or exception
text is retained or pub
no independent unsubscribe handle for a borrowed client. Supply your own
health check for that injected client. If
`allowOperationHeader=true` is explicitly enabled, changing an individual
message's operation does not retarget the
readiness observer, which always reflects the endpoint's configured operation.
+
+== Authorization observations
+
+See xref:manual::authorization-observability.adoc[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.
diff --git
a/components/camel-micrometer/src/main/docs/micrometer-component.adoc
b/components/camel-micrometer/src/main/docs/micrometer-component.adoc
index 0e04a150e170..ac48ca86cf57 100644
--- a/components/camel-micrometer/src/main/docs/micrometer-component.adoc
+++ b/components/camel-micrometer/src/main/docs/micrometer-component.adoc
@@ -983,6 +983,13 @@ camel.metrics.binders=processor,jvm-info,file-descriptor
----
+=== Authorization observations
+
+See xref:manual::authorization-observability.adoc[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.
+
=== Using Camel Micrometer with Spring Boot
When you use `camel-micrometer-starter` with Spring Boot, then Spring Boot
autoconfiguration will automatically enable metrics capture if a
`io.micrometer.core.instrument.MeterRegistry` is available.
diff --git
a/components/camel-micrometer/src/main/java/org/apache/camel/component/micrometer/eventnotifier/MicrometerAuthorizationEventNotifier.java
b/components/camel-micrometer/src/main/java/org/apache/camel/component/micrometer/eventnotifier/MicrometerAuthorizationEventNotifier.java
new file mode 100644
index 000000000000..405c0dd2b2e1
--- /dev/null
+++
b/components/camel-micrometer/src/main/java/org/apache/camel/component/micrometer/eventnotifier/MicrometerAuthorizationEventNotifier.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.micrometer.eventnotifier;
+
+import java.util.concurrent.TimeUnit;
+
+import io.micrometer.core.instrument.Counter;
+import io.micrometer.core.instrument.Tags;
+import io.micrometer.core.instrument.Timer;
+import org.apache.camel.component.micrometer.MicrometerConstants;
+import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.support.security.AuthorizationDecisionEvent;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+
+/**
+ * Optional metrics for authorization observations. Every label is a fixed
enum; correlation and revisions are omitted.
+ */
+public class MicrometerAuthorizationEventNotifier extends
AbstractMicrometerEventNotifier<AuthorizationDecisionEvent> {
+ public MicrometerAuthorizationEventNotifier() {
+ super(AuthorizationDecisionEvent.class);
+ }
+
+ @Override
+ public void notify(CamelEvent event) {
+ AuthorizationDecisionEvent decision = (AuthorizationDecisionEvent)
event;
+ Tags common = Tags.of("engine", decision.getEngine().name(),
"operation", decision.getOperation().name(),
+ MicrometerConstants.CAMEL_CONTEXT_TAG,
getCamelContext().getName(), MicrometerConstants.KIND, "authorization");
+ Timer.builder("camel.authorization.duration")
+ .tags(common.and("outcome", decision.getOutcome().name(),
"failure", decision.getFailure().name()))
+
.register(getMeterRegistry()).record(decision.getDurationNanos(),
TimeUnit.NANOSECONDS);
+ var counts = decision.getCounts();
+ count(common, Outcome.ALLOW, counts.allowed());
+ count(common, Outcome.DENY, counts.denied());
+ count(common, Outcome.ERROR, counts.errors());
+ count(common, Outcome.UNAVAILABLE, counts.unavailable());
+ count(common, Outcome.FAILED_OPEN, counts.failedOpen());
+ if (decision.getPoolWaitNanos() >= 0) {
+
Timer.builder("camel.authorization.pool.wait").tags(common).register(getMeterRegistry())
+ .record(decision.getPoolWaitNanos(), TimeUnit.NANOSECONDS);
+ }
+ }
+
+ private void count(Tags common, Outcome outcome, long count) {
+ if (count > 0) {
+
Counter.builder("camel.authorization.decisions").tags(common.and("outcome",
outcome.name()))
+ .register(getMeterRegistry()).increment(count);
+ }
+ }
+}
diff --git
a/components/camel-micrometer/src/test/java/org/apache/camel/component/micrometer/eventnotifier/MicrometerAuthorizationEventNotifierTest.java
b/components/camel-micrometer/src/test/java/org/apache/camel/component/micrometer/eventnotifier/MicrometerAuthorizationEventNotifierTest.java
new file mode 100644
index 000000000000..2148868679b5
--- /dev/null
+++
b/components/camel-micrometer/src/test/java/org/apache/camel/component/micrometer/eventnotifier/MicrometerAuthorizationEventNotifierTest.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.micrometer.eventnotifier;
+
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import io.micrometer.core.instrument.Tag;
+import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+import org.apache.camel.component.micrometer.MicrometerConstants;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Operation;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.apache.camel.support.security.AuthorizationObservation;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class MicrometerAuthorizationEventNotifierTest {
+ @Test
+ void revisionsAndCorrelationDoNotCreateAdditionalMetricSeries() throws
Exception {
+ var registry = new SimpleMeterRegistry();
+ try (var context = new DefaultCamelContext()) {
+ var notifier = new MicrometerAuthorizationEventNotifier();
+ notifier.setCamelContext(context);
+ notifier.setMeterRegistry(registry);
+ context.getManagementStrategy().addEventNotifier(notifier);
+ context.start();
+ for (int index = 0; index < 2; index++) {
+ var exchange = new DefaultExchange(context);
+ exchange.getExchangeExtension().setFromRouteId("secret-route-"
+ index);
+ exchange.getMessage().setHeader("Authorization",
"secret-token");
+ var observation = AuthorizationObservation.begin(exchange,
Engine.OPA_WASM, Operation.BATCH,
+ "secret-revision-" + index);
+ observation.item(Outcome.ALLOW);
+ observation.item(Outcome.DENY);
+ observation.item(Outcome.FAILED_OPEN);
+ observation.poolWait(100);
+ observation.completeBatch();
+ }
+ var authorizationMeters = registry.getMeters().stream()
+ .filter(meter ->
meter.getId().getName().startsWith("camel.authorization.")).toList();
+ assertEquals(5, authorizationMeters.size());
+ assertEquals(2,
registry.get("camel.authorization.duration").timer().count());
+ assertEquals(2,
registry.get("camel.authorization.pool.wait").timer().count());
+ assertEquals(2.0,
registry.get("camel.authorization.decisions").tag("outcome",
"FAILED_OPEN").counter().count());
+ authorizationMeters.forEach(meter -> {
+ Set<String> keys =
meter.getId().getTags().stream().map(Tag::getKey)
+ .collect(Collectors.toSet());
+ assertTrue(Set.of("engine", "operation", "outcome", "failure",
MicrometerConstants.CAMEL_CONTEXT_TAG,
+ MicrometerConstants.KIND).containsAll(keys));
+ assertEquals(context.getName(),
meter.getId().getTag(MicrometerConstants.CAMEL_CONTEXT_TAG));
+ assertEquals("authorization",
meter.getId().getTag(MicrometerConstants.KIND));
+ assertFalse(meter.getId().toString().contains("secret"));
+ });
+ } finally {
+ registry.close();
+ }
+ }
+}
diff --git a/components/camel-opa/src/main/docs/opa-component.adoc
b/components/camel-opa/src/main/docs/opa-component.adoc
index 5d37f259b00d..1120f8935b23 100644
--- a/components/camel-opa/src/main/docs/opa-component.adoc
+++ b/components/camel-opa/src/main/docs/opa-component.adoc
@@ -866,3 +866,10 @@ where the policy is evaluated in-process and there is no
server to probe.
* 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 `includeProperties` rather than through a header, as
<<authorizing-an-identity>> explains.
+
+== Authorization observations
+
+See xref:manual::authorization-observability.adoc[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.
diff --git
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaPolicyEvaluator.java
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaPolicyEvaluator.java
index 988d3b1d582d..51d5f69d4bd1 100644
---
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaPolicyEvaluator.java
+++
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaPolicyEvaluator.java
@@ -33,6 +33,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Message;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Failure;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Operation;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.apache.camel.support.security.AuthorizationObservation;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -94,6 +99,51 @@ public abstract class OpaPolicyEvaluator {
* @throws OpaPolicyEvaluationException when the policy could not be
evaluated and {@code failOpen} is false
*/
public boolean evaluate(Exchange exchange) throws
OpaPolicyEvaluationException {
+ AuthorizationObservation observation
+ = AuthorizationObservation.begin(exchange,
observationEngine(), Operation.DECISION, null);
+ if (!observation.isEnabled()) {
+ return evaluateInternal(exchange, null);
+ }
+ long[] poolWait = observationEngine() == Engine.OPA_WASM ? new long[]
{ -1 } : null;
+ try {
+ boolean allowed = evaluateInternal(exchange, poolWait);
+ if (poolWait != null) {
+ observation.poolWait(poolWait[0]);
+ }
+ boolean failedOpen =
Boolean.TRUE.equals(exchange.getMessage().getHeader(OpaConstants.DECISION_FAILED_OPEN));
+ observation.complete(failedOpen ? Outcome.FAILED_OPEN : allowed ?
Outcome.ALLOW : Outcome.DENY,
+ failedOpen ? Failure.UNAVAILABLE : Failure.NONE);
+ return allowed;
+ } catch (OpaPolicyEvaluationException | RuntimeException e) {
+ if (poolWait != null) {
+ observation.poolWait(poolWait[0]);
+ }
+ boolean unavailable = observationUnavailable(e);
+ observation.complete(unavailable ? Outcome.UNAVAILABLE :
Outcome.ERROR,
+ AuthorizationObservation.interrupted(e) ?
Failure.INTERRUPTED
+ : unavailable ? Failure.UNAVAILABLE :
Failure.EVALUATION);
+ throw e;
+ }
+ }
+
+ private boolean observationUnavailable(Exception failure) {
+ if (failure instanceof InputDocumentException) {
+ return false;
+ }
+ Exception cause = failure instanceof OpaPolicyEvaluationException &&
failure.getCause() instanceof Exception wrapped
+ ? wrapped : failure;
+ return isDecisionPointUnavailable(cause);
+ }
+
+ protected Engine observationEngine() {
+ return Engine.OPA_REST;
+ }
+
+ protected Object evaluateDecision(Map<String, Object> input, long[]
poolWaitNanos) throws Exception {
+ return evaluateDecision(input);
+ }
+
+ private boolean evaluateInternal(Exchange exchange, long[] poolWaitNanos)
throws OpaPolicyEvaluationException {
// a verdict the message arrived with is a claim, not evidence. Clear
it before deciding anything, so that
// every way out of this method - allowed, denied, or a failure the
route goes on to handle - leaves only
// what this component decided. Overwriting at the end is not enough:
the paths that throw never get there,
@@ -104,11 +154,11 @@ public abstract class OpaPolicyEvaluator {
input = buildInput(exchange);
} catch (Exception e) {
restoreInterruptIfWrapped(e);
- throw new OpaPolicyEvaluationException("Failed to build input for
policy " + policyPath, exchange, e);
+ throw new InputDocumentException("Failed to build input for policy
" + policyPath, exchange, e);
}
Object decision;
try {
- decision = evaluateDecision(input);
+ decision = evaluateDecision(input, poolWaitNanos);
} catch (InterruptedException e) {
// not a policy failure but a shutdown, so failOpen must not turn
it into an allow: nothing decided
// that this exchange was permitted. Restore the flag the
interruptible wait cleared, then fail closed.
@@ -211,6 +261,33 @@ public abstract class OpaPolicyEvaluator {
* {@code UNAVAILABLE} and failed open; they do not say which of the two
happened.
*/
public List<Boolean> evaluateBatch(Exchange exchange, List<?> elements)
throws OpaPolicyEvaluationException {
+ AuthorizationObservation observation
+ = AuthorizationObservation.begin(exchange,
observationEngine(), Operation.BATCH, null);
+ try {
+ List<Boolean> verdicts = evaluateBatchInternal(exchange, elements);
+ if (observation.isEnabled()) {
+ @SuppressWarnings("unchecked")
+ List<OpaBatchOutcome> outcomes =
exchange.getMessage().getHeader(OpaConstants.BATCH_OUTCOMES, List.class);
+ for (OpaBatchOutcome outcome : outcomes) {
+ observation.item(outcome.isFailedOpen() ?
Outcome.FAILED_OPEN
+ : outcome.getFailureCategory() ==
OpaBatchOutcome.FailureCategory.UNAVAILABLE ? Outcome.UNAVAILABLE
+ : outcome.getFailureCategory() !=
OpaBatchOutcome.FailureCategory.NONE ? Outcome.ERROR
+ : outcome.isAllowed() ? Outcome.ALLOW :
Outcome.DENY);
+ }
+ observation.completeBatch();
+ }
+ return verdicts;
+ } catch (OpaPolicyEvaluationException | RuntimeException e) {
+ boolean unavailable = observationUnavailable(e);
+ observation.remainingItems(unavailable ? Outcome.UNAVAILABLE :
Outcome.ERROR, elements.size());
+ observation.complete(unavailable ? Outcome.UNAVAILABLE :
Outcome.ERROR,
+ AuthorizationObservation.interrupted(e) ?
Failure.INTERRUPTED
+ : unavailable ? Failure.UNAVAILABLE :
Failure.EVALUATION);
+ throw e;
+ }
+ }
+
+ private List<Boolean> evaluateBatchInternal(Exchange exchange, List<?>
elements) throws OpaPolicyEvaluationException {
clearDecisionHeaders(exchange);
// an empty list has nothing to authorize. Short-circuit before the
engine call: an empty batch is a case the
// OPA SDK does not define, and letting it reach the server could turn
"nothing to decide" into a whole-batch
@@ -227,7 +304,7 @@ public abstract class OpaPolicyEvaluator {
}
} catch (Exception e) {
restoreInterruptIfWrapped(e);
- throw new OpaPolicyEvaluationException("Failed to build batch
input for policy " + policyPath, exchange, e);
+ throw new InputDocumentException("Failed to build batch input for
policy " + policyPath, exchange, e);
}
List<OpaBatchOutcome> outcomes = new ArrayList<>(elements.size());
@@ -558,4 +635,14 @@ public abstract class OpaPolicyEvaluator {
}
return
exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange,
value);
}
+
+ /** Distinguishes input construction from backend availability when
classifying an observation. */
+ private static final class InputDocumentException extends
OpaPolicyEvaluationException {
+ private static final long serialVersionUID = 1L;
+
+ private InputDocumentException(String message, Exchange exchange,
Exception cause) {
+ super(message, exchange, cause);
+ }
+ }
+
}
diff --git
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaReloadableWasmEvaluator.java
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaReloadableWasmEvaluator.java
index 366638718461..8ea232bbfe06 100644
---
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaReloadableWasmEvaluator.java
+++
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaReloadableWasmEvaluator.java
@@ -32,6 +32,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.camel.CamelContext;
import org.apache.camel.Expression;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -268,8 +269,18 @@ public final class OpaReloadableWasmEvaluator extends
OpaPolicyEvaluator impleme
}
}
+ @Override
+ protected Engine observationEngine() {
+ return Engine.OPA_WASM;
+ }
+
@Override
protected Object evaluateDecision(Map<String, Object> input) throws
Exception {
+ return evaluateDecision(input, null);
+ }
+
+ @Override
+ protected Object evaluateDecision(Map<String, Object> input, long[]
poolWaitNanos) throws Exception {
Snapshot snapshot;
synchronized (state) {
ensureOpen(-1);
@@ -277,7 +288,9 @@ public final class OpaReloadableWasmEvaluator extends
OpaPolicyEvaluator impleme
snapshot.readers++;
}
try {
- return snapshot.evaluator.evaluateDecision(input);
+ return poolWaitNanos == null
+ ? snapshot.evaluator.evaluateDecision(input)
+ : snapshot.evaluator.evaluateDecision(input,
poolWaitNanos);
} finally {
boolean drained;
synchronized (state) {
diff --git
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java
index f0ed1f5b377b..62b244753d5c 100644
---
a/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java
+++
b/components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java
@@ -28,6 +28,7 @@ import com.styra.opa.wasm.OpaPolicy;
import org.apache.camel.CamelContext;
import org.apache.camel.Expression;
import org.apache.camel.support.ResourceHelper;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
import org.apache.camel.util.ObjectHelper;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
@@ -196,9 +197,27 @@ public class OpaWasmEvaluator extends OpaPolicyEvaluator
implements AutoCloseabl
@Override
protected Object evaluateDecision(Map<String, Object> input) throws
Exception {
- // serialized before borrowing, so an input that cannot be serialized
costs no pooled instance
+ return evaluateDecision(input, null);
+ }
+
+ @Override
+ protected Engine observationEngine() {
+ return Engine.OPA_WASM;
+ }
+
+ @Override
+ protected Object evaluateDecision(Map<String, Object> input, long[]
poolWaitNanos) throws Exception {
+ // Serialization failures do not consume a pooled policy instance.
String json = MAPPER.writeValueAsString(input);
- OpaWasmPolicyPool.Lease lease = pool.borrow();
+ long started = poolWaitNanos != null ? System.nanoTime() : 0;
+ OpaWasmPolicyPool.Lease lease;
+ try {
+ lease = pool.borrow();
+ } finally {
+ if (poolWaitNanos != null) {
+ poolWaitNanos[0] = System.nanoTime() - started;
+ }
+ }
String result;
try {
result = lease.policy().evaluate(json);
diff --git
a/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaAuthorizationObservationTest.java
b/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaAuthorizationObservationTest.java
new file mode 100644
index 000000000000..d236b0ad0bf0
--- /dev/null
+++
b/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaAuthorizationObservationTest.java
@@ -0,0 +1,244 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.opa;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import com.styra.opa.OPAClient;
+import org.apache.camel.Exchange;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.EventNotifierSupport;
+import org.apache.camel.support.ExpressionAdapter;
+import org.apache.camel.support.security.AuthorizationDecisionEvent;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+class OpaAuthorizationObservationTest {
+ @Test
+ void observesAllowDenyAndEvaluationErrorWithoutMessageData() throws
Exception {
+ try (Fixture fixture = new Fixture()) {
+ Evaluator evaluator = new Evaluator(false);
+ Exchange exchange = fixture.exchange();
+ evaluator.decision = true;
+ assertThat(evaluator.evaluate(exchange)).isTrue();
+ evaluator.decision = false;
+ assertThat(evaluator.evaluate(exchange)).isFalse();
+ evaluator.failure = new IllegalStateException("secret-error-text");
+ assertThatThrownBy(() ->
evaluator.evaluate(exchange)).isInstanceOf(OpaPolicyEvaluationException.class);
+
assertThat(fixture.events).extracting(AuthorizationDecisionEvent::getOutcome)
+ .containsExactly(Outcome.ALLOW, Outcome.DENY,
Outcome.ERROR);
+ assertThat(fixture.events).allSatisfy(event -> {
+
assertThat(event.getExchangeId()).isEqualTo(exchange.getExchangeId());
+ assertThat(event.getRevision()).isNull();
+ assertThat(event.getDurationNanos()).isNotNegative();
+
assertThat(event.asJSon().toString()).doesNotContain("secret-body",
"secret-token", "secret-error-text");
+ });
+ }
+ }
+
+ @Test
+ void unavailableAndFailedOpenRemainDistinctFromAnAllow() throws Exception {
+ try (Fixture fixture = new Fixture()) {
+ Evaluator closed = new Evaluator(false);
+ closed.failure = new IOException("secret-network-error");
+ assertThatThrownBy(() ->
closed.evaluate(fixture.exchange())).isInstanceOf(OpaPolicyEvaluationException.class);
+ Evaluator open = new Evaluator(true);
+ open.failure = new IOException("secret-network-error");
+ Exchange exchange = fixture.exchange();
+ assertThat(open.evaluate(exchange)).isTrue();
+
assertThat(exchange.getMessage().getHeader(OpaConstants.DECISION_FAILED_OPEN)).isEqualTo(true);
+
assertThat(fixture.events).extracting(AuthorizationDecisionEvent::getOutcome)
+ .containsExactly(Outcome.UNAVAILABLE, Outcome.FAILED_OPEN);
+ }
+ }
+
+ @Test
+ void partialBatchPreservesTrueDecisionsFailuresAndFailedOpenCounts()
throws Exception {
+ try (Fixture fixture = new Fixture()) {
+ Evaluator evaluator = new Evaluator(true);
+ evaluator.batch = Map.of("0", new
OpaPolicyEvaluator.BatchElement(true, null),
+ "1", new OpaPolicyEvaluator.BatchElement(false, null),
+ "2", new OpaPolicyEvaluator.BatchElement(null, new
IOException("secret")),
+ "3", new OpaPolicyEvaluator.BatchElement(null, new
IllegalStateException("secret")));
+ assertThat(evaluator.evaluateBatch(fixture.exchange(),
List.of("a", "b", "c", "d")))
+ .containsExactly(true, false, true, false);
+ assertThat(fixture.events).hasSize(1);
+ assertThat(fixture.events.getFirst().getCounts()).isEqualTo(new
AuthorizationDecisionEvent.Counts(1, 1, 1, 0, 1));
+
assertThat(fixture.events.getFirst().getOperation()).isEqualTo(AuthorizationDecisionEvent.Operation.BATCH);
+ }
+ }
+
+ @Test
+ void wholeBatchUnavailableCountsAllElementsAndEmptyBatchHasNoDecisions()
throws Exception {
+ try (Fixture fixture = new Fixture()) {
+ Evaluator evaluator = new Evaluator(false);
+ evaluator.failure = new IOException("offline");
+ assertThatThrownBy(() ->
evaluator.evaluateBatch(fixture.exchange(), List.of("a", "b")))
+ .isInstanceOf(OpaPolicyEvaluationException.class);
+
assertThat(fixture.events.getFirst().getCounts().unavailable()).isEqualTo(2);
+ assertThat(evaluator.evaluateBatch(fixture.exchange(),
List.of())).isEmpty();
+ assertThat(fixture.events.getLast().getCounts()).isEqualTo(new
AuthorizationDecisionEvent.Counts(0, 0, 0, 0, 0));
+ }
+ }
+
+ @Test
+ void structuredMissingAndUnavailableOutcomesDriveObservedCounts() throws
Exception {
+ try (Fixture fixture = new Fixture()) {
+ Evaluator evaluator = new Evaluator(false);
+ evaluator.batch = Map.of("0", new
OpaPolicyEvaluator.BatchElement(true, null),
+ "1", new OpaPolicyEvaluator.BatchElement(null, new
IOException("offline")));
+ Exchange exchange = fixture.exchange();
+ assertThat(evaluator.evaluateBatch(exchange, List.of("allow",
"unavailable", "missing")))
+ .containsExactly(true, false, false);
+ assertThat(fixture.events.getFirst().getCounts()).isEqualTo(new
AuthorizationDecisionEvent.Counts(1, 0, 1, 1, 0));
+
assertThat(exchange.getMessage().getHeader(OpaConstants.BATCH_OUTCOMES,
List.class)).hasSize(3);
+ }
+ }
+
+ @Test
+ void reloadWrapperObservesMappedWasmInputOnceAndKeepsThePoolWait() throws
Exception {
+ try (Fixture fixture = new Fixture()) {
+ OpaWasmEvaluator inner = mock(OpaWasmEvaluator.class);
+ when(inner.evaluateDecision(anyMap(),
any(long[].class))).thenAnswer(invocation -> {
+ Map<String, Object> input = invocation.getArgument(0);
+ assertThat(input).containsEntry("subject",
"verified").containsEntry("order", "secret-body");
+ long[] poolWait = invocation.getArgument(1);
+ poolWait[0] = 123;
+ return true;
+ });
+ try (var evaluator = new OpaReloadableWasmEvaluator(
+ fixture.context, 0,
+ () -> new OpaWasmEvaluator.Bundle(new byte[] { 1 }, null),
bundle -> inner,
+ "policy", "allow", "*", null, true, false, new
ExpressionAdapter() {
+ @Override
+ public Object evaluate(Exchange exchange) {
+ return Map.of("subject",
exchange.getProperty("verifiedSubject"),
+ "order", exchange.getMessage().getBody());
+ }
+ })) {
+ Exchange exchange = fixture.exchange();
+ exchange.setProperty("verifiedSubject", "verified");
+ assertThat(evaluator.evaluate(exchange)).isTrue();
+
assertThat(exchange.getMessage().getBody()).isEqualTo("secret-body");
+ assertThat(fixture.events).hasSize(1);
+ AuthorizationDecisionEvent event = fixture.events.getFirst();
+
assertThat(event.getEngine()).isEqualTo(AuthorizationDecisionEvent.Engine.OPA_WASM);
+ assertThat(event.getOutcome()).isEqualTo(Outcome.ALLOW);
+ assertThat(event.getPoolWaitNanos()).isEqualTo(123);
+ }
+ }
+ }
+
+ @Test
+ void mapperIoFailureIsAnEvaluationErrorWithoutCallingTheDecisionPoint()
throws Exception {
+ try (Fixture fixture = new Fixture()) {
+ OPAClient client = mock(OPAClient.class);
+ OpaRestEvaluator evaluator = new OpaRestEvaluator(
+ client, null, "policy", "allow", "*", null, true, true,
+ new ExpressionAdapter() {
+ @Override
+ public Object evaluate(Exchange exchange) {
+ throw new RuntimeCamelException(new
IOException("mapper unavailable"));
+ }
+ });
+ assertThatThrownBy(() ->
evaluator.evaluate(fixture.exchange())).isInstanceOf(OpaPolicyEvaluationException.class);
+ assertThatThrownBy(() ->
evaluator.evaluateBatch(fixture.exchange(), List.of("a", "b")))
+ .isInstanceOf(OpaPolicyEvaluationException.class);
+
assertThat(fixture.events).extracting(AuthorizationDecisionEvent::getOutcome)
+ .containsExactly(Outcome.ERROR, Outcome.ERROR);
+ assertThat(fixture.events.getLast().getCounts()).isEqualTo(new
AuthorizationDecisionEvent.Counts(0, 0, 2, 0, 0));
+ verifyNoInteractions(client);
+ }
+ }
+
+ private static class Evaluator extends OpaPolicyEvaluator {
+ Object decision;
+ Exception failure;
+ Map<String, BatchElement> batch;
+
+ Evaluator(boolean failOpen) {
+ super("policy", "allow", "*", null, true, failOpen);
+ }
+
+ @Override
+ protected Object evaluateDecision(Map<String, Object> input) throws
Exception {
+ if (failure != null) {
+ throw failure;
+ }
+ return decision;
+ }
+
+ @Override
+ protected boolean isDecisionPointUnavailable(Exception failure) {
+ return failure instanceof IOException;
+ }
+
+ @Override
+ protected Map<String, BatchElement> evaluateBatchDecisions(Map<String,
Map<String, Object>> inputs) throws Exception {
+ if (failure != null) {
+ throw failure;
+ }
+ return batch;
+ }
+ }
+
+ private static class Fixture implements AutoCloseable {
+ final DefaultCamelContext context = new DefaultCamelContext();
+ final List<AuthorizationDecisionEvent> events = new ArrayList<>();
+
+ Fixture() throws Exception {
+ context.getManagementStrategy().addEventNotifier(new
EventNotifierSupport() {
+ @Override
+ public boolean isEnabled(CamelEvent event) {
+ return event instanceof AuthorizationDecisionEvent;
+ }
+
+ @Override
+ public void notify(CamelEvent event) {
+ events.add((AuthorizationDecisionEvent) event);
+ }
+ });
+ context.start();
+ }
+
+ Exchange exchange() {
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getMessage().setBody("secret-body");
+ exchange.getMessage().setHeader("Authorization", "secret-token");
+ return exchange;
+ }
+
+ @Override
+ public void close() throws Exception {
+ context.close();
+ }
+ }
+}
diff --git
a/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmIT.java
b/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmIT.java
index 6987b0b717a2..5985855db993 100644
---
a/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmIT.java
+++
b/components/camel-opa/src/test/java/org/apache/camel/component/opa/OpaWasmIT.java
@@ -22,6 +22,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
@@ -39,7 +40,10 @@ import
org.apache.camel.component.opa.security.OpaSecurityPolicy;
import org.apache.camel.health.HealthCheck;
import org.apache.camel.health.HealthCheckHelper;
import org.apache.camel.health.WritableHealthCheckRepository;
+import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.support.EventNotifierSupport;
import org.apache.camel.support.builder.ExpressionBuilder;
+import org.apache.camel.support.security.AuthorizationDecisionEvent;
import org.apache.camel.test.infra.opa.services.OpaWasmBundleBuilder;
import org.apache.camel.test.junit6.CamelTestSupport;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
@@ -147,6 +151,33 @@ public class OpaWasmIT extends CamelTestSupport {
return repository.stream().toList();
}
+ @Test
+ void wasmEvaluationPublishesOneDecisionEventWithItsPoolWait() throws
Exception {
+ var events = new ArrayList<AuthorizationDecisionEvent>();
+ var observer = new EventNotifierSupport() {
+ @Override
+ public boolean isEnabled(CamelEvent event) {
+ return event instanceof AuthorizationDecisionEvent;
+ }
+
+ @Override
+ public void notify(CamelEvent event) {
+ events.add((AuthorizationDecisionEvent) event);
+ }
+ };
+ context.getManagementStrategy().addEventNotifier(observer);
+ try {
+ Exchange out = template.request(wasm("authz/allow"), exchange ->
exchange.getMessage().setHeader("user", "alice"));
+ assertThat(out.getException()).isNull();
+ assertThat(events).hasSize(1);
+ assertThat(events.getFirst().getEngine())
+ .isEqualTo(AuthorizationDecisionEvent.Engine.OPA_WASM);
+ assertThat(events.getFirst().getPoolWaitNanos()).isNotNegative();
+ } finally {
+ context.getManagementStrategy().removeEventNotifier(observer);
+ }
+ }
+
/**
* In {@code wasm} mode the policy is evaluated in-process, so there is no
OPA server to probe and no producer
* health check is registered (CAMEL-24743).
diff --git a/components/camel-openfga/src/main/docs/openfga-component.adoc
b/components/camel-openfga/src/main/docs/openfga-component.adoc
index 74720cb2391c..c262e7a9af2c 100644
--- a/components/camel-openfga/src/main/docs/openfga-component.adoc
+++ b/components/camel-openfga/src/main/docs/openfga-component.adoc
@@ -959,3 +959,10 @@ YAML::
uri: direct:serveOrder
----
====
+
+== Authorization observations
+
+See xref:manual::authorization-observability.adoc[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.
diff --git
a/components/camel-openfga/src/main/java/org/apache/camel/component/openfga/OpenFgaAuthorizer.java
b/components/camel-openfga/src/main/java/org/apache/camel/component/openfga/OpenFgaAuthorizer.java
index 065354464831..af306cc34079 100644
---
a/components/camel-openfga/src/main/java/org/apache/camel/component/openfga/OpenFgaAuthorizer.java
+++
b/components/camel-openfga/src/main/java/org/apache/camel/component/openfga/OpenFgaAuthorizer.java
@@ -36,6 +36,11 @@ import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Message;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Failure;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Operation;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.apache.camel.support.security.AuthorizationObservation;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -190,6 +195,27 @@ public class OpenFgaAuthorizer {
* @throws OpenFgaEvaluationException when no answer could be obtained and
{@code failOpen} is false
*/
public boolean check(Exchange exchange) throws OpenFgaEvaluationException {
+ AuthorizationObservation observation
+ = AuthorizationObservation.begin(exchange, Engine.OPENFGA,
Operation.DECISION, authorizationModelId);
+ if (!observation.isEnabled()) {
+ return checkInternal(exchange);
+ }
+ try {
+ boolean allowed = checkInternal(exchange);
+ boolean failedOpen =
Boolean.TRUE.equals(exchange.getMessage().getHeader(OpenFgaConstants.FAILED_OPEN));
+ observation.complete(failedOpen ? Outcome.FAILED_OPEN : allowed ?
Outcome.ALLOW : Outcome.DENY,
+ failedOpen ? Failure.UNAVAILABLE : Failure.NONE);
+ return allowed;
+ } catch (OpenFgaEvaluationException | RuntimeException e) {
+ boolean unavailable = isDecisionPointUnavailable(e);
+ observation.complete(unavailable ? Outcome.UNAVAILABLE :
Outcome.ERROR,
+ AuthorizationObservation.interrupted(e) ?
Failure.INTERRUPTED
+ : unavailable ? Failure.UNAVAILABLE :
Failure.EVALUATION);
+ throw e;
+ }
+ }
+
+ private boolean checkInternal(Exchange exchange) throws
OpenFgaEvaluationException {
// Clear first, and before anything is resolved. A verdict a message
arrived with is a claim, not evidence, and
// overwriting at the end would not be enough: the paths that throw
never reach the end, and a route that
// handles the exception would carry on with the sender's own verdict
still on the message. Clearing before the
@@ -271,7 +297,7 @@ public class OpenFgaAuthorizer {
* A 429 is the exception that proves the rule: it is a 4xx by status
class, but what it says is "not right now",
* which is precisely a decision point that could not answer.
*/
- private static boolean isDecisionPointUnavailable(Throwable failure) {
+ static boolean isDecisionPointUnavailable(Throwable failure) {
boolean looksUnavailable = false;
for (Throwable cause = failure; cause != null; cause =
cause.getCause()) {
if (cause instanceof FgaError error) {
diff --git
a/components/camel-openfga/src/main/java/org/apache/camel/component/openfga/OpenFgaProducer.java
b/components/camel-openfga/src/main/java/org/apache/camel/component/openfga/OpenFgaProducer.java
index 733a9ea812a5..699151362a9a 100644
---
a/components/camel-openfga/src/main/java/org/apache/camel/component/openfga/OpenFgaProducer.java
+++
b/components/camel-openfga/src/main/java/org/apache/camel/component/openfga/OpenFgaProducer.java
@@ -73,6 +73,11 @@ import org.apache.camel.InvalidPayloadException;
import org.apache.camel.health.HealthCheckHelper;
import org.apache.camel.health.WritableHealthCheckRepository;
import org.apache.camel.support.DefaultProducer;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Failure;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Operation;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.apache.camel.support.security.AuthorizationObservation;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -176,14 +181,36 @@ public class OpenFgaProducer extends DefaultProducer {
* allowed - so a route can filter a collection down to what the caller
may see in one step.
*/
private void batchCheck(Exchange exchange, OpenFgaAuthorizer authorizer)
throws Exception {
+ AuthorizationObservation observation =
AuthorizationObservation.begin(exchange, Engine.OPENFGA, Operation.BATCH,
+ getEndpoint().getConfiguration().getAuthorizationModelId());
+ if (!observation.isEnabled()) {
+ batchCheckInternal(exchange, authorizer, observation);
+ return;
+ }
+ try {
+ batchCheckInternal(exchange, authorizer, observation);
+ observation.completeBatch();
+ } catch (Exception e) {
+ boolean unavailable =
OpenFgaAuthorizer.isDecisionPointUnavailable(e);
+ observation.failure(unavailable ? Outcome.UNAVAILABLE :
Outcome.ERROR,
+ AuthorizationObservation.interrupted(e) ?
Failure.INTERRUPTED
+ : unavailable ? Failure.UNAVAILABLE :
Failure.EVALUATION);
+ throw e;
+ }
+ }
+
+ private void batchCheckInternal(Exchange exchange, OpenFgaAuthorizer
authorizer, AuthorizationObservation observation)
+ throws Exception {
OpenFgaAuthorizer.clearDecisionHeaders(exchange);
List<String> objects = bodyAsList(exchange);
+ observation.expectedItems(objects.size());
String user = authorizer.resolveUser(exchange);
String relation = authorizer.resolveRelation(exchange);
if (user == null || relation == null) {
// the subject or the permission could not be established, so none
of the objects is allowed. The deny
// reason is already on the exchange
exchange.getMessage().setBody(List.of());
+ observation.items(Outcome.DENY, objects.size());
return;
}
@@ -192,6 +219,7 @@ public class OpenFgaProducer extends DefaultProducer {
// a configured contextual tuple did not resolve, so no object is
allowed; the reason is on the exchange
exchange.getMessage().setHeader(OpenFgaConstants.ALLOWED, false);
exchange.getMessage().setBody(List.of());
+ observation.items(Outcome.DENY, objects.size());
return;
}
@@ -201,6 +229,7 @@ public class OpenFgaProducer extends DefaultProducer {
// an entry that cannot be an object of a check is not one the
caller may have; leaving it out of the
// batch leaves it out of the result, which is the fail-closed
answer
LOG.debug("Skipping '{}' in a batchCheck: not usable as an
object identifier", object);
+ observation.item(Outcome.DENY);
continue;
}
ClientCheckRequest item = new
ClientCheckRequest().user(user).relation(relation)._object(object);
@@ -216,15 +245,16 @@ public class OpenFgaProducer extends DefaultProducer {
}
List<String> allowed =
getEndpoint().getConfiguration().getBatchCheckMode() ==
OpenFgaBatchCheckMode.server
- ? serverBatchCheck(exchange, authorizer, requests)
- : clientBatchCheck(exchange, authorizer, requests, objects,
user, relation);
+ ? serverBatchCheck(exchange, authorizer, requests, observation)
+ : clientBatchCheck(exchange, authorizer, requests, objects,
user, relation, observation);
+ observation.remainingItems(Outcome.DENY, objects.size());
exchange.getMessage().setHeader(OpenFgaConstants.ALLOWED,
!allowed.isEmpty());
exchange.getMessage().setBody(allowed);
}
private List<String> clientBatchCheck(
Exchange exchange, OpenFgaAuthorizer authorizer,
List<ClientCheckRequest> requests,
- List<String> objects, String user, String relation)
+ List<String> objects, String user, String relation,
AuthorizationObservation observation)
throws Exception {
int maxParallelRequests =
getEndpoint().getConfiguration().getMaxParallelRequests();
ClientBatchCheckClientOptions options = new
ClientBatchCheckClientOptions()
@@ -255,6 +285,9 @@ public class OpenFgaProducer extends DefaultProducer {
}
if (Boolean.TRUE.equals(response.getAllowed())) {
permitted.add(response.getRequest().getObject());
+ observation.item(Outcome.ALLOW);
+ } else {
+ observation.item(Outcome.DENY);
}
}
// filter the body rather than collect the answers: the SDK issues the
checks in parallel and hands them back
@@ -269,7 +302,9 @@ public class OpenFgaProducer extends DefaultProducer {
return allowed;
}
- private List<String> serverBatchCheck(Exchange exchange, OpenFgaAuthorizer
authorizer, List<ClientCheckRequest> requests)
+ private List<String> serverBatchCheck(
+ Exchange exchange, OpenFgaAuthorizer authorizer,
List<ClientCheckRequest> requests,
+ AuthorizationObservation observation)
throws Exception {
List<ClientBatchCheckItem> checks = new ArrayList<>(requests.size());
Set<String> pending = new HashSet<>();
@@ -307,6 +342,9 @@ public class OpenFgaProducer extends DefaultProducer {
}
if (result.isAllowed()) {
permitted.add(result.getCorrelationId());
+ observation.item(Outcome.ALLOW);
+ } else {
+ observation.item(Outcome.DENY);
}
}
if (!pending.isEmpty()) {
diff --git
a/components/camel-openfga/src/test/java/org/apache/camel/component/openfga/OpenFgaAuthorizationObservationTest.java
b/components/camel-openfga/src/test/java/org/apache/camel/component/openfga/OpenFgaAuthorizationObservationTest.java
new file mode 100644
index 000000000000..e2c99fbed367
--- /dev/null
+++
b/components/camel-openfga/src/test/java/org/apache/camel/component/openfga/OpenFgaAuthorizationObservationTest.java
@@ -0,0 +1,211 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.openfga;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+
+import dev.openfga.sdk.api.client.OpenFgaClient;
+import dev.openfga.sdk.api.client.model.ClientBatchCheckClientResponse;
+import dev.openfga.sdk.api.client.model.ClientBatchCheckResponse;
+import dev.openfga.sdk.api.client.model.ClientBatchCheckSingleResponse;
+import dev.openfga.sdk.api.client.model.ClientCheckRequest;
+import dev.openfga.sdk.api.client.model.ClientCheckResponse;
+import org.apache.camel.Exchange;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.EventNotifierSupport;
+import org.apache.camel.support.security.AuthorizationDecisionEvent;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class OpenFgaAuthorizationObservationTest {
+ @Test
+ void observesDecisionsAndConfiguredModelWithoutSubjectsOrResources()
throws Exception {
+ try (Fixture fixture = new Fixture()) {
+ ClientCheckResponse allowed = mock(ClientCheckResponse.class);
+ when(allowed.getAllowed()).thenReturn(true);
+ ClientCheckResponse denied = mock(ClientCheckResponse.class);
+ when(denied.getAllowed()).thenReturn(false);
+ when(fixture.client.check(any(),
any())).thenReturn(CompletableFuture.completedFuture(allowed))
+ .thenReturn(CompletableFuture.completedFuture(denied))
+ .thenReturn(CompletableFuture.failedFuture(new
IllegalStateException("secret-error")));
+ OpenFgaAuthorizer authorizer = new
OpenFgaAuthorizer(fixture.client, fixture.configuration, fixture.context);
+ Exchange exchange = new DefaultExchange(fixture.context);
+ assertThat(authorizer.check(exchange)).isTrue();
+ assertThat(authorizer.check(exchange)).isFalse();
+ assertThatThrownBy(() ->
authorizer.check(exchange)).isInstanceOf(OpenFgaEvaluationException.class);
+
assertThat(fixture.events).extracting(AuthorizationDecisionEvent::getOutcome)
+ .containsExactly(Outcome.ALLOW, Outcome.DENY,
Outcome.ERROR);
+ assertThat(fixture.events).allSatisfy(event -> {
+ assertThat(event.getRevision()).isEqualTo("model-1");
+
assertThat(event.asJSon().toString()).doesNotContain("user:secret",
"document:secret", "secret-error");
+
assertThat(event.getExchangeId()).isEqualTo(exchange.getExchangeId());
+ });
+ }
+ }
+
+ @Test
+ void unavailableFailedOpenAndInputDenyAreDistinct() throws Exception {
+ try (Fixture fixture = new Fixture()) {
+ when(fixture.client.check(any(),
any())).thenReturn(CompletableFuture.failedFuture(new IOException("offline")));
+ OpenFgaAuthorizer closed = new OpenFgaAuthorizer(fixture.client,
fixture.configuration, fixture.context);
+ assertThatThrownBy(() -> closed.check(new
DefaultExchange(fixture.context)))
+ .isInstanceOf(OpenFgaEvaluationException.class);
+ fixture.configuration.setFailOpen(true);
+ OpenFgaAuthorizer open = new OpenFgaAuthorizer(fixture.client,
fixture.configuration, fixture.context);
+ assertThat(open.check(new
DefaultExchange(fixture.context))).isTrue();
+ fixture.configuration.setUser("${header.missing}");
+ OpenFgaAuthorizer missing = new OpenFgaAuthorizer(fixture.client,
fixture.configuration, fixture.context);
+ assertThat(missing.check(new
DefaultExchange(fixture.context))).isFalse();
+
assertThat(fixture.events).extracting(AuthorizationDecisionEvent::getOutcome)
+ .containsExactly(Outcome.UNAVAILABLE, Outcome.FAILED_OPEN,
Outcome.DENY);
+ }
+ }
+
+ @Test
+ void partialBatchFailureDoesNotClaimTheFilterWasSuccessful() throws
Exception {
+ try (Fixture fixture = new Fixture()) {
+ var a = item("document:a", true, null);
+ var b = item("document:b", false, null);
+ var c = item("document:c", false, new
IllegalStateException("secret-error"));
+ when(fixture.client.clientBatchCheck(anyList(), any()))
+ .thenReturn(CompletableFuture.completedFuture(List.of(a,
b, c)));
+ var endpoint
+ = new OpenFgaEndpoint("openfga:batchCheck", new
OpenFgaComponent(fixture.context), fixture.configuration);
+ endpoint.setOperation(OpenFgaOperation.batchCheck);
+ endpoint.start();
+ var producer = new OpenFgaProducer(endpoint);
+ producer.start();
+ try {
+ Exchange exchange = new DefaultExchange(fixture.context);
+ exchange.getMessage().setBody(List.of("document:a",
"document:b", "document:c"));
+ assertThatThrownBy(() ->
producer.process(exchange)).isInstanceOf(OpenFgaEvaluationException.class);
+ assertThat(fixture.events).hasSize(1);
+
assertThat(fixture.events.getFirst().getOutcome()).isEqualTo(Outcome.ERROR);
+ assertThat(fixture.events.getFirst().getCounts())
+ .isEqualTo(new AuthorizationDecisionEvent.Counts(1, 1,
1, 0, 0));
+ } finally {
+ producer.stop();
+ endpoint.stop();
+ }
+ }
+ }
+
+ @Test
+ void
nativeServerBatchObservesEachCorrelatedDecisionIncludingDuplicateObjects()
throws Exception {
+ try (Fixture fixture = new Fixture()) {
+
fixture.configuration.setBatchCheckMode(OpenFgaBatchCheckMode.server);
+ when(fixture.client.batchCheck(any(),
any())).thenReturn(CompletableFuture.completedFuture(
+ new ClientBatchCheckResponse(
+ List.of(
+ new ClientBatchCheckSingleResponse(true,
null, "2", null),
+ new ClientBatchCheckSingleResponse(true,
null, "0", null),
+ new ClientBatchCheckSingleResponse(false,
null, "1", null)))));
+ var endpoint
+ = new OpenFgaEndpoint("openfga:batchCheck", new
OpenFgaComponent(fixture.context), fixture.configuration);
+ endpoint.setOperation(OpenFgaOperation.batchCheck);
+ endpoint.start();
+ var producer = new OpenFgaProducer(endpoint);
+ producer.start();
+ try {
+ Exchange exchange = new DefaultExchange(fixture.context);
+ exchange.getMessage().setBody(List.of("document:a",
"document:b", "document:a"));
+ producer.process(exchange);
+
assertThat(exchange.getMessage().getBody(List.class)).containsExactly("document:a",
"document:a");
+ assertThat(fixture.events).hasSize(1);
+ assertThat(fixture.events.getFirst().getCounts())
+ .isEqualTo(new AuthorizationDecisionEvent.Counts(2, 1,
0, 0, 0));
+
assertThat(fixture.events.getFirst().getOperation()).isEqualTo(AuthorizationDecisionEvent.Operation.BATCH);
+ } finally {
+ producer.stop();
+ endpoint.stop();
+ }
+ }
+ }
+
+ @Test
+ void atomicRelationshipWriteDoesNotPublishAnAuthorizationDecision() throws
Exception {
+ try (Fixture fixture = new Fixture()) {
+ when(fixture.client.write(any(),
any())).thenReturn(CompletableFuture.completedFuture(null));
+ var endpoint = new OpenFgaEndpoint("openfga:write", new
OpenFgaComponent(fixture.context), fixture.configuration);
+ endpoint.setOperation(OpenFgaOperation.write);
+ endpoint.start();
+ var producer = new OpenFgaProducer(endpoint);
+ producer.start();
+ try {
+ Exchange exchange = new DefaultExchange(fixture.context);
+ producer.process(exchange);
+ assertThat(fixture.events).isEmpty();
+
assertThat(exchange.getMessage().getHeader(OpenFgaConstants.WRITTEN_TUPLES)).isEqualTo(1);
+ } finally {
+ producer.stop();
+ endpoint.stop();
+ }
+ }
+ }
+
+ private static ClientBatchCheckClientResponse item(String object, boolean
allowed, Throwable error) {
+ var item = mock(ClientBatchCheckClientResponse.class);
+ when(item.getRequest()).thenReturn(new
ClientCheckRequest()._object(object));
+ when(item.getAllowed()).thenReturn(allowed);
+ when(item.getThrowable()).thenReturn(error);
+ return item;
+ }
+
+ private static class Fixture implements AutoCloseable {
+ final DefaultCamelContext context = new DefaultCamelContext();
+ final OpenFgaClient client = mock(OpenFgaClient.class);
+ final OpenFgaConfiguration configuration = new OpenFgaConfiguration();
+ final List<AuthorizationDecisionEvent> events = new ArrayList<>();
+
+ Fixture() throws Exception {
+ configuration.setOpenFgaClient(client);
+ configuration.setUser("user:secret");
+ configuration.setRelation("reader");
+ configuration.setObject("document:secret");
+ configuration.setAuthorizationModelId("model-1");
+ context.getManagementStrategy().addEventNotifier(new
EventNotifierSupport() {
+ @Override
+ public boolean isEnabled(CamelEvent event) {
+ return event instanceof AuthorizationDecisionEvent;
+ }
+
+ @Override
+ public void notify(CamelEvent event) {
+ events.add((AuthorizationDecisionEvent) event);
+ }
+ });
+ context.start();
+ }
+
+ @Override
+ public void close() throws Exception {
+ context.close();
+ }
+ }
+}
diff --git a/components/camel-spiffe/pom.xml b/components/camel-spiffe/pom.xml
index e3625314bae7..7866378b4ae3 100644
--- a/components/camel-spiffe/pom.xml
+++ b/components/camel-spiffe/pom.xml
@@ -61,6 +61,12 @@
<version>${java-spiffe-version}</version>
</dependency>
+ <!-- The SDK exposes gRPC failures at runtime; observation classifies
their status codes. -->
+ <dependency>
+ <groupId>io.grpc</groupId>
+ <artifactId>grpc-api</artifactId>
+ </dependency>
+
<!-- for testing -->
<dependency>
<groupId>org.apache.camel</groupId>
diff --git a/components/camel-spiffe/src/main/docs/spiffe-component.adoc
b/components/camel-spiffe/src/main/docs/spiffe-component.adoc
index e15b62e8b0b6..50cf86c81e04 100644
--- a/components/camel-spiffe/src/main/docs/spiffe-component.adoc
+++ b/components/camel-spiffe/src/main/docs/spiffe-component.adoc
@@ -668,3 +668,10 @@ No token, private key, certificate contents or exception
text is retained or pub
no independent unsubscribe handle for a borrowed client. Supply your own
health check for that injected client. If
`allowOperationHeader=true` is explicitly enabled, changing an individual
message's operation does not retarget the
readiness observer, which always reflects the endpoint's configured operation.
+
+== Authorization observations
+
+See xref:manual::authorization-observability.adoc[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.
diff --git
a/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeJwtSecurityProcessor.java
b/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeJwtSecurityProcessor.java
index f38dad28c227..663bfa0d4a40 100644
---
a/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeJwtSecurityProcessor.java
+++
b/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeJwtSecurityProcessor.java
@@ -23,6 +23,11 @@ import org.apache.camel.CamelAuthorizationException;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.support.processor.DelegateAsyncProcessor;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Failure;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Operation;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.apache.camel.support.security.AuthorizationObservation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -61,14 +66,18 @@ final class SpiffeJwtSecurityProcessor extends
DelegateAsyncProcessor {
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
+ AuthorizationObservation observation
+ = AuthorizationObservation.begin(exchange, Engine.SPIFFE,
Operation.VALIDATE_JWT, null);
try {
JwtSvid svid = SpiffeJwtValidator.validate(
- endpoint.getWorkloadApiClient(), exchange,
endpoint.getConfiguration().getAudience(), false);
+ endpoint.getWorkloadApiClient(), exchange,
endpoint.getConfiguration().getAudience(), false, false);
if (!policy.isAuthorized(svid.getSpiffeId())) {
throw new IllegalArgumentException("Validated SPIFFE identity
is not authorized by this policy");
}
SpiffeJwtValidator.recordIdentity(exchange, svid, false);
+ observation.complete(Outcome.ALLOW, Failure.NONE);
} catch (Exception e) {
+ SpiffeJwtValidator.recordFailure(observation, e);
// Only the class of the failure is logged: the message of the SDK
exception may contain the credential.
// A failure that is not a verdict on the token, such as the
Workload API being unreachable, is worth a
// warning, since to the caller every failure is the same 401 and
an outage would look like a 401 storm.
diff --git
a/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeJwtValidator.java
b/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeJwtValidator.java
index efeb28ba5d1b..3fff225b3cf3 100644
---
a/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeJwtValidator.java
+++
b/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeJwtValidator.java
@@ -18,11 +18,17 @@ package org.apache.camel.component.spiffe;
import java.util.Arrays;
+import io.grpc.Status;
import io.spiffe.exception.JwtSvidException;
import io.spiffe.svid.jwtsvid.JwtSvid;
import io.spiffe.workloadapi.WorkloadApiClient;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Failure;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Operation;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.apache.camel.support.security.AuthorizationObservation;
import org.apache.camel.util.ObjectHelper;
/** Shared JWT validation for the producer and the route security policy. */
@@ -32,6 +38,43 @@ final class SpiffeJwtValidator {
static JwtSvid validate(WorkloadApiClient client, Exchange exchange,
String configuredAudience, boolean allowBodyToken)
throws JwtSvidException {
+ return validate(client, exchange, configuredAudience, allowBodyToken,
true);
+ }
+
+ static JwtSvid validate(
+ WorkloadApiClient client, Exchange exchange, String
configuredAudience, boolean allowBodyToken,
+ boolean observe)
+ throws JwtSvidException {
+ if (!observe) {
+ return validateInternal(client, exchange, configuredAudience,
allowBodyToken);
+ }
+ AuthorizationObservation observation
+ = AuthorizationObservation.begin(exchange, Engine.SPIFFE,
Operation.VALIDATE_JWT, null);
+ try {
+ JwtSvid result = validateInternal(client, exchange,
configuredAudience, allowBodyToken);
+ observation.complete(Outcome.ALLOW, Failure.NONE);
+ return result;
+ } catch (JwtSvidException | RuntimeException e) {
+ recordFailure(observation, e);
+ throw e;
+ }
+ }
+
+ static void recordFailure(AuthorizationObservation observation, Exception
e) {
+ boolean interrupted = AuthorizationObservation.interrupted(e);
+ Status.Code code = Status.fromThrowable(e).getCode();
+ boolean unavailable = !interrupted && (code == Status.Code.UNAVAILABLE
|| code == Status.Code.DEADLINE_EXCEEDED);
+ boolean denied = e instanceof JwtSvidException || e instanceof
IllegalArgumentException;
+ observation.complete(
+ interrupted ? Outcome.ERROR : unavailable ?
Outcome.UNAVAILABLE : denied ? Outcome.DENY : Outcome.ERROR,
+ interrupted ? Failure.INTERRUPTED : unavailable ?
Failure.UNAVAILABLE : denied ? Failure.NONE
+ : Failure.EVALUATION);
+ }
+
+ private static JwtSvid validateInternal(
+ WorkloadApiClient client, Exchange exchange, String
configuredAudience,
+ boolean allowBodyToken)
+ throws JwtSvidException {
clearIdentity(exchange);
Message message = exchange.getMessage();
String token = message.getHeader(SpiffeConstants.TOKEN, String.class);
diff --git
a/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeSecurityProcessor.java
b/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeSecurityProcessor.java
index fce3ba6526dd..9ef485955f1f 100644
---
a/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeSecurityProcessor.java
+++
b/components/camel-spiffe/src/main/java/org/apache/camel/component/spiffe/SpiffeSecurityProcessor.java
@@ -22,6 +22,11 @@ import org.apache.camel.CamelAuthorizationException;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.support.processor.DelegateAsyncProcessor;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Failure;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Operation;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.apache.camel.support.security.AuthorizationObservation;
/**
* Enforces a {@link SpiffeSecurityPolicy} before the wrapped processor runs.
@@ -52,6 +57,24 @@ public class SpiffeSecurityProcessor extends
DelegateAsyncProcessor {
}
protected void authorize(Exchange exchange) throws
CamelAuthorizationException {
+ AuthorizationObservation observation =
AuthorizationObservation.begin(exchange, Engine.SPIFFE, Operation.MTLS, null);
+ if (!observation.isEnabled()) {
+ authorizeInternal(exchange);
+ return;
+ }
+ try {
+ authorizeInternal(exchange);
+ observation.complete(Outcome.ALLOW, Failure.NONE);
+ } catch (CamelAuthorizationException e) {
+ observation.complete(Outcome.DENY, Failure.NONE);
+ throw e;
+ } catch (RuntimeException e) {
+ observation.complete(Outcome.ERROR, Failure.EVALUATION);
+ throw e;
+ }
+ }
+
+ private void authorizeInternal(Exchange exchange) throws
CamelAuthorizationException {
SpiffeId peer = SpiffePeerIdentity.fromExchange(exchange,
policy.getSslSessionHeader());
if (peer == null) {
markFailure(exchange);
diff --git
a/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/SpiffeAuthorizationObservationTest.java
b/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/SpiffeAuthorizationObservationTest.java
new file mode 100644
index 000000000000..b9977b4dabc8
--- /dev/null
+++
b/components/camel-spiffe/src/test/java/org/apache/camel/component/spiffe/SpiffeAuthorizationObservationTest.java
@@ -0,0 +1,185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.spiffe;
+
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.net.ssl.SSLSession;
+
+import io.grpc.Status;
+import io.spiffe.exception.JwtSvidException;
+import io.spiffe.spiffeid.SpiffeId;
+import io.spiffe.svid.jwtsvid.JwtSvid;
+import io.spiffe.workloadapi.WorkloadApiClient;
+import org.apache.camel.AsyncProcessor;
+import org.apache.camel.CamelAuthorizationException;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.Route;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.EventNotifierSupport;
+import org.apache.camel.support.security.AuthorizationDecisionEvent;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.apache.camel.support.service.ServiceHelper;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class SpiffeAuthorizationObservationTest {
+ @Test
+ void observesVerifiedMtlsAndMissingIdentityWithoutRecordingThePeer()
throws Exception {
+ try (Fixture fixture = new Fixture()) {
+ var policy = new SpiffeSecurityPolicy();
+ policy.setAcceptAnySpiffeId(true);
+ var processor = new SpiffeSecurityProcessor(exchange -> {
+ }, policy);
+ Exchange exchange = new DefaultExchange(fixture.context);
+ assertThatThrownBy(() ->
processor.authorize(exchange)).isInstanceOf(CamelAuthorizationException.class);
+ X509Certificate certificate = mock(X509Certificate.class);
+
when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6,
"spiffe://example.org/secret-peer")));
+ SSLSession session = mock(SSLSession.class);
+ when(session.getPeerCertificates()).thenReturn(new Certificate[] {
certificate });
+
exchange.getMessage().setHeader(SpiffeSecurityPolicy.DEFAULT_SSL_SESSION_HEADER,
session);
+ processor.authorize(exchange);
+
assertThat(exchange.getProperty(SpiffeConstants.PEER_SPIFFE_ID)).isEqualTo("spiffe://example.org/secret-peer");
+
assertThat(fixture.events).extracting(AuthorizationDecisionEvent::getOutcome).containsExactly(Outcome.DENY,
+ Outcome.ALLOW);
+ assertThat(fixture.events).allSatisfy(event -> {
+
assertThat(event.getOperation()).isEqualTo(AuthorizationDecisionEvent.Operation.MTLS);
+
assertThat(event.asJSon().toString()).doesNotContain("secret-peer");
+
assertThat(event.getExchangeId()).isEqualTo(exchange.getExchangeId());
+ });
+ }
+ }
+
+ @Test
+ void observesJwtValidationSuccessDenialAndWorkloadApiUnavailable() throws
Exception {
+ try (Fixture fixture = new Fixture()) {
+ WorkloadApiClient client = mock(WorkloadApiClient.class);
+ JwtSvid svid = mock(JwtSvid.class);
+
when(svid.getSpiffeId()).thenReturn(SpiffeId.parse("spiffe://example.org/secret-peer"));
+ when(client.validateJwtSvid("secret-token",
"audience")).thenReturn(svid)
+ .thenThrow(new JwtSvidException("secret-rejected-token"))
+ .thenThrow(new JwtSvidException("secret-transport",
Status.UNAVAILABLE.asRuntimeException()));
+ SpiffeConfiguration configuration = new SpiffeConfiguration();
+ configuration.setWorkloadApiClient(client);
+ configuration.setOperation(SpiffeOperation.validateJwtSvid);
+ configuration.setAudience("audience");
+ var endpoint = new SpiffeEndpoint("spiffe:validate", new
SpiffeComponent(fixture.context), configuration);
+ endpoint.start();
+ var producer = new SpiffeProducer(endpoint);
+ producer.start();
+ try {
+ for (int index = 0; index < 3; index++) {
+ Exchange exchange = new DefaultExchange(fixture.context);
+ exchange.getMessage().setHeader(SpiffeConstants.TOKEN,
"secret-token");
+ if (index == 0) {
+ producer.process(exchange);
+ } else {
+ assertThatThrownBy(() ->
producer.process(exchange)).isInstanceOf(JwtSvidException.class);
+ }
+ }
+
assertThat(fixture.events).extracting(AuthorizationDecisionEvent::getOutcome)
+ .containsExactly(Outcome.ALLOW, Outcome.DENY,
Outcome.UNAVAILABLE);
+ assertThat(fixture.events).allSatisfy(event -> {
+
assertThat(event.getOperation()).isEqualTo(AuthorizationDecisionEvent.Operation.VALIDATE_JWT);
+
assertThat(event.asJSon().toString()).doesNotContain("secret-peer",
"secret-token", "secret-transport");
+ });
+ } finally {
+ producer.stop();
+ endpoint.stop();
+ }
+ }
+ }
+
+ @Test
+ void jwtPolicyRecordsItsFinalVerdictOnceAndPreservesThePayload() throws
Exception {
+ try (Fixture fixture = new Fixture()) {
+ WorkloadApiClient client = mock(WorkloadApiClient.class);
+ JwtSvid svid = mock(JwtSvid.class);
+
when(svid.getSpiffeId()).thenReturn(SpiffeId.parse("spiffe://example.org/accepted"));
+ when(client.validateJwtSvid("token", "audience")).thenReturn(svid);
+ SpiffeJwtSecurityPolicy policy = new SpiffeJwtSecurityPolicy();
+ policy.setAudience("audience");
+ policy.setAcceptedSpiffeIds("spiffe://example.org/accepted");
+ policy.setWorkloadApiClient(client);
+ Route route = mock(Route.class);
+ when(route.getCamelContext()).thenReturn(fixture.context);
+ policy.beforeWrap(route, null);
+ Processor wrapped
+ = policy.wrap(route, exchange ->
assertThat(exchange.getMessage().getBody()).isEqualTo("payload"));
+ ServiceHelper.startService(wrapped);
+ try {
+ Exchange allowed = new DefaultExchange(fixture.context);
+ allowed.getMessage().setHeader(SpiffeConstants.TOKEN, "token");
+ allowed.getMessage().setBody("payload");
+ ((AsyncProcessor) wrapped).process(allowed, done -> {
+ });
+ assertThat(allowed.getException()).isNull();
+
assertThat(allowed.getMessage().getBody()).isEqualTo("payload");
+
assertThat(allowed.getProperty(SpiffeConstants.JWT_IDENTITY)).isInstanceOf(SpiffeJwtIdentity.class);
+
when(svid.getSpiffeId()).thenReturn(SpiffeId.parse("spiffe://example.org/rejected"));
+ Exchange denied = new DefaultExchange(fixture.context);
+ denied.getMessage().setHeader(SpiffeConstants.TOKEN, "token");
+ denied.getMessage().setBody("payload");
+ ((AsyncProcessor) wrapped).process(denied, done -> {
+ });
+
assertThat(denied.getException()).isInstanceOf(CamelAuthorizationException.class);
+
assertThat(denied.getProperty(SpiffeConstants.JWT_IDENTITY)).isNull();
+
assertThat(fixture.events).extracting(AuthorizationDecisionEvent::getOutcome)
+ .containsExactly(Outcome.ALLOW, Outcome.DENY);
+ assertThat(fixture.events).allSatisfy(
+ event ->
assertThat(event.getOperation()).isEqualTo(AuthorizationDecisionEvent.Operation.VALIDATE_JWT));
+ } finally {
+ ServiceHelper.stopService(wrapped);
+ }
+ }
+ }
+
+ private static class Fixture implements AutoCloseable {
+ final DefaultCamelContext context = new DefaultCamelContext();
+ final List<AuthorizationDecisionEvent> events = new ArrayList<>();
+
+ Fixture() throws Exception {
+ context.getManagementStrategy().addEventNotifier(new
EventNotifierSupport() {
+ @Override
+ public boolean isEnabled(CamelEvent event) {
+ return event instanceof AuthorizationDecisionEvent;
+ }
+
+ @Override
+ public void notify(CamelEvent event) {
+ events.add((AuthorizationDecisionEvent) event);
+ }
+ });
+ context.start();
+ }
+
+ @Override
+ public void close() throws Exception {
+ context.close();
+ }
+ }
+}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/EventHelper.java
b/core/camel-support/src/main/java/org/apache/camel/support/EventHelper.java
index b4e597256f17..6b627722718d 100644
--- a/core/camel-support/src/main/java/org/apache/camel/support/EventHelper.java
+++ b/core/camel-support/src/main/java/org/apache/camel/support/EventHelper.java
@@ -1628,6 +1628,44 @@ public final class EventHelper {
return answer;
}
+ /**
+ * Delivers an application-defined event through the standard notifier
isolation and logging path. Custom events are
+ * filtered by {@link EventNotifier#isEnabled(CamelEvent)}, independently
of exchange event opt-outs.
+ *
+ * @since 4.24
+ */
+ public static boolean notifyCustomEvent(CamelContext context,
Supplier<CamelEvent> eventSupplier) {
+ try {
+ ManagementStrategy management = context != null ?
context.getManagementStrategy() : null;
+ List<EventNotifier> notifiers = management != null ?
management.getStartedEventNotifiers() : null;
+ if (notifiers == null || notifiers.isEmpty()) {
+ return false;
+ }
+ boolean answer = false;
+ CamelEvent event = null;
+ for (EventNotifier notifier : notifiers) {
+ try {
+ if (notifier.isDisabled()) {
+ continue;
+ }
+ if (event == null) {
+ event = eventSupplier.get();
+ if (event == null) {
+ return answer;
+ }
+ }
+ answer |= doNotifyEvent(notifier, event);
+ } catch (Throwable e) {
+ LOG.warn("Error notifying custom event. This exception
will be ignored.", e);
+ }
+ }
+ return answer;
+ } catch (Throwable e) {
+ LOG.warn("Error obtaining custom event notifiers. This exception
will be ignored.", e);
+ return false;
+ }
+ }
+
private static boolean isDisabledOrIgnored(EventNotifier notifier) {
return notifier.isDisabled() || notifier.isIgnoreExchangeEvents();
}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/security/AuthorizationDecisionEvent.java
b/core/camel-support/src/main/java/org/apache/camel/support/security/AuthorizationDecisionEvent.java
new file mode 100644
index 000000000000..a112c8fc3be8
--- /dev/null
+++
b/core/camel-support/src/main/java/org/apache/camel/support/security/AuthorizationDecisionEvent.java
@@ -0,0 +1,234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.support.security;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+import org.apache.camel.spi.CamelEvent;
+
+/**
+ * Immutable authorization observation, without credentials, subjects,
resources, inputs, exceptions or Exchange
+ * references. Correlation and configured revision are event fields, never
default metric labels. Unknown revisions are
+ * null.
+ *
+ * @since 4.24
+ */
+public final class AuthorizationDecisionEvent implements CamelEvent {
+ public enum Engine {
+ OPA_REST,
+ OPA_WASM,
+ OPENFGA,
+ SPIFFE
+ }
+
+ public enum Operation {
+ DECISION,
+ BATCH,
+ MTLS,
+ VALIDATE_JWT
+ }
+
+ public enum Outcome {
+ ALLOW,
+ DENY,
+ ERROR,
+ UNAVAILABLE,
+ FAILED_OPEN
+ }
+
+ public enum Failure {
+ NONE,
+ EVALUATION,
+ UNAVAILABLE,
+ INTERRUPTED
+ }
+
+ /** Counts distinguish actual decisions from elements that never obtained
a decision. */
+ public static final class Counts {
+ private final long allowed;
+ private final long denied;
+ private final long errors;
+ private final long unavailable;
+ private final long failedOpen;
+
+ public Counts(long allowed, long denied, long errors, long
unavailable, long failedOpen) {
+ this.allowed = allowed;
+ this.denied = denied;
+ this.errors = errors;
+ this.unavailable = unavailable;
+ this.failedOpen = failedOpen;
+ }
+
+ public long allowed() {
+ return allowed;
+ }
+
+ public long denied() {
+ return denied;
+ }
+
+ public long errors() {
+ return errors;
+ }
+
+ public long unavailable() {
+ return unavailable;
+ }
+
+ public long failedOpen() {
+ return failedOpen;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof Counts counts)) {
+ return false;
+ }
+ return allowed == counts.allowed && denied == counts.denied &&
errors == counts.errors
+ && unavailable == counts.unavailable && failedOpen ==
counts.failedOpen;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(allowed, denied, errors, unavailable,
failedOpen);
+ }
+
+ @Override
+ public String toString() {
+ return "Counts[allowed=" + allowed + ", denied=" + denied + ",
errors=" + errors
+ + ", unavailable=" + unavailable + ", failedOpen=" +
failedOpen + "]";
+ }
+ }
+
+ private final Engine engine;
+ private final Operation operation;
+ private final Outcome outcome;
+ private final Failure failure;
+ private final long durationNanos;
+ private final long poolWaitNanos;
+ private final Counts counts;
+ private final String revision;
+ private final String exchangeId;
+ private final String routeId;
+ private final long timestamp;
+
+ AuthorizationDecisionEvent(Engine engine, Operation operation, Outcome
outcome, Failure failure, long durationNanos,
+ long poolWaitNanos, Counts counts, String
revision, String exchangeId, String routeId) {
+ this.engine = engine;
+ this.operation = operation;
+ this.outcome = outcome;
+ this.failure = failure;
+ this.durationNanos = durationNanos;
+ this.poolWaitNanos = poolWaitNanos;
+ this.counts = counts;
+ this.revision = revision;
+ this.exchangeId = exchangeId;
+ this.routeId = routeId;
+ this.timestamp = System.currentTimeMillis();
+ }
+
+ public Engine getEngine() {
+ return engine;
+ }
+
+ public Operation getOperation() {
+ return operation;
+ }
+
+ public Outcome getOutcome() {
+ return outcome;
+ }
+
+ public Failure getFailure() {
+ return failure;
+ }
+
+ public long getDurationNanos() {
+ return durationNanos;
+ }
+
+ /** Borrow wait, including a failed borrow, or -1 when this operation does
not use a WASM pool. */
+ public long getPoolWaitNanos() {
+ return poolWaitNanos;
+ }
+
+ public Counts getCounts() {
+ return counts;
+ }
+
+ /** Configured model revision, or null when the actual revision is not
known. */
+ public String getRevision() {
+ return revision;
+ }
+
+ public String getExchangeId() {
+ return exchangeId;
+ }
+
+ public String getRouteId() {
+ return routeId;
+ }
+
+ @Override
+ public Type getType() {
+ return Type.Custom;
+ }
+
+ @Override
+ public Object getSource() {
+ return engine;
+ }
+
+ @Override
+ public long getTimestamp() {
+ return timestamp;
+ }
+
+ @Override
+ public void setTimestamp(long timestamp) {
+ throw new UnsupportedOperationException("Immutable authorization
event");
+ }
+
+ @Override
+ public Map<String, Object> asJSon() {
+ Map<String, Object> values = new LinkedHashMap<>();
+ values.put("engine", engine.name());
+ values.put("operation", operation.name());
+ values.put("outcome", outcome.name());
+ values.put("failure", failure.name());
+ values.put("durationNanos", durationNanos);
+ values.put("poolWaitNanos", poolWaitNanos);
+ values.put("counts", Map.of("allowed", counts.allowed(), "denied",
counts.denied(), "errors", counts.errors(),
+ "unavailable", counts.unavailable(), "failedOpen",
counts.failedOpen()));
+ values.put("revision", revision);
+ values.put("exchangeId", exchangeId);
+ values.put("routeId", routeId);
+ values.put("timestamp", timestamp);
+ return Collections.unmodifiableMap(values);
+ }
+
+ @Override
+ public String toString() {
+ return "AuthorizationDecisionEvent[engine=" + engine + ", operation="
+ operation + ", outcome=" + outcome + "]";
+ }
+}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/security/AuthorizationObservation.java
b/core/camel-support/src/main/java/org/apache/camel/support/security/AuthorizationObservation.java
new file mode 100644
index 000000000000..e088c1614d25
--- /dev/null
+++
b/core/camel-support/src/main/java/org/apache/camel/support/security/AuthorizationObservation.java
@@ -0,0 +1,187 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.support.security;
+
+import java.util.List;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.spi.EventNotifier;
+import org.apache.camel.support.EventHelper;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Counts;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Failure;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Operation;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Optional authorization events through Camel's started EventNotifiers;
observer failures cannot affect routing.
+ *
+ * @since 4.24
+ */
+public final class AuthorizationObservation {
+ private static final Logger LOG =
LoggerFactory.getLogger(AuthorizationObservation.class);
+ private static final AuthorizationObservation DISABLED = new
AuthorizationObservation();
+ private final CamelContext context;
+ private final Engine engine;
+ private final Operation operation;
+ private final String revision;
+ private final String exchangeId;
+ private final String routeId;
+ private final long started;
+ private long poolWaitNanos = -1;
+ private int expectedItems;
+ private final long[] counts;
+
+ private AuthorizationObservation() {
+ context = null;
+ engine = null;
+ operation = null;
+ revision = null;
+ exchangeId = null;
+ routeId = null;
+ started = 0;
+ counts = null;
+ }
+
+ private AuthorizationObservation(Exchange exchange, Engine engine,
Operation operation, String revision) {
+ this.context = exchange.getContext();
+ this.engine = engine;
+ this.operation = operation;
+ this.revision = revision;
+ this.exchangeId = exchange.getExchangeId();
+ this.routeId = exchange.getFromRouteId();
+ this.started = System.nanoTime();
+ this.counts = new long[Outcome.values().length];
+ }
+
+ public static AuthorizationObservation begin(Exchange exchange, Engine
engine, Operation operation, String revision) {
+ try {
+ for (EventNotifier notifier : notifiers(exchange.getContext())) {
+ try {
+ if (!notifier.isDisabled()) {
+ return new AuthorizationObservation(exchange, engine,
operation, revision);
+ }
+ } catch (Throwable failure) {
+ LOG.warn("Error checking authorization event notifier.
This exception will be ignored.", failure);
+ }
+ }
+ } catch (Throwable failure) {
+ LOG.warn("Error obtaining authorization event notifiers. This
exception will be ignored.", failure);
+ }
+ return DISABLED;
+ }
+
+ private static List<EventNotifier> notifiers(CamelContext context) {
+ if (context == null || context.getManagementStrategy() == null) {
+ return List.of();
+ }
+ List<EventNotifier> result =
context.getManagementStrategy().getStartedEventNotifiers();
+ return result != null ? result : List.of();
+ }
+
+ public boolean isEnabled() {
+ return context != null;
+ }
+
+ public void item(Outcome outcome) {
+ if (isEnabled()) {
+ counts[outcome.ordinal()]++;
+ }
+ }
+
+ public void items(Outcome outcome, int count) {
+ if (isEnabled()) {
+ counts[outcome.ordinal()] += count;
+ }
+ }
+
+ public void expectedItems(int total) {
+ if (isEnabled()) {
+ expectedItems = total;
+ }
+ }
+
+ public void failure(Outcome outcome, Failure failure) {
+ remainingItems(outcome, expectedItems);
+ complete(outcome, failure);
+ }
+
+ public void remainingItems(Outcome outcome, int total) {
+ if (isEnabled()) {
+ long recorded = 0;
+ for (long count : counts) {
+ recorded += count;
+ }
+ counts[outcome.ordinal()] += Math.max(0, total - recorded);
+ }
+ }
+
+ public void poolWait(long nanos) {
+ if (isEnabled() && nanos >= 0) {
+ poolWaitNanos = nanos;
+ }
+ }
+
+ public void complete(Outcome outcome, Failure failure) {
+ if (!isEnabled()) {
+ return;
+ }
+ if (operation != Operation.BATCH) {
+ item(outcome);
+ }
+ publish(outcome, failure);
+ }
+
+ public void completeBatch() {
+ if (!isEnabled()) {
+ return;
+ }
+ Outcome outcome = counts[Outcome.FAILED_OPEN.ordinal()] > 0 ?
Outcome.FAILED_OPEN
+ : counts[Outcome.ERROR.ordinal()] > 0 ? Outcome.ERROR
+ : counts[Outcome.UNAVAILABLE.ordinal()] > 0 ?
Outcome.UNAVAILABLE
+ : counts[Outcome.DENY.ordinal()] > 0 ? Outcome.DENY :
Outcome.ALLOW;
+ Failure failure = counts[Outcome.ERROR.ordinal()] > 0 ?
Failure.EVALUATION
+ : counts[Outcome.UNAVAILABLE.ordinal()] +
counts[Outcome.FAILED_OPEN.ordinal()] > 0
+ ? Failure.UNAVAILABLE
+ : Failure.NONE;
+ publish(outcome, failure);
+ }
+
+ private void publish(Outcome outcome, Failure failure) {
+ AuthorizationDecisionEvent event = new AuthorizationDecisionEvent(
+ engine, operation, outcome, failure,
+ Math.max(0, System.nanoTime() - started), poolWaitNanos,
+ new Counts(
+ counts[Outcome.ALLOW.ordinal()],
counts[Outcome.DENY.ordinal()], counts[Outcome.ERROR.ordinal()],
+ counts[Outcome.UNAVAILABLE.ordinal()],
counts[Outcome.FAILED_OPEN.ordinal()]),
+ revision, exchangeId, routeId);
+ EventHelper.notifyCustomEvent(context, () -> event);
+ }
+
+ public static boolean interrupted(Throwable failure) {
+ Throwable cause = failure;
+ for (int depth = 0; cause != null && depth < 64; depth++, cause =
cause.getCause()) {
+ if (cause instanceof InterruptedException) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git
a/core/camel-support/src/test/java/org/apache/camel/support/security/AuthorizationObservationTest.java
b/core/camel-support/src/test/java/org/apache/camel/support/security/AuthorizationObservationTest.java
new file mode 100644
index 000000000000..9b2b7b4e6834
--- /dev/null
+++
b/core/camel-support/src/test/java/org/apache/camel/support/security/AuthorizationObservationTest.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.support.security;
+
+import java.lang.reflect.Proxy;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Function;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.spi.EventNotifier;
+import org.apache.camel.spi.ManagementStrategy;
+import org.apache.camel.support.SimpleEventNotifierSupport;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Engine;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Operation;
+import org.apache.camel.support.security.AuthorizationDecisionEvent.Outcome;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class AuthorizationObservationTest {
+ @Test
+ void noStartedListenerUsesTheSharedDisabledObservation() {
+ Exchange exchange = exchange(List.of());
+ var first = AuthorizationObservation.begin(exchange, Engine.OPENFGA,
Operation.BATCH, "model");
+ var second = AuthorizationObservation.begin(exchange, Engine.OPA_REST,
Operation.DECISION, null);
+ assertThat(first).isSameAs(second);
+ assertThat(first.isEnabled()).isFalse();
+ first.item(Outcome.ERROR);
+ first.completeBatch();
+ }
+
+ @Test
+ void eventIsImmutableAndContainsOnlySafeDecisionMetadata() {
+ Collector collector = new Collector();
+ var observation
+ = AuthorizationObservation.begin(exchange(List.of(collector)),
Engine.OPENFGA, Operation.BATCH, "model-1");
+ observation.item(Outcome.ALLOW);
+ observation.item(Outcome.DENY);
+ observation.item(Outcome.ERROR);
+ observation.completeBatch();
+ AuthorizationDecisionEvent event = collector.events.getFirst();
+ assertThat(event.getType()).isEqualTo(CamelEvent.Type.Custom);
+ assertThat(event.getSource()).isEqualTo(Engine.OPENFGA);
+ assertThat(event.getExchangeId()).isEqualTo("exchange-1");
+ assertThat(event.getRouteId()).isEqualTo("route-1");
+ assertThat(event.getRevision()).isEqualTo("model-1");
+ assertThat(event.getOutcome()).isEqualTo(Outcome.ERROR);
+ assertThat(event.getCounts()).isEqualTo(new
AuthorizationDecisionEvent.Counts(1, 1, 1, 0, 0));
+ assertThat(event.getDurationNanos()).isNotNegative();
+ assertThat(event.getPoolWaitNanos()).isEqualTo(-1);
+ assertThat(event.asJSon().keySet()).doesNotContain("exchange",
"principal", "resource", "input", "exception", "token");
+ assertThatThrownBy(() ->
event.setTimestamp(1)).isInstanceOf(UnsupportedOperationException.class);
+ assertThatThrownBy(() -> event.asJSon().put("token",
"secret")).isInstanceOf(UnsupportedOperationException.class);
+ }
+
+ @Test
+ void brokenListenersCannotChangeOutcomeOrStarveOtherListeners() {
+ Collector collector = new Collector();
+ EventNotifier brokenOptOut = new Collector() {
+ @Override
+ public boolean isDisabled() {
+ throw new IllegalStateException("secret");
+ }
+ };
+ EventNotifier brokenEnablement = new Collector() {
+ @Override
+ public boolean isEnabled(CamelEvent event) {
+ throw new IllegalStateException("secret");
+ }
+ };
+ EventNotifier brokenNotification = new Collector() {
+ @Override
+ public void notify(CamelEvent event) {
+ throw new IllegalStateException("secret");
+ }
+ };
+ var observation = AuthorizationObservation.begin(
+ exchange(List.of(brokenOptOut, brokenEnablement,
brokenNotification, collector)),
+ Engine.SPIFFE, Operation.MTLS, null);
+ observation.complete(Outcome.ALLOW,
AuthorizationDecisionEvent.Failure.NONE);
+ assertThat(collector.events).hasSize(1);
+
assertThat(collector.events.getFirst().getOutcome()).isEqualTo(Outcome.ALLOW);
+ }
+
+ @Test
+ void
customEventsHonorDisablementAndEnablementIndependentlyOfExchangeOptOut() {
+ Collector disabled = new Collector() {
+ @Override
+ public boolean isDisabled() {
+ return true;
+ }
+ };
+ Collector ignored = new Collector();
+ ignored.setIgnoreExchangeEvents(true);
+ Collector filtered = new Collector() {
+ @Override
+ public boolean isEnabled(CamelEvent event) {
+ return false;
+ }
+ };
+ var observation =
AuthorizationObservation.begin(exchange(List.of(disabled, ignored, filtered)),
Engine.SPIFFE,
+ Operation.MTLS, null);
+ observation.complete(Outcome.DENY,
AuthorizationDecisionEvent.Failure.NONE);
+ assertThat(disabled.events).isEmpty();
+ assertThat(ignored.events).hasSize(1);
+ assertThat(filtered.events).isEmpty();
+ }
+
+ // Proxies deliberately reject body/header/property access: constructing
observations must not inspect message data.
+ private static Exchange exchange(List<EventNotifier> notifiers) {
+ ManagementStrategy management = proxy(ManagementStrategy.class,
(method) -> {
+ if (method.equals("getStartedEventNotifiers")) {
+ return notifiers;
+ }
+ throw new UnsupportedOperationException(method);
+ });
+ CamelContext context = proxy(CamelContext.class, method -> {
+ if (method.equals("getManagementStrategy")) {
+ return management;
+ }
+ throw new UnsupportedOperationException(method);
+ });
+ return proxy(Exchange.class, method -> switch (method) {
+ case "getContext" -> context;
+ case "getExchangeId" -> "exchange-1";
+ case "getFromRouteId" -> "route-1";
+ default -> throw new UnsupportedOperationException(method);
+ });
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T> T proxy(Class<T> type, Function<String, Object>
invocation) {
+ return (T) Proxy.newProxyInstance(type.getClassLoader(), new
Class<?>[] { type },
+ (object, method, args) -> invocation.apply(method.getName()));
+ }
+
+ private static class Collector extends SimpleEventNotifierSupport {
+ final List<AuthorizationDecisionEvent> events = new ArrayList<>();
+
+ Collector() {
+ setIgnoreExchangeEvents(false);
+ }
+
+ @Override
+ public boolean isEnabled(CamelEvent event) {
+ return event instanceof AuthorizationDecisionEvent;
+ }
+
+ @Override
+ public void notify(CamelEvent event) {
+ events.add((AuthorizationDecisionEvent) event);
+ }
+ }
+}
diff --git a/docs/user-manual/modules/ROOT/nav.adoc
b/docs/user-manual/modules/ROOT/nav.adoc
index 2d5e25aadbc9..c0b1718863d8 100644
--- a/docs/user-manual/modules/ROOT/nav.adoc
+++ b/docs/user-manual/modules/ROOT/nav.adoc
@@ -76,6 +76,7 @@
** xref:security.adoc[Security]
** xref:security-policy.adoc[Security Policy Enforcement]
** xref:security-model.adoc[Security Model]
+** xref:authorization-observability.adoc[Authorization Observations]
** xref:governed-ai-agents.adoc[Governed AI Agents]
* xref:architecture.adoc[Architecture]
** xref:backlog-debugger.adoc[Backlog debugger]
diff --git
a/docs/user-manual/modules/ROOT/pages/authorization-observability.adoc
b/docs/user-manual/modules/ROOT/pages/authorization-observability.adoc
new file mode 100644
index 000000000000..66fdb36ba7e0
--- /dev/null
+++ b/docs/user-manual/modules/ROOT/pages/authorization-observability.adoc
@@ -0,0 +1,171 @@
+= Authorization observations
+
+Camel OPA, OpenFGA and SPIFFE emit optional `AuthorizationDecisionEvent` events
+through the existing Camel `EventNotifier` lifecycle. Register a notifier
before
+starting the context. No event or observation clock is created when there are
no
+started enabled notifiers.
+`isDisabled()` and `isEnabled(event)` are honored independently of
`ignoreExchangeEvents`, because these are custom events. Listener failures do
+not change an authorization result or prevent delivery to other listeners.
+
+[source,java]
+----
+context.getManagementStrategy().addEventNotifier(new EventNotifierSupport() {
+ @Override
+ public boolean isEnabled(CamelEvent event) {
+ return event instanceof AuthorizationDecisionEvent;
+ }
+
+ @Override
+ public void notify(CamelEvent event) {
+ AuthorizationDecisionEvent decision = (AuthorizationDecisionEvent)
event;
+ // Send the bounded decision metadata to your audit sink.
+ }
+});
+----
+
+The immutable event lives in `org.apache.camel.support.security`. It is a
+`CamelEvent` of type `Custom`, with no retained `Exchange`, credentials,
subject,
+resource identifier, full input or exception text. It records:
+
+* Engine: OPA REST, OPA WASM, OpenFGA or SPIFFE.
+* Operation: a single decision, batch, SPIFFE mutual TLS check or JWT
validation.
+* Outcome: `ALLOW`, `DENY`, `ERROR`, `UNAVAILABLE` or `FAILED_OPEN`.
+* Failure category: `NONE`, `EVALUATION`, `UNAVAILABLE` or `INTERRUPTED`.
+* Monotonic elapsed nanoseconds and outcome counts. OPA WASM also reports the
+ actual pool borrow wait, including a failed borrow; other operations use -1.
+* Exchange and originating route identifiers for event correlation.
+* The configured OpenFGA model revision, when pinned. OPA REST does not expose
a
+ verified deployed revision here, and the WASM evaluator does not infer one
from
+ a bundle filename; unknown revisions are null. An unpinned OpenFGA model is
+ likewise unknown.
+
+An explicit negative decision is `DENY`. An evaluation that never obtains a
+verdict is `ERROR` or, where the engine can identify an availability failure,
+`UNAVAILABLE`. `FAILED_OPEN` means configuration allowed processing without a
+verdict. It is distinct from `ALLOW`. For SPIFFE, unavailable Workload API gRPC
+statuses are reported as availability failures; an invalid JWT is a denial.
+The JWT security policy records its final allow or deny once, including a
validated identity rejected by its allow list.
+
+Batch counts distinguish allowed and denied decisions from failed elements.
+For mixed successful batches the aggregate outcome prioritizes failed-open,
+evaluation error, unavailability and denial, in that order. A whole OpenFGA
batch
+that throws still reports failure even if some individual checks had answered.
+Existing verdict headers, failure handling and filtering behavior are
unchanged.
+Query and tuple maintenance operations do not emit authorization decisions.
+Fetching a local SVID is not a peer authorization decision and emits no such
event.
+
+== Optional Micrometer metrics
+
+Add `camel-micrometer` and register its
+`MicrometerAuthorizationEventNotifier`. No Micrometer dependency is needed in
+OPA, OpenFGA or SPIFFE themselves:
+
+[source,java]
+----
+MicrometerAuthorizationEventNotifier notifier = new
MicrometerAuthorizationEventNotifier();
+notifier.setCamelContext(context);
+notifier.setMeterRegistry(meterRegistry);
+context.getManagementStrategy().addEventNotifier(notifier);
+----
+
+The notifier records `camel.authorization.duration`, element counts in
+`camel.authorization.decisions` and, for WASM, `camel.authorization.pool.wait`.
+Decision labels are fixed enums: engine, operation, outcome and failure as
applicable. The standard `camelContext` and `kind=authorization` tags identify
the configured context and meter category.
+Revision, correlation IDs, route IDs, principal and resource are never metric
+labels. Processing more exchanges or deploying another model revision does not
+create another metric series with the same engine and outcomes.
+
+Events provide authorization semantics alongside normal Camel telemetry. They
+do not create spans or duplicate OpenFGA SDK spans. An application can attach
+safe event attributes to its existing tracing integration through a notifier;
+do not turn correlation IDs, inputs or identities into metric labels.
+
+== Compose verified identity with policy decisions
+
+The following examples assume registered `spiffeIdentity` and
`opaAuthorization`
+policies. Require mutual TLS in `SpiffeSSLContextParameters`, and configure the
+SPIFFE policy with an appropriate peer allow-list. Configure the OPA policy's
+`includeProperties` to include `CamelSpiffePeerId`.
+
+`mapVerifiedIdentity` is an application processor that maps the verified
+`CamelSpiffePeerId` exchange property to an OpenFGA subject and sets
+`verifiedFgaUser`. It must not take the subject from an inbound identity
header.
+Keep the mapping explicit: the engines retain their own subject and policy
models.
+Every decision event shares the exchange correlation while retaining its
engine.
+
+[tabs]
+====
+Java::
++
+[source,java]
+----
+from("netty-http:https://0.0.0.0:8443?sslContextParameters=#spiffeSsl")
+ .policy(spiffeIdentity)
+ .policy(opaAuthorization)
+ .process(mapVerifiedIdentity)
+
.to("openfga:check?storeId={{fga.store}}&authorizationModelId={{fga.model}}"
+ + "&user=${exchangeProperty.verifiedFgaUser}&relation=reader"
+ + "&object=document:${header.documentId}")
+ .filter(header("CamelOpenFgaAllowed").isEqualTo(true))
+ .to("direct:serveDocument")
+ .end();
+----
+
+XML::
++
+[source,xml]
+----
+<route>
+ <from uri="netty-http:https://0.0.0.0:8443?sslContextParameters=#spiffeSsl"/>
+ <policy ref="spiffeIdentity">
+ <policy ref="opaAuthorization">
+ <process ref="mapVerifiedIdentity"/>
+ <to
uri="openfga:check?storeId={{fga.store}}&authorizationModelId={{fga.model}}&user=${exchangeProperty.verifiedFgaUser}&relation=reader&object=document:${header.documentId}"/>
+ <filter>
+ <simple>${header.CamelOpenFgaAllowed} == true</simple>
+ <to uri="direct:serveDocument"/>
+ </filter>
+ </policy>
+ </policy>
+</route>
+----
+
+YAML::
++
+[source,yaml]
+----
+- route:
+ from:
+ uri: netty-http:https://0.0.0.0:8443
+ parameters:
+ sslContextParameters: "#spiffeSsl"
+ steps:
+ - policy:
+ ref: spiffeIdentity
+ steps:
+ - policy:
+ ref: opaAuthorization
+ steps:
+ - process:
+ ref: mapVerifiedIdentity
+ - to:
+ uri: openfga:check
+ parameters:
+ storeId: "{{fga.store}}"
+ authorizationModelId: "{{fga.model}}"
+ user: "${exchangeProperty.verifiedFgaUser}"
+ relation: reader
+ object: "document:${header.documentId}"
+ - filter:
+ expression:
+ simple:
+ expression: "${header.CamelOpenFgaAllowed} == true"
+ steps:
+ - to:
+ uri: direct:serveDocument
+----
+====
+
+See xref:next@components::spiffe-component.adoc[SPIFFE] for the verified TLS
session
+requirements, xref:next@components::opa-component.adoc[OPA] for input
selection, and
+xref:next@components::openfga-component.adoc[OpenFGA] for subject and model
configuration.