Skip to content
Open
Show file tree
Hide file tree
Changes from 46 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
4b3ef30
feat(agent-gateway): authorize tools from trusted identities
BobSong-dev Oct 18, 2026
6788e7b
feat(agent-gateway): authorize tools from trusted identities
BobSong-dev Oct 19, 2026
19eea6f
feat(agent-gateway): unify request context and terminal observation
BobSong-dev Oct 19, 2026
3c09a39
merge: reconcile master retry policy with agent observation
BobSong-dev Oct 20, 2026
dd6d878
merge: reconcile agent context tests with latest master
BobSong-dev Oct 20, 2026
f4392ce
feat(agent-gateway): add runtime governance observability
BobSong-dev Oct 21, 2026
5d97d96
Merge remote-tracking branch 'origin/master' into integration/agent-g…
BobSong-dev Oct 21, 2026
e451ec6
Merge remote-tracking branch 'origin/master' into feat/agent-gateway-…
BobSong-dev Oct 23, 2026
8aba05c
feat(agent-gateway): add unified invocation auditing
BobSong-dev Oct 23, 2026
4a9544d
merge: reconcile agent observation with latest master
BobSong-dev Oct 25, 2026
2324714
ci: re-run agent gateway checks
BobSong-dev Oct 25, 2026
423278e
test(agent-gateway): harden migration null fixture
BobSong-dev Oct 26, 2026
4736952
test(agent-gateway): harden migration null fixture
BobSong-dev Oct 26, 2026
1664140
fix(agent-gateway): address observation and ordering review
BobSong-dev Oct 26, 2026
be45a5f
Merge remote-tracking branch 'fork/integration/agent-gateway-p003' in…
BobSong-dev Oct 26, 2026
020fd64
Merge remote-tracking branch 'origin/master' into integration/agent-g…
BobSong-dev Oct 26, 2026
cad1e72
merge: reconcile agent integration with latest master
BobSong-dev Oct 26, 2026
5b0a459
fix(agent-gateway): preserve metrics and tracing compatibility
BobSong-dev Oct 26, 2026
5e72769
Merge commit 'cad1e72320a4c2bf7c9e952762450feca8599a81' into feat/age…
BobSong-dev Oct 26, 2026
fa79ddd
Merge commit '5b0a4597c0a3a3fba57a622a18d1aed2fe3a702b' into feat/age…
BobSong-dev Oct 26, 2026
e69b7cc
fix(agent-gateway): align audit module version
BobSong-dev Oct 26, 2026
c8b7a32
chore: retrigger checks
BobSong-dev Oct 26, 2026
f9eb7ba
fix(agent-gateway): preserve released upgrade migrations
BobSong-dev Oct 27, 2026
a34127b
test(admin): cover plugin tables in migration contract fixtures
BobSong-dev Oct 27, 2026
3f417a3
merge: reconcile governance observability with latest master
BobSong-dev Oct 27, 2026
0fac12d
Merge commit 'a34127bc8a492e6de33efdb48285b3abd6c476e6' into HEAD
BobSong-dev Oct 27, 2026
6e1486e
Merge commit '3f417a358a0f5c4f37016235f7a564fdcc3c8456' into HEAD
BobSong-dev Oct 27, 2026
1b68fcb
Merge remote-tracking branch 'origin/master' into HEAD
BobSong-dev Oct 27, 2026
d093d0e
fix(ai-proxy): preserve audit mapping after master merge
BobSong-dev Oct 27, 2026
cb82930
Merge commit 'a34127bc8a492e6de33efdb48285b3abd6c476e6' into integrat…
BobSong-dev Oct 27, 2026
89a2fe2
Merge remote-tracking branch 'origin/master' into integration/agent-g…
BobSong-dev Oct 27, 2026
6b1207c
Merge remote-tracking branch 'origin/master' into integration/agent-g…
BobSong-dev Oct 28, 2026
1a05008
Merge remote-tracking branch 'fork/integration/agent-gateway-p003' in…
BobSong-dev Oct 28, 2026
e9dc976
Merge remote-tracking branch 'fork/integration/agent-gateway-p105' in…
BobSong-dev Oct 28, 2026
4c6d01b
fix(agent-gateway): preserve rejection audits across master merge
BobSong-dev Oct 30, 2026
6cda864
Merge latest master into audit publication base
BobSong-dev Nov 5, 2026
83645b7
feat(common): add shared governance decisions
BobSong-dev Nov 5, 2026
63b02d3
fix(metrics): preserve single registration when reconciling audit bas…
BobSong-dev Nov 5, 2026
c2eeb87
Merge branch 'integration/audit-publication-20261105' into feat/agent…
BobSong-dev Nov 5, 2026
b9a5bdc
fix(ai-proxy): remove stale transport import from integration baseline
BobSong-dev Nov 5, 2026
8d5f608
Merge branch 'integration/audit-publication-20261105' into feat/agent…
BobSong-dev Nov 5, 2026
db7196c
ci: rerun governance checks after intermittent admin failure
BobSong-dev Nov 5, 2026
cdb0298
test: synchronize admin state and MCP cancellation assertions
BobSong-dev Nov 5, 2026
7b9c3c3
fix(ci): reconcile governance baseline with master test fixes
BobSong-dev Nov 9, 2026
41c792d
merge: reconcile audit integration with current master
BobSong-dev Nov 12, 2026
a2e3a1d
merge: synchronize governance with current audit baseline
BobSong-dev Nov 12, 2026
7da40cf
merge: align governance with accepted runtime and test fixes
BobSong-dev Nov 18, 2026
6786e2d
fix(audit): separate governance decisions from invocation terminals
BobSong-dev Nov 20, 2026
aa7e271
merge: reconcile governance audit fix with accepted master baseline
BobSong-dev Nov 20, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/agent-governance-decision.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Agent governance decision contract

Agent Gateway governance consumers use one versioned decision contract before introducing MCP quotas or LLM budgets. A decision identifies its consumer, policy/configuration versions, shadow or enforce mode, result, bounded reason, correlation id, ledger generation and effective time. Tenant, subject and trace id are not labels; they remain in the existing trusted request context and metadata-only audit event.

## Results and modes

- `ALLOW` means policy permits the call.
- `WOULD_DENY` is valid only in shadow mode. It is reported and counted in an isolated shadow ledger but must not reject traffic or debit production quota/budget state.
- `DENY` is valid only in enforce mode and is the only result that may reject traffic.

Authentication, authorization and fundamental resource-limit failures are mandatory denies in both modes. They are represented as enforce decisions even when the policy itself is shadow, so shadow mode cannot bypass security or base resource protection.

## Isolated shadow state and transitions

Each shadow ledger generation is immutable. Configuration replacement creates a new generation and closes the old ledger to new evaluations; existing in-flight reservations continue settling or cancelling against the generation that admitted them, and no state is moved or double-settled between ledgers. The bounded reference ledger reserves capacity for shadow `ALLOW` evaluations and records subsequent `WOULD_DENY` evaluations with bounded reason counters, accepted/observed/overflow/settled/cancelled/expired values, and explicit close. Overflow drops only shadow evaluation state, never traffic. Actual usage continues through the existing metering and terminal-event owners.

Shadow reservations have a bounded TTL. Expiry only releases that reservation's capacity and records an expired count; it does not reject traffic or debit a production policy. Cancellation and settlement are idempotent and mutually exclusive for the same reservation.

Shadow/enforce comparison is explicit: `SAME_EFFECT`, `SHADOW_STRICTER`, or `ENFORCE_STRICTER`. Comparisons require the same consumer, versions, ledger generation and correlation id, and are observations for rollout; they do not retroactively change an execution decision.

`AgentGovernanceContractLabels` is the metric boundary and exposes only consumer, mode, result and reason. `AgentGovernanceAuditAdapter` maps shadow would-deny to an audit `ALLOWED` terminal with a `SHADOW_*` reason; enforce deny maps to `REJECTED` with the bounded reason.

## Non-goals

This contract does not implement Redis quota admission, token reservation, cost settlement, provider usage parsing, or execution-point wiring. Those belong to #7957 and #7958 and must consume this vocabulary rather than invent local switches.
42 changes: 42 additions & 0 deletions docs/agent-invocation-audit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Agent invocation audit

Agent Gateway and AI Proxy can emit metadata-only invocation audit events when `shenyu.plugins.agent.audit.enabled=true`.

## Record contract

Every event has schema version `1`, a logical request id, selector/rule ids, configuration version, policy version, target, decision, bounded outcome/reason, optional HTTP status, and timestamp. Logical records are terminal results; attempt records are separately numbered and correlated by the same request id.

Trusted tenant and subject are included when a server-side identity adapter resolves them. No prompt, arguments, response body, credential, raw API key, header map, or trace id is stored. W3C trace ids are correlation-only when used by tracing, never identity.

Target is optional metadata. The bridge omits caller-supplied targets that are blank, longer than 256 characters, padded with whitespace, or contain control characters. It preserves the logical rejection record and its trusted identity, outcome and status; it does not truncate an invalid target into another tool name. Valid targets remain unchanged, and direct audit-event builders retain strict metadata validation.

Policy version identifies the admission contract (`tool-grant-intersection-v1`, `agent-ai-admission-v1`, `key-auth-admission-v1` or `agent-rule-admission-v1`), not a revision of an external identity provider's policy. Configuration version is the captured node-local Agent Gateway rule generation. Standalone AI Proxy and rejected invalid configuration have no such generation and explicitly report `unknown`; no fingerprint of credential-bearing configuration is emitted.

## Outcomes

Logical and attempt records use `SUCCESS`, `TOOL_ERROR`, `REJECTED`, `RATE_LIMITED`, `TIMEOUT`, `CANCELLED`, and `SERVER_ERROR`. MCP attempt presence is marked after pre-execution validation; its terminal snapshot and duration come from the logical owner, including validation, result filtering and response writing. It is an actual-execution marker, not an upstream wire-latency metric. Rejected authorization or missing client capabilities never create an attempt. Reasons are bounded strings such as `TOOL_REPORTED_ERROR`, `DEADLINE_EXCEEDED`, `DOWNSTREAM_CANCELLED`, `HTTP_500`, `CREDENTIAL_REJECTED` and `INVALID_CONFIGURATION`.

The bridge consumes existing `AiRequestObservation` and `AgentMcpTerminalObservation` events. It does not create another request registry or complete an inherited logical call again. AI retry and fallback attempts use the existing one-based attempt sequence. Application terminal observers continue receiving events even when audit delivery fails. Key Auth rejection happens before Agent Gateway and produces a separate admission terminal record with a fresh server request id and no invented tenant/subject/model; it does not create an AI call or upstream attempt. Existing response status/body remain unchanged, including Key Auth's existing response-status convention. HTTP status is an assigned status, not proof of response delivery.

## Delivery

The shared `shenyu-spring-boot-starter-agent-audit` is included by both Agent Gateway and AI Proxy starters; AI-only deployment does not require Agent Gateway. The default observer submits metadata to ShenYu's existing `AbstractLogCollector`, which delivers asynchronously to SLF4J logger `org.apache.shenyu.agent.invocation.audit`. Callback exceptions cannot alter a gateway response. Applications may replace the observer bean with an external nonblocking sink, or provide an `AgentInvocationAuditConsumer` for worker-side batch delivery.

The adapter reuses the existing collector's single-client bounded admission, worker, batches of up to 100, polling interval of approximately 100 ms and `LoggingQueueMetrics`. Queue saturation rejects new records; accepted/dropped/backlog/capacity have the existing collector-class labels. Sink exceptions increment `AgentInvocationAuditCollector.getFailedRecords()` and emit a fixed warning without exception payloads. The collector interrupts its worker and attempts a final queue flush on close; it does not guarantee delivery of an interrupted in-flight batch, persist records, retry failed batches or count post-close submissions as queue overflow. Final flush runs on the shutdown caller and depends on the sink's timeout behavior. Custom sinks must bound their blocking time. This is best-effort, not lossless delivery.

Configuration:

| Property | Default | Meaning |
|---|---:|---|
|`shenyu.plugins.agent.audit.enabled`|`false`|Enable the managed observer.|
|`shenyu.plugins.agent.audit.queue-capacity`|`8192`|Maximum waiting records.|

Retention and remote delivery are owned by the configured logging or storage backend, not by the gateway plugins.

## Known identity boundary

AI traffic inside Agent Gateway uses the inherited immutable trusted tenant/subject context, including a rejection before AI Proxy. Standalone AI Proxy requests do not infer tenant/subject from an API key or trace id and remain unscoped. MCP uses its resolved security identity. AI Proxy includes the synchronized mapping's internal database ID when available; older Admin payloads without an ID remain supported and leave that field absent. Key Auth's current authentication contract has no separate credential-record ID, so it is left absent rather than substituting a raw key. Neither the presented proxy key nor the upstream credential is copied into audit events.

## Integration baseline

The request/terminal contracts from PR #7860 are now on master. This candidate still integrates runtime governance from PR #7921; the audit delta must be reviewed against the resulting master after that prerequisite merges. The earlier independent prototype's identity interface, completion logic and custom queue are not used.
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ private ProxyApiKeyData convert(final ProxyApiKeyDO entity, final String resolve
entity.getNamespaceId(), normalizedNs, entity.getProxyApiKey());
}
return ProxyApiKeyData.builder()
.id(entity.getId())
.proxyApiKey(entity.getProxyApiKey())
.realApiKey(resolvedRealKey)
.description(entity.getDescription())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verifyNoInteractions;
Expand Down Expand Up @@ -193,7 +194,7 @@ public void testRemoveByKey() {

@Test
public void testSubmit() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, ShenyuThreadFactory.create("scheduled-upstream-task", false));
ScheduledThreadPoolExecutor executor = mock(ScheduledThreadPoolExecutor.class);
ReflectionTestUtils.setField(upstreamCheckService, "executor", executor);
final DivideUpstream divideUpstream = DivideUpstream.builder()
.upstreamUrl("divide-upstream-60")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ void testEnabledPublishesEvent() {
ArgumentCaptor<DataChangedEvent> captor = ArgumentCaptor.forClass(DataChangedEvent.class);
verify(publisher).publishEvent(captor.capture());
assertEquals(ConfigGroupEnum.AI_PROXY_API_KEY, captor.getValue().getGroupKey());
List<?> synchronizedKeys = (List<?>) captor.getValue().getSource();
assertEquals("1", ((org.apache.shenyu.common.dto.ProxyApiKeyData) synchronizedKeys.get(0)).getId());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* 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.shenyu.common.audit;

import org.apache.shenyu.common.dto.AgentRequestContext;
import org.apache.shenyu.common.governance.AgentGovernanceDecision;

import java.util.Objects;

/**
* Adapts a governance decision into the existing metadata-only audit contract.
* Shadow would-deny remains an allowed invocation in the audit terminal outcome.
*/
public final class AgentGovernanceAuditAdapter {

private AgentGovernanceAuditAdapter() {
}

public static AgentInvocationAuditEvent toEvent(final AgentRequestContext context, final AgentGovernanceDecision decision) {
Objects.requireNonNull(context, "context");
Objects.requireNonNull(decision, "decision");
boolean denied = decision.deniesTraffic();
return AgentInvocationAuditEvent.logical()
.requestId(context.getRequestId())
.tenant(context.getTenant()).subject(context.getSubject()).apiKeyId(context.getApiKeyId())
.selectorId(context.getSelectorId()).ruleId(context.getRuleId())
.configurationVersion(Objects.isNull(context.getConfigurationVersion()) ? "unknown" : context.getConfigurationVersion().toString())
.policyVersion(decision.getPolicyVersion())
.decision(denied ? AgentInvocationAuditEvent.Decision.REJECTED : AgentInvocationAuditEvent.Decision.ALLOWED)
.target(context.getTarget())
.outcome(denied ? "REJECTED" : "SUCCESS")
.reason(denied ? decision.getReason().name() : "SHADOW_" + decision.getReason().name())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* 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.shenyu.common.audit;

import org.apache.shenyu.common.dto.AgentRequestContext;
import org.apache.shenyu.common.metrics.AgentMcpTerminalEvent;
import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver;
import org.apache.shenyu.common.metrics.AiAttemptEvent;
import org.apache.shenyu.common.metrics.AiCallObserver;
import org.apache.shenyu.common.metrics.AiTerminalEvent;

import java.util.Objects;

/** Maps existing terminal owners without another request registry or completion state machine. */
public final class AgentInvocationAuditBridge {

private AgentInvocationAuditBridge() {
}

/**
* Preserve the application observer and add independent audit delivery.
* @param existing existing observer
* @param audit optional audit sink
* @return combined observer, or the existing observer when disabled
*/
public static AiCallObserver ai(final AiCallObserver existing, final AgentInvocationAuditObserver audit) {
if (Objects.isNull(audit)) {
return existing;
}
return new AiCallObserver() {
@Override
public void record(final AiTerminalEvent event) {
safely(() -> emit(audit, event.context(), event.outcome().name(), event.httpStatus(), event.elapsedMillis(), null));
if (Objects.nonNull(existing)) {
safely(() -> existing.record(event));
}
}

@Override
public void recordAttempt(final AiAttemptEvent event) {
safely(() -> emit(audit, event.context(), event.outcome().name(), event.httpStatus(), event.elapsedMillis(), event.attemptNumber()));
if (Objects.nonNull(existing)) {
safely(() -> existing.recordAttempt(event));
}
}
};
}

/**
* Adapt MCP logical and actual execution snapshots without copying payloads.
* @param existing existing observer
* @param audit optional audit sink
* @return combined observer
*/
public static AgentMcpTerminalObserver mcp(final AgentMcpTerminalObserver existing, final AgentInvocationAuditObserver audit) {
if (Objects.isNull(audit)) {
return existing;
}
return new AgentMcpTerminalObserver() {
@Override
public void record(final AgentMcpTerminalEvent event) {
safely(() -> emit(audit, event.getContext(), event.getOutcome().name(), event.getHttpStatus(), event.getElapsedMillis(), null));
if (Objects.nonNull(existing)) {
safely(() -> existing.record(event));
}
}

@Override
public void recordAttempt(final AgentMcpTerminalEvent event) {
safely(() -> emit(audit, event.getContext(), event.getOutcome().name(), event.getHttpStatus(), event.getElapsedMillis(), 1));
if (Objects.nonNull(existing)) {
safely(() -> existing.recordAttempt(event));
}
}
};
}

private static void emit(final AgentInvocationAuditObserver sink, final AgentRequestContext context, final String outcome,
final Integer status, final long elapsed, final Integer attempt) {
AgentInvocationAuditEvent.Builder builder = Objects.isNull(attempt) ? AgentInvocationAuditEvent.logical() : AgentInvocationAuditEvent.attempt(attempt);
sink.record(builder.requestId(context.getRequestId()).tenant(context.getTenant()).subject(context.getSubject()).apiKeyId(context.getApiKeyId())
.selectorId(context.getSelectorId()).ruleId(context.getRuleId()).target(auditTarget(context.getTarget()))
.configurationVersion(Objects.isNull(context.getConfigurationVersion()) ? "unknown" : context.getConfigurationVersion().toString())
.policyVersion("mcp".equals(context.getTrafficType()) ? "tool-grant-intersection-v1" : "agent-ai-admission-v1")
.decision("REJECTED".equals(outcome) || "RATE_LIMITED".equals(outcome)
? AgentInvocationAuditEvent.Decision.REJECTED : AgentInvocationAuditEvent.Decision.ALLOWED)
.outcome("ERROR".equals(outcome) ? "SERVER_ERROR" : outcome)
.reason("CANCELLED".equals(outcome) ? "DOWNSTREAM_CANCELLED" : "TIMEOUT".equals(outcome) ? "DEADLINE_EXCEEDED"
: "TOOL_ERROR".equals(outcome) ? "TOOL_REPORTED_ERROR" : Objects.isNull(status) ? "NO_RESPONSE" : "HTTP_" + status)
.httpStatus(status).elapsedMillis(elapsed).build());
}

private static String auditTarget(final String value) {
// Caller-supplied optional metadata must not suppress a rejection audit.
try {
return AgentInvocationAuditEvent.nullableText(value, "target");
} catch (IllegalArgumentException ignored) {
return null;
}
}

private static void safely(final Runnable action) {
try {
action.run();
} catch (RuntimeException ignored) {
// Sink failures must not alter traffic or suppress another observer.
}
}
}
Loading
Loading