From 4b3ef30eebf3ea1ca86dd38669ea314b573a4c5a Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Sun, 18 Oct 2026 21:51:42 +0800 Subject: [PATCH 01/36] feat(agent-gateway): authorize tools from trusted identities --- docs/agent-gateway-key-auth.md | 102 ++++++ docs/agent-gateway-principal-authorization.md | 129 +++++++ .../protocol/AgentMcpExecutionContext.java | 14 + .../gateway/protocol/AgentMcpHttpHandler.java | 5 +- .../gateway/security/AgentMcpIdentity.java | 42 ++- .../key/auth/KeyAuthAuthentication.java | 114 ++++++ .../shenyu/plugin/key/auth/KeyAuthPlugin.java | 7 +- .../auth/KeyAuthAuthenticationHttpTest.java | 187 ++++++++++ .../key/auth/KeyAuthAuthenticationTest.java | 331 ++++++++++++++++++ .../pom.xml | 26 ++ .../AgentGatewayPluginConfiguration.java | 113 +++++- .../gateway/KeyAuthMcpSecurityProperties.java | 128 +++++++ .../gateway/KeyAuthMcpSecurityResolver.java | 93 +++++ .../PrincipalMcpSecurityProperties.java | 136 +++++++ .../gateway/PrincipalMcpSecurityResolver.java | 161 +++++++++ .../agent/gateway/KeyAuthMcpHttpTest.java | 208 +++++++++++ .../KeyAuthMcpSecurityConfigurationTest.java | 230 ++++++++++++ .../agent/gateway/KeyAuthMcpTestFixture.java | 327 +++++++++++++++++ .../agent/gateway/OAuthLoginMcpHttpTest.java | 188 ++++++++++ .../agent/gateway/PrincipalMcpHttpTest.java | 281 +++++++++++++++ .../PrincipalMcpSecurityResolverTest.java | 235 +++++++++++++ 21 files changed, 3052 insertions(+), 5 deletions(-) create mode 100644 docs/agent-gateway-key-auth.md create mode 100644 docs/agent-gateway-principal-authorization.md create mode 100644 shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthentication.java create mode 100644 shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthenticationHttpTest.java create mode 100644 shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthenticationTest.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityProperties.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityResolver.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityProperties.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityResolver.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpHttpTest.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityConfigurationTest.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpTestFixture.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OAuthLoginMcpHttpTest.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpHttpTest.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityResolverTest.java diff --git a/docs/agent-gateway-key-auth.md b/docs/agent-gateway-key-auth.md new file mode 100644 index 000000000000..543f7ea6c356 --- /dev/null +++ b/docs/agent-gateway-key-auth.md @@ -0,0 +1,102 @@ + + +# API key identities for Agent Gateway tools + +Agent Gateway can reuse the existing `key-auth` plugin's successful authentication. +It does not verify a second credential or derive an identity from client headers. +Install and enable the key-auth starter alongside the Agent Gateway starter. +The key-auth plugin must match and authenticate the request before Agent Gateway. +Its existing header/query credential contract and error response remain unchanged. +Prefer HTTPS and header credentials; query credentials can appear in access logs. + +## Explicit deployment policy + +This adapter is disabled by default. Configure it in the gateway application, +not in a client request or MCP `_meta`: + +```yaml +shenyu: + plugins: + agent: + gateway: + enabled: true + security: + key-auth: + enabled: true + bindings: + - namespace-id: production-namespace-id + selector-id: service-a-selector-id + rule-id: service-a-key-rule-id + tenant: tenant-a + subject: service-a + tool-grants: [inventory.lookup, orders.read, orders.delete] + tool-denials: [orders.delete] +``` + +Replace all three configuration IDs with the IDs of the authenticated key-auth +rule. They are matched exactly as a tuple. The namespace is a configuration +identifier, **not** an inferred tenant. Neither the API key nor its hash belongs +in this policy. A rule denotes one service identity; users sharing its key are +not distinguished. Use separate rules and credentials for separate identities. + +All five identity/reference fields are required. Duplicate rule bindings, empty +binding lists, unknown properties and wildcard permissions fail startup. Tool +names are exact, case-sensitive names, including prefixes for remote tools; the +adapter accepts 1–128 ASCII letters, digits, underscores, dots and hyphens. +An omitted grant list is empty and grants no tools. + +Effective permission is `(tool-grants - tool-denials) ∩ rule.allowedTools`. +The Agent Gateway rule must separately enable the intended tools. Both +`tools/list` and `tools/call` use this same permission snapshot, for JSON and SSE. +Unauthorized calls are rejected before tool execution; listing does not grant +permission. Existing tool registration, target restrictions and result filtering +remain in effect. The adapter adds no prompts/resources authorization. + +## Isolation, conflicts and changes + +- Authentication is a credential-free, immutable reference in the request-bound + Reactor Context. A different exchange cannot borrow it; disabled or unmatched + key-auth execution cannot inherit an earlier authentication result. +- Missing authentication, an unbound reference or an existing principal produces + no trusted identity and the MCP handler responds with HTTP 401. An existing + principal is rejected conservatively, even if it names the same subject. The + adapter does not silently combine authentication authorities. +- Configure only one `AgentMcpSecurityResolver`. Multiple resolver beans fail + startup, including when one is `@Primary`. Custom deployments needing source + arbitration must provide their own single resolver and disable this adapter. +- Bindings are copied at startup; restart the application to change them. There + is no implicit tenant, anonymous fallback, live policy mutation or new admin + CRUD API. Existing adapters using subject-only identities remain compatible. +- Key-auth credential rotation continues to use its existing configuration sync. + Changing a key on the same rule retains the bound service identity. Changing + the namespace, selector or rule reference requires a corresponding policy + binding; never reuse an authorized rule for a different identity accidentally. +- New requests use current matched rule configuration. An admitted in-flight + call retains its immutable identity and permissions; revocation does not undo + already-executed tool effects. Cancellation remains linked to the execution. +- No identity or raw key is automatically added to outbound MCP server requests. + Existing fixed server credentials remain independent of the inbound identity. + +## Regression scope + +Key-auth tests exercise authentication, scheduler transitions and cross-request +isolation. Starter tests cover configuration, public key-auth → Agent Gateway +plugin execution, real loopback JSON/SSE HTTP, tenant isolation, deny precedence, +key rotation, missing bindings and authorization snapshots. The test cache and +tool providers are controlled fixtures, not a deployed Admin/WebSocket or real +model integration environment. diff --git a/docs/agent-gateway-principal-authorization.md b/docs/agent-gateway-principal-authorization.md new file mode 100644 index 000000000000..54e55b6f7b30 --- /dev/null +++ b/docs/agent-gateway-principal-authorization.md @@ -0,0 +1,129 @@ + + +# Trusted identity and tools authorization + +Agent Gateway adapts existing successful authentication; it is not an OAuth +authorization server and does not authenticate a raw token a second time. +Choose **one** authority for this gateway: key-auth rule bindings (see +[API key configuration](agent-gateway-key-auth.md)), an application-authenticated +principal described here, or a custom `AgentMcpSecurityResolver`. +All adapters default to disabled. No identity means no MCP access. + +## Application prerequisites + +| Source | Accepted authenticated principal | Application responsibility | +| --- | --- | --- | +| `jwt` | `JwtAuthenticationToken` | Resource Server filter chain, signature/algorithm, time, issuer/audience, key rotation | +| `opaque-token` | `BearerTokenAuthentication` | Resource Server filter chain, trusted introspection endpoint, active/expiry/revocation policy, TLS and credentials | +| `oauth2-login` | `OAuth2AuthenticationToken` | Trusted client registration, authorization code/state, token exchange, trusted UserInfo or OIDC validation, session and CSRF | + +Add the selected Spring Security dependencies to the application. They are +optional in this starter: JWT needs resource-server and jose; opaque tokens need +resource-server and the chosen introspector's dependencies; login needs oauth2-client. +The application owns `SecurityWebFilterChain`, authentication managers, decoders, +introspectors and sessions. This adapter creates none of them. The old ShenYu +OAuth2 forwarding plugin is not a Resource Server authentication result, and +claims copied into HTTP headers by another plugin are not a trusted principal. + +## JWT or opaque-token configuration + +```yaml +shenyu: + plugins: + agent: + gateway: + enabled: true + security: + principal: + enabled: true + source: jwt # or opaque-token + issuer: https://identity.example.com + audience: shenyu-mcp + # Optional: used ONLY for an authenticated identity without tenant_id. + # default-tenant: explicitly-assigned-service-tenant + scope-mappings: + - scope: inventory:read + tool-grants: [inventory.lookup, warehouse.stock] + tool-denials: [warehouse.delete] +``` + +Issuer and audience are required and compared exactly. Trusted token attributes +must include string `iss` and a collection of strings in `aud` (the shape exposed +by the tested Spring Security converters). `registration-id` is rejected for +these sources. The application must validate tokens before this adapter runs. + +For an application-owned OAuth login, select `source: oauth2-login` and set +`registration-id: trusted-registration` instead of issuer/audience. The selected +registration is the authority boundary; issuer/audience options are rejected in +login mode rather than silently ignored. OIDC authentication remains owned by +the application's OIDC client. Keep CSRF enabled for cookie-authenticated MCP +POST requests and send the application's CSRF token; this plugin does not +exempt the endpoint. Agent clients using bearer credentials should use a Resource +Server source instead of assuming support for browser login. + +## Attribute and permission contract + +- `sub` must match the authenticated principal name exactly. No principal aliases + or header fallback are chosen silently. `tenant_id` must be nonblank bounded + text. Missing tenant may use the explicitly configured default; malformed + tenant never falls back, and anonymous traffic never gets a default identity. +- `tool_grants` and `tool_denies` are optional collections of exact tool names. + `scope` (space-separated string or string collection) or `scp` is mapped only + through the deployment's explicit scope mappings. If both exist, their sets + must agree; otherwise the identity is rejected. Unmapped scopes grant nothing. + `ROLE_*` and `SCOPE_*` authorities are not independently merged as a second + permission source. Login permissions come from trusted principal attributes, + not an unrelated access-token cache. +- Effective tools = `(direct grants + mapped grants - direct denies - mapped + denies) ∩ Agent Gateway rule.allowedTools`. Denial wins across all mappings. + `tools/list` and `tools/call` use the existing same request snapshot. A denied + tool is hidden from the list and rejected before execution. Remote names keep + their exact `server.tool` prefix. No wildcard or implicit scope-to-tool match. +- Identity strings are at most 256 characters without surrounding whitespace or + control characters; tool names use `[A-Za-z0-9_.-]{1,128}`. Each permission/scope + collection and mapping list is capped at 1024. A scope string is capped at + 8192 characters and uses space separators, not tabs or duplicate spaces. +- The configured source accepts only its matching authenticated token type. + Missing/malformed identity, wrong issuer/audience/registration, or a verified + key-auth result together with a principal is rejected; no source overrides + another. Multiple resolver beans fail startup even with `@Primary`. Both + built-in adapters enabled together also fail startup. Unknown settings, + duplicate mappings and missing selected dependencies fail startup. +- Policies and identities are copied, not read from mutable configuration during + execution. Policy changes require restart. Rule/credential sync is unchanged; + newly admitted requests use current rules while already admitted calls retain + their captured policy. Cancellation does not grant permissions or undo effects. +- Keys, tokens, raw claims and request bodies are not logged by the adapter. + Inbound identity is not copied into outbound MCP credentials. + +## Verification and boundaries + +Tests cover real signed JWT and HTTP introspection through Spring Security and +the public key-auth/Agent Gateway plugin chain, plus real authorization-code +exchange and UserInfo using a loopback identity provider. JSON/SSE tools listing, +execution, deny/intersection, forged attributes, concurrent tenants, conflicting +authentication and rule revocation are covered. Login tests preserve CSRF/state +validation. API key cancellation and in-flight snapshots reuse their existing +regressions. Fixtures own their local configuration caches and identity providers: +this is not proof of a production IdP deployment or an Admin/WebSocket deployment. + +Prompts/resources permissions follow those capabilities separately. AI/MCP +terminal events, quotas, tracing propagation and audit remain separate work. +The existing JWT-only PR and this local complete candidate overlap; reconcile +their public interfaces against merged master before publishing, without changing +other PRs or silently depending on an unmerged branch. diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java index 7a4de4de4f58..0daef70f4b9f 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java @@ -21,6 +21,7 @@ import java.util.HashSet; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.time.Instant; @@ -34,6 +35,8 @@ public final class AgentMcpExecutionContext { private final String subject; + private final String tenant; + private final String ruleId; private final long configurationVersion; @@ -59,6 +62,13 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion, final Set ruleTools, final Set securityGrants, final Instant deadline, final AgentGatewayResultFilterConfig resultFilters) { + this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters, null); + } + + public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion, + final Set ruleTools, final Set securityGrants, final Instant deadline, + final AgentGatewayResultFilterConfig resultFilters, final String tenant) { + this.tenant = Objects.isNull(tenant) ? null : requireText(tenant, "tenant"); this.deadline = Objects.requireNonNull(deadline, "deadline"); this.resultFilters = Objects.requireNonNull(resultFilters, "resultFilters"); this.requestId = requireText(requestId, "requestId"); @@ -86,6 +96,10 @@ public String getSubject() { return subject; } + public Optional getTenant() { + return Optional.ofNullable(tenant); + } + public String getRuleId() { return ruleId; } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java index 2ba90c9bdda7..1ad669eef207 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java @@ -99,8 +99,9 @@ public Mono handle(final ServerWebExchange exchange, final AgentGatewayMcp .flatMap(request -> { rpcId.set(request.getId()); observation.parsed(request); - return dispatcher.dispatch(request, () -> new AgentMcpExecutionContext(traffic.getRequestId(), identity.getSubject(), - traffic.getRuleId(), configurationVersion, config.getAllowedTools(), identity.getToolGrants(), deadline, config.getResultFilters())) + return dispatcher.dispatch(request, () -> new AgentMcpExecutionContext(traffic.getRequestId(), + identity.getSubject(), traffic.getRuleId(), configurationVersion, config.getAllowedTools(), + identity.getToolGrants(), deadline, config.getResultFilters(), identity.getTenant().orElse(null))) .contextWrite(observation::traceContext); })) .flatMap(response -> { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/security/AgentMcpIdentity.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/security/AgentMcpIdentity.java index 1f7fc735c48d..4597497d211f 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/security/AgentMcpIdentity.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/security/AgentMcpIdentity.java @@ -19,6 +19,8 @@ import java.util.Objects; import java.util.Set; +import java.util.HashSet; +import java.util.Optional; /** * Verified identity and tool grants from a server-side security adapter, never from wire metadata. @@ -29,12 +31,38 @@ public final class AgentMcpIdentity { private final Set toolGrants; + private final Set toolDenials; + + private final String tenant; + public AgentMcpIdentity(final String subject, final Set toolGrants) { + this(subject, toolGrants, Set.of(), null); + } + + /** + * Snapshot a tenant-bound identity supplied by a verified server adapter. + * @param tenant explicitly resolved tenant, never an anonymous default + * @param subject verified subject within that tenant + * @param toolGrants exact tool names granted by the authority + * @param toolDenials exact names denied, taking precedence over grants + */ + public AgentMcpIdentity(final String tenant, final String subject, final Set toolGrants, final Set toolDenials) { + this(subject, toolGrants, toolDenials, Objects.requireNonNull(tenant, "tenant")); + } + + private AgentMcpIdentity(final String subject, final Set toolGrants, final Set toolDenials, final String tenant) { if (Objects.requireNonNull(subject, "subject").isBlank()) { throw new IllegalArgumentException("subject must not be blank"); } this.subject = subject; - this.toolGrants = Set.copyOf(toolGrants); + if (Objects.nonNull(tenant) && tenant.isBlank()) { + throw new IllegalArgumentException("tenant must not be blank"); + } + this.tenant = tenant; + this.toolDenials = Set.copyOf(toolDenials); + Set effective = new HashSet<>(Set.copyOf(toolGrants)); + effective.removeAll(this.toolDenials); + this.toolGrants = Set.copyOf(effective); } public String getSubject() { @@ -44,4 +72,16 @@ public String getSubject() { public Set getToolGrants() { return toolGrants; } + + public Set getToolDenials() { + return toolDenials; + } + + /** + * Return an explicitly assigned tenant; legacy adapters remain unassigned. + * @return tenant, never a fabricated default + */ + public Optional getTenant() { + return Optional.ofNullable(tenant); + } } diff --git a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthentication.java b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthentication.java new file mode 100644 index 000000000000..2bc5fb2cf774 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthentication.java @@ -0,0 +1,114 @@ +/* + * 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.plugin.key.auth; + +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.plugin.api.ShenyuPluginChain; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; +import reactor.util.context.Context; + +import java.util.Map; +import java.util.Objects; + +/** + * Immutable, credential-free reference to a rule that authenticated this request. + * Configuration namespace is not a tenant, and a rule reference is not a user identity or grant. + * Downstream adapters must use an explicit trusted binding before deriving authorization. + */ +public final class KeyAuthAuthentication { + + private static final Object CONTEXT_KEY = new Object(); + + private final String namespaceId; + + private final String selectorId; + + private final String ruleId; + + private KeyAuthAuthentication(final RuleData rule) { + this.namespaceId = rule.getNamespaceId(); + this.selectorId = rule.getSelectorId(); + this.ruleId = rule.getId(); + } + + /** + * Read authentication from this request's downstream subscription. + * Exchange decorators sharing the original attributes retain the binding; another request does not. + * No principal, header, query parameter or exchange attribute is accepted as authentication. + * + * @param exchange current request + * @return verified rule reference, or empty when key-auth did not authenticate this request + */ + public static Mono from(final ServerWebExchange exchange) { + Objects.requireNonNull(exchange, "exchange"); + return Mono.deferContextual(context -> { + Binding binding = context.getOrDefault(CONTEXT_KEY, null); + return Objects.nonNull(binding) && binding.attributes == exchange.getAttributes() + ? Mono.just(binding.authentication) : Mono.empty(); + }); + } + + static Mono execute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final RuleData rule) { + Binding binding = new Binding(exchange.getAttributes(), new KeyAuthAuthentication(rule)); + return Mono.defer(() -> chain.execute(exchange)).contextWrite(context -> context.put(CONTEXT_KEY, binding)); + } + + static Context clear(final Context context) { + return context.delete(CONTEXT_KEY); + } + + /** + * Return the configuration namespace, which may be absent in legacy configuration. + * + * @return configuration namespace, not an inferred tenant + */ + public String getNamespaceId() { + return namespaceId; + } + + /** + * Return the authenticated selector reference. + * + * @return selector id + */ + public String getSelectorId() { + return selectorId; + } + + /** + * Return the authenticated rule reference, never the credential. + * + * @return rule id + */ + public String getRuleId() { + return ruleId; + } + + private static final class Binding { + + private final Map attributes; + + private final KeyAuthAuthentication authentication; + + private Binding(final Map attributes, final KeyAuthAuthentication authentication) { + this.attributes = attributes; + this.authentication = authentication; + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java index 388dbb8e237b..6b89c4d4f7df 100644 --- a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java +++ b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java @@ -38,6 +38,11 @@ public class KeyAuthPlugin extends AbstractShenyuPlugin { + @Override + public Mono execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) { + return Mono.defer(() -> super.execute(exchange, chain)).contextWrite(KeyAuthAuthentication::clear); + } + @Override public int getOrder() { return PluginEnum.KEY_AUTH.getCode(); @@ -60,7 +65,7 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu return WebFluxResultUtils.result(exchange, error); } if (checkKey(exchange, keyAuthRuleHandle.getKeyName(), keyAuthRuleHandle.getKey())) { - return chain.execute(exchange); + return KeyAuthAuthentication.execute(exchange, chain, rule); } Object error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.ERROR_KEY); return WebFluxResultUtils.result(exchange, error); diff --git a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthenticationHttpTest.java b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthenticationHttpTest.java new file mode 100644 index 000000000000..3107d668ea36 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthenticationHttpTest.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.shenyu.plugin.key.auth; + +import org.apache.shenyu.common.config.ShenyuConfig; +import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.common.dto.SelectorData; +import org.apache.shenyu.common.enums.SelectorTypeEnum; +import org.apache.shenyu.plugin.api.result.DefaultShenyuResult; +import org.apache.shenyu.plugin.api.result.ShenyuResult; +import org.apache.shenyu.plugin.api.utils.SpringBeanUtils; +import org.apache.shenyu.plugin.base.cache.BaseDataCache; +import org.apache.shenyu.plugin.key.auth.handler.KeyAuthPluginDataHandler; +import org.junit.jupiter.api.Test; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; +import reactor.netty.resources.LoopResources; +import reactor.test.StepVerifier; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Real HTTP requests through the public plugin entry and the server-owned rule cache. + */ +class KeyAuthAuthenticationHttpTest { + + @Test + void authenticatesHeaderAndQueryWithoutEchoingCredentials() { + try (Fixture fixture = new Fixture()) { + fixture.client.get().uri("/").header("X-Api-Key", "test-secret") + .header("X-Tenant-Id", "untrusted").exchange().expectStatus().isOk() + .expectBody(String.class).isEqualTo("http-namespace/http-selector/http-rule"); + fixture.client.get().uri("/?X-Api-Key=test-secret").exchange().expectStatus().isOk() + .expectBody(String.class).isEqualTo("http-namespace/http-selector/http-rule"); + assertEquals(2, fixture.calls.get()); + } + } + + @Test + void invalidCredentialNeverInvokesBusinessHandler() { + try (Fixture fixture = new Fixture()) { + fixture.client.get().uri("/").header("X-Api-Key", "wrong-secret").exchange() + .expectBody(String.class).value(body -> assertFalse(body.contains("wrong-secret"))); + fixture.client.get().uri("/").header("X-Tenant-Id", "untrusted").exchange().expectBody(); + assertEquals(0, fixture.calls.get()); + } + } + + @Test + void concurrentValidAndInvalidRequestsStayIsolated() { + try (Fixture fixture = new Fixture()) { + WebClient client = WebClient.builder().baseUrl(fixture.url()).build(); + StepVerifier.create(Flux.range(0, 32).flatMap(index -> client.get().uri("/") + .header("X-Api-Key", index % 2 == 0 ? "test-secret" : "invalid") + .retrieve().bodyToMono(String.class).doOnNext(body -> { + if (index % 2 == 0) { + assertEquals("http-namespace/http-selector/http-rule", body); + } else { + assertFalse(body.contains("http-rule")); + } + }), 8).then()).expectComplete().verify(Duration.ofSeconds(30)); + assertEquals(16, fixture.calls.get()); + } + } + + @Test + void disabledPluginDoesNotMakeDownstreamAuthenticated() { + try (Fixture fixture = new Fixture()) { + fixture.data.setEnabled(false); + BaseDataCache.getInstance().cachePluginData(fixture.data); + fixture.client.get().uri("/").header("X-Api-Key", "test-secret").exchange().expectStatus().isUnauthorized(); + assertEquals(0, fixture.calls.get()); + } + } + + private static final class Fixture implements AutoCloseable { + + private final KeyAuthPlugin plugin = new KeyAuthPlugin(); + + private final KeyAuthPluginDataHandler handler = new KeyAuthPluginDataHandler(); + + private final AtomicInteger calls = new AtomicInteger(); + + private final RuleData rule = new RuleData(); + + private final PluginData data = new PluginData(); + + private final LoopResources loops = LoopResources.create("key-auth-test", 2, true); + + private final DisposableServer server; + + private final WebTestClient client; + + private Fixture() { + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); + ShenyuConfig config = new ShenyuConfig(); + config.getSelectorMatchCache().getCache().setEnabled(false); + config.getRuleMatchCache().getCache().setEnabled(false); + when(context.getBean(ShenyuConfig.class)).thenReturn(config); + when(context.getBean(ShenyuResult.class)).thenReturn(new DefaultShenyuResult()); + SpringBeanUtils.getInstance().setApplicationContext(context); + data.setName(plugin.named()); + data.setEnabled(true); + BaseDataCache.getInstance().cachePluginData(data); + SelectorData selector = new SelectorData(); + selector.setId("http-selector"); + selector.setPluginName(plugin.named()); + selector.setType(SelectorTypeEnum.FULL_FLOW.getCode()); + selector.setContinued(true); + selector.setEnabled(true); + selector.setLogged(false); + selector.setSort(0); + BaseDataCache.getInstance().cacheSelectData(selector); + rule.setId("http-rule"); + rule.setSelectorId(selector.getId()); + rule.setNamespaceId("http-namespace"); + rule.setEnabled(true); + rule.setLoged(false); + rule.setSort(0); + rule.setHandle("{\"keyName\":\"X-Api-Key\",\"key\":\"test-secret\"}"); + handler.handlerRule(rule); + BaseDataCache.getInstance().cacheRuleData(rule); + server = HttpServer.create().host("127.0.0.1").port(0).runOn(loops) + .handle(new ReactorHttpHandlerAdapter(WebHttpHandlerBuilder.webHandler(exchange -> + plugin.execute(exchange, this::business)).build())).bindNow(Duration.ofSeconds(20)); + client = WebTestClient.bindToServer().baseUrl(url()).responseTimeout(Duration.ofSeconds(20)).build(); + } + + private Mono business(final ServerWebExchange exchange) { + return KeyAuthAuthentication.from(exchange).map(result -> { + calls.incrementAndGet(); + return result.getNamespaceId() + "/" + result.getSelectorId() + "/" + result.getRuleId(); + }).switchIfEmpty(Mono.defer(() -> { + exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); + return Mono.just("unauthenticated"); + })).flatMap(body -> exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory() + .wrap(body.getBytes(StandardCharsets.UTF_8))))).subscribeOn(Schedulers.parallel()); + } + + private String url() { + return "http://127.0.0.1:" + server.port(); + } + + @Override + public void close() { + server.disposeNow(Duration.ofSeconds(10)); + loops.disposeLater().block(Duration.ofSeconds(10)); + handler.removeRule(rule); + BaseDataCache.getInstance().removeRuleDataBySelectorId(rule.getSelectorId()); + BaseDataCache.getInstance().removeSelectDataByPluginName(plugin.named()); + BaseDataCache.getInstance().removePluginDataByPluginName(plugin.named()); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthenticationTest.java b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthenticationTest.java new file mode 100644 index 000000000000..ed1d1681bdf0 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthAuthenticationTest.java @@ -0,0 +1,331 @@ +/* + * 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.plugin.key.auth; + +import org.apache.shenyu.common.config.ShenyuConfig; +import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.common.dto.SelectorData; +import org.apache.shenyu.common.enums.SelectorTypeEnum; +import org.apache.shenyu.plugin.api.ShenyuPluginChain; +import org.apache.shenyu.plugin.api.result.DefaultShenyuResult; +import org.apache.shenyu.plugin.api.result.ShenyuResult; +import org.apache.shenyu.plugin.api.utils.SpringBeanUtils; +import org.apache.shenyu.plugin.base.cache.BaseDataCache; +import org.apache.shenyu.plugin.key.auth.handler.KeyAuthPluginDataHandler; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; +import reactor.core.scheduler.Schedulers; +import reactor.test.StepVerifier; + +import java.security.Principal; +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Authentication publication and request-boundary regression tests. + */ +class KeyAuthAuthenticationTest { + + private final KeyAuthPlugin plugin = new KeyAuthPlugin(); + + private final KeyAuthPluginDataHandler handler = new KeyAuthPluginDataHandler(); + + private RuleData rule; + + @BeforeEach + void setUp() { + rule = new RuleData(); + rule.setId("verified-rule"); + rule.setSelectorId("verified-selector"); + rule.setNamespaceId("config-namespace"); + rule.setHandle("{\"keyName\":\"X-Api-Key\",\"key\":\"test-secret\"}"); + handler.handlerRule(rule); + ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); + when(context.getBean(ShenyuResult.class)).thenReturn(new DefaultShenyuResult()); + ShenyuConfig config = new ShenyuConfig(); + config.getSelectorMatchCache().getCache().setEnabled(false); + config.getRuleMatchCache().getCache().setEnabled(false); + when(context.getBean(ShenyuConfig.class)).thenReturn(config); + SpringBeanUtils.getInstance().setApplicationContext(context); + } + + @AfterEach + void cleanUp() { + handler.removeRule(rule); + BaseDataCache.getInstance().removePluginDataByPluginName(plugin.named()); + BaseDataCache.getInstance().removeSelectDataByPluginName(plugin.named()); + BaseDataCache.getInstance().removeRuleDataBySelectorId("verified-selector"); + } + + @Test + void publishesVerifiedHeaderResultAfterSchedulerSwitch() { + ServerWebExchange exchange = request("test-secret"); + ShenyuPluginChain chain = current -> KeyAuthAuthentication.from(current) + .switchIfEmpty(Mono.error(new AssertionError("Missing verified key-auth result"))) + .doOnNext(this::assertRule).then().subscribeOn(Schedulers.parallel()); + StepVerifier.create(authenticate(exchange, chain)).expectComplete().verify(Duration.ofSeconds(10)); + StepVerifier.create(KeyAuthAuthentication.from(exchange)).verifyComplete(); + } + + @Test + void publishesVerifiedQueryResult() { + ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/mcp") + .queryParam("X-Api-Key", "test-secret")); + StepVerifier.create(authenticate(exchange, current -> KeyAuthAuthentication.from(current) + .switchIfEmpty(Mono.error(new AssertionError("Missing query authentication result"))) + .doOnNext(this::assertRule).then())).verifyComplete(); + } + + @Test + void rejectsWrongKeyBeforeDownstream() { + AtomicInteger calls = new AtomicInteger(); + ServerWebExchange exchange = request("wrong-secret"); + StepVerifier.create(authenticate(exchange, current -> { + calls.incrementAndGet(); + return Mono.empty(); + })).verifyComplete(); + assertEquals(0, calls.get()); + StepVerifier.create(KeyAuthAuthentication.from(exchange)).verifyComplete(); + } + + @Test + void cannotReadAnotherRequestsAuthentication() { + ServerWebExchange exchange = request("test-secret"); + ServerWebExchange other = request("test-secret"); + StepVerifier.create(authenticate(exchange, current -> KeyAuthAuthentication.from(current) + .switchIfEmpty(Mono.error(new AssertionError("Missing current authentication"))) + .flatMap(result -> KeyAuthAuthentication.from(other).hasElement()) + .doOnNext(present -> assertFalse(present)).then())).verifyComplete(); + } + + @Test + void ignoresIdentityHeadersAndAttributesWithoutAuthentication() { + ServerWebExchange exchange = request("test-secret"); + exchange.getAttributes().put(KeyAuthAuthentication.class.getName(), "forged"); + StepVerifier.create(KeyAuthAuthentication.from(exchange.mutate() + .request(builder -> builder.header("X-Tenant-Id", "admin")).build())).verifyComplete(); + } + + @Test + void preservesPrincipalHeadersAndExchangeAttributes() { + Principal principal = () -> "existing-principal"; + ServerWebExchange exchange = request("test-secret").mutate().principal(Mono.just(principal)).build(); + Map attributes = Map.copyOf(exchange.getAttributes()); + StepVerifier.create(authenticate(exchange, current -> current.getPrincipal() + .doOnNext(value -> assertSame(principal, value)) + .then(required(current.mutate().request(builder -> builder.path("/rewritten")).build()) + .doOnNext(this::assertRule)).then())).verifyComplete(); + assertEquals(attributes, exchange.getAttributes()); + assertEquals("test-secret", exchange.getRequest().getHeaders().getFirst("X-Api-Key")); + } + + @Test + void retainsSnapshotAfterRuleMutation() { + StepVerifier.create(authenticate(request("test-secret"), current -> required(current).doOnNext(result -> { + rule.setNamespaceId("replacement-namespace"); + rule.setSelectorId("replacement-selector"); + rule.setId("replacement-rule"); + assertRule(result); + rule.setSelectorId("verified-selector"); + rule.setId("verified-rule"); + }).then())).verifyComplete(); + } + + @Test + void missingNamespaceIsNotInventedAsTenant() { + rule.setNamespaceId(null); + StepVerifier.create(authenticate(request("test-secret"), current -> required(current) + .doOnNext(result -> assertNull(result.getNamespaceId())).then())).verifyComplete(); + } + + @Test + void missingKeyAndInvalidConfigurationNeverInvokeDownstream() { + ShenyuPluginChain fail = current -> Mono.error(new AssertionError("Unauthenticated invocation")); + StepVerifier.create(authenticate(MockServerWebExchange.from(MockServerHttpRequest.get("/mcp")), fail)).verifyComplete(); + rule.setHandle("{}"); + handler.handlerRule(rule); + StepVerifier.create(authenticate(request("test-secret"), fail)).verifyComplete(); + handler.removeRule(rule); + StepVerifier.create(authenticate(request("test-secret"), fail)).verifyComplete(); + } + + @Test + void preservesExistingHeaderOrQueryAcceptance() { + ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/mcp") + .header("X-Api-Key", "wrong").queryParam("X-Api-Key", "test-secret")); + StepVerifier.create(authenticate(exchange, current -> required(current).doOnNext(this::assertRule).then())).verifyComplete(); + } + + @Test + void bypassedPluginDoesNotInheritAuthentication() { + ServerWebExchange exchange = request("test-secret"); + StepVerifier.create(authenticate(exchange, current -> plugin.execute(current, nested -> + KeyAuthAuthentication.from(nested).hasElement().doOnNext(present -> assertFalse(present)).then()) + .then(required(current).doOnNext(this::assertRule)).then())).verifyComplete(); + } + + @Test + void disabledPluginDoesNotInheritAuthentication() { + PluginData data = new PluginData(); + data.setName(plugin.named()); + data.setEnabled(false); + BaseDataCache.getInstance().cachePluginData(data); + StepVerifier.create(authenticate(request("test-secret"), current -> plugin.execute(current, nested -> + KeyAuthAuthentication.from(nested).hasElement().doOnNext(present -> assertFalse(present)).then()))).verifyComplete(); + } + + @Test + void unmatchedPluginDoesNotInheritAuthentication() { + PluginData data = new PluginData(); + data.setName(plugin.named()); + data.setEnabled(true); + BaseDataCache.getInstance().cachePluginData(data); + StepVerifier.create(authenticate(request("test-secret"), current -> plugin.execute(current, nested -> + KeyAuthAuthentication.from(nested).hasElement().doOnNext(present -> assertFalse(present)).then()))).verifyComplete(); + } + + @Test + void subscriptionAuthenticatesAgainstCurrentConfiguration() { + configureMatchingPlugin(); + AtomicInteger calls = new AtomicInteger(); + Mono execution = plugin.execute(request("test-secret"), current -> required(current) + .doOnNext(result -> calls.incrementAndGet()).then()); + assertEquals(0, calls.get()); + StepVerifier.create(execution).verifyComplete(); + assertEquals(1, calls.get()); + rule.setHandle("{\"keyName\":\"X-Api-Key\",\"key\":\"rotated-secret\"}"); + handler.handlerRule(rule); + StepVerifier.create(execution).verifyComplete(); + assertEquals(1, calls.get()); + StepVerifier.create(plugin.execute(request("rotated-secret"), current -> required(current) + .doOnNext(result -> calls.incrementAndGet()).then())).verifyComplete(); + assertEquals(2, calls.get()); + } + + @Test + void concurrentRequestsKeepIndependentRuleSnapshots() { + AtomicInteger calls = new AtomicInteger(); + StepVerifier.create(Flux.range(0, 32).flatMap(index -> { + RuleData concurrent = new RuleData(); + concurrent.setId("concurrent-" + index); + concurrent.setSelectorId("selector-" + index); + concurrent.setNamespaceId("namespace-" + index); + concurrent.setHandle(rule.getHandle()); + handler.handlerRule(concurrent); + ServerWebExchange exchange = request("test-secret"); + return plugin.doExecute(exchange, current -> Mono.delay(Duration.ofMillis(2)) + .then(required(current)).doOnNext(result -> { + assertEquals(concurrent.getId(), result.getRuleId()); + assertEquals(concurrent.getSelectorId(), result.getSelectorId()); + assertEquals(concurrent.getNamespaceId(), result.getNamespaceId()); + calls.incrementAndGet(); + }).then(), new SelectorData(), concurrent).subscribeOn(Schedulers.parallel()) + .doFinally(signal -> handler.removeRule(concurrent)); + }, 16)).expectComplete().verify(Duration.ofSeconds(15)); + assertEquals(32, calls.get()); + } + + @Test + void errorAndCancellationDoNotLeakAuthentication() { + ServerWebExchange exchange = request("test-secret"); + StepVerifier.create(authenticate(exchange, current -> required(current) + .flatMap(result -> Mono.error(new IllegalStateException("downstream failed"))))) + .expectErrorMessage("downstream failed").verify(); + StepVerifier.create(KeyAuthAuthentication.from(exchange)).verifyComplete(); + AtomicBoolean cancelled = new AtomicBoolean(); + StepVerifier.create(authenticate(exchange, current -> required(current) + .then(Mono.never()).doOnCancel(() -> cancelled.set(true)))) + .thenCancel().verify(); + assertTrue(cancelled.get()); + StepVerifier.create(KeyAuthAuthentication.from(exchange)).verifyComplete(); + StepVerifier.create(authenticate(request("test-secret"), current -> required(current).then())).verifyComplete(); + } + + @Test + void rotationDoesNotRewriteInflightSnapshot() { + configureMatchingPlugin(); + Sinks.One release = Sinks.one(); + ServerWebExchange exchange = request("test-secret"); + StepVerifier.create(plugin.execute(exchange, current -> required(current).flatMap(result -> { + rule.setHandle("{\"keyName\":\"X-Api-Key\",\"key\":\"rotated-secret\"}"); + handler.handlerRule(rule); + release.tryEmitEmpty(); + return release.asMono().then(required(current)).doOnNext(value -> assertSame(result, value)).then(); + }))).verifyComplete(); + StepVerifier.create(plugin.execute(request("test-secret"), current -> + Mono.error(new AssertionError("Revoked credential reached downstream")))).verifyComplete(); + } + + private Mono required(final ServerWebExchange exchange) { + return KeyAuthAuthentication.from(exchange).switchIfEmpty(Mono.error(new AssertionError("Missing authentication"))); + } + + private void configureMatchingPlugin() { + PluginData data = new PluginData(); + data.setName(plugin.named()); + data.setEnabled(true); + BaseDataCache.getInstance().cachePluginData(data); + SelectorData selector = new SelectorData(); + selector.setId(rule.getSelectorId()); + selector.setPluginName(plugin.named()); + selector.setType(SelectorTypeEnum.FULL_FLOW.getCode()); + selector.setEnabled(true); + selector.setContinued(true); + selector.setLogged(false); + selector.setSort(0); + rule.setEnabled(true); + rule.setLoged(false); + rule.setSort(0); + BaseDataCache.getInstance().cacheSelectData(selector); + BaseDataCache.getInstance().cacheRuleData(rule); + } + + private Mono authenticate(final ServerWebExchange exchange, final ShenyuPluginChain chain) { + return plugin.doExecute(exchange, chain, new SelectorData(), rule); + } + + private ServerWebExchange request(final String key) { + return MockServerWebExchange.from(MockServerHttpRequest.get("/mcp").header("X-Api-Key", key)); + } + + private void assertRule(final KeyAuthAuthentication result) { + assertEquals("config-namespace", result.getNamespaceId()); + assertEquals("verified-selector", result.getSelectorId()); + assertEquals("verified-rule", result.getRuleId()); + assertFalse(result.toString().contains("test-secret")); + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml index 3ce2ba86b8d2..a018ca75c08f 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml @@ -26,6 +26,32 @@ shenyu-spring-boot-starter-plugin-agent-gateway + + org.springframework.security + spring-security-oauth2-resource-server + true + + + org.springframework.security + spring-security-oauth2-jose + true + + + org.springframework.security + spring-security-oauth2-client + true + + + org.springframework.security + spring-security-config + test + + + org.apache.shenyu + shenyu-plugin-key-auth + ${project.version} + true + io.opentelemetry opentelemetry-api diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java index 4ab469170e64..b9467ef27740 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java @@ -37,12 +37,14 @@ import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.core.env.Environment; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.apache.shenyu.plugin.agent.gateway.remote.ManagedRemoteMcpCatalog; import org.apache.shenyu.plugin.agent.gateway.remote.RemoteServiceCredentialResolver; import org.apache.shenyu.plugin.agent.gateway.remote.FileRemoteServiceCredentialResolver; import java.net.URI; import java.nio.file.Path; import java.util.Arrays; +import java.util.List; import java.util.Set; import java.util.stream.Collectors; import reactor.core.publisher.Mono; @@ -71,13 +73,25 @@ public ShenyuPlugin agentGatewayPlugin(final ObjectProvider p if (environment.getProperty("shenyu.plugins.agent.gateway.tracing.enabled", Boolean.class, false) && java.util.Objects.isNull(tracer)) { throw new IllegalStateException("Enabled MCP tracing requires an application tracing bridge"); } + if (environment.getProperty("shenyu.plugins.agent.gateway.security.key-auth.enabled", Boolean.class, false) + && resolvers.stream().noneMatch(resolver -> resolver instanceof KeyAuthMcpSecurityResolver)) { + throw new IllegalStateException("Enabled key-auth MCP authorization requires the key-auth plugin dependency"); + } + if (environment.getProperty("shenyu.plugins.agent.gateway.security.principal.enabled", Boolean.class, false) + && resolvers.stream().noneMatch(resolver -> "org.apache.shenyu.springboot.starter.plugin.agent.gateway.PrincipalMcpSecurityResolver".equals(resolver.getClass().getName()))) { + throw new IllegalStateException("Enabled MCP principal authorization requires an explicit source and its optional dependencies"); + } return createPlugin(providers, resolvers, catalogs.getIfAvailable(), tracer); } private ShenyuPlugin createPlugin(final ObjectProvider providers, final ObjectProvider resolvers, final AgentMcpRemoteCatalog catalog, final AgentMcpCallTracer tracer) { AgentToolRegistry registry = new AgentToolRegistry(providers.orderedStream().toList()); - AgentMcpSecurityResolver resolver = resolvers.getIfAvailable(() -> exchange -> Mono.empty()); + List candidates = resolvers.stream().toList(); + if (candidates.size() > 1) { + throw new IllegalStateException("MCP requires exactly one authoritative security resolver"); + } + AgentMcpSecurityResolver resolver = candidates.isEmpty() ? exchange -> Mono.empty() : candidates.get(0); return new AgentGatewayPlugin(new AgentMcpHttpHandler(new AgentMcpDispatcher(registry, "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, catalog), resolver, tracer)); } @@ -112,6 +126,103 @@ public ManagedRemoteMcpCatalog agentGatewayRemoteCatalog(final Environment envir return new ManagedRemoteMcpCatalog(allowed, tools.orderedStream().map(AgentToolProvider::getName).collect(Collectors.toUnmodifiableSet()), resolver); } + private static Mono keyAuthenticationPresent(final org.springframework.web.server.ServerWebExchange exchange) { + if (org.springframework.util.ClassUtils.isPresent("org.apache.shenyu.plugin.key.auth.KeyAuthAuthentication", AgentGatewayPluginConfiguration.class.getClassLoader())) { + return org.apache.shenyu.plugin.key.auth.KeyAuthAuthentication.from(exchange).hasElement(); + } + return Mono.just(false); + } + + private static java.util.function.Predicate> tokenAuthority(final PrincipalMcpSecurityProperties properties) { + String issuer = PrincipalMcpSecurityResolver.text(properties.getIssuer()); + String audience = PrincipalMcpSecurityResolver.text(properties.getAudience()); + if (java.util.Objects.nonNull(properties.getRegistrationId())) { + throw new IllegalArgumentException("Token source does not accept a login registration"); + } + return attributes -> issuer.equals(attributes.get("iss")) + && PrincipalMcpSecurityResolver.names(attributes.get("aud"), false).contains(audience); + } + + /** + * Explicit opt-in; authentication remains owned by the earlier key-auth plugin. + */ + @Configuration(proxyBeanMethods = false) + @ConditionalOnClass(name = "org.apache.shenyu.plugin.key.auth.KeyAuthAuthentication") + @ConditionalOnProperty(value = "shenyu.plugins.agent.gateway.security.key-auth.enabled", havingValue = "true") + @EnableConfigurationProperties(KeyAuthMcpSecurityProperties.class) + static class KeyAuthConfiguration { + + /** + * Snapshot deployment-owned bindings, rejecting duplicate or incomplete identities. + * @param properties explicit authorization bindings + * @return the sole key-auth identity adapter + */ + @Bean + KeyAuthMcpSecurityResolver agentGatewayKeyAuthSecurityResolver(final KeyAuthMcpSecurityProperties properties) { + return new KeyAuthMcpSecurityResolver(properties); + } + } + + /** + * Reuse an application-owned JWT Resource Server without building another authenticator. + */ + @Configuration(proxyBeanMethods = false) + @ConditionalOnClass(name = {"org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken", "org.springframework.security.oauth2.jwt.Jwt"}) + @ConditionalOnProperty(prefix = "shenyu.plugins.agent.gateway.security.principal", name = "enabled", havingValue = "true") + @EnableConfigurationProperties(PrincipalMcpSecurityProperties.class) + static class JwtPrincipalConfiguration { + + @Bean + @ConditionalOnProperty(prefix = "shenyu.plugins.agent.gateway.security.principal", name = "source", havingValue = "jwt") + AgentMcpSecurityResolver agentGatewayPrincipalJwtResolver(final PrincipalMcpSecurityProperties properties) { + var authority = tokenAuthority(properties); + return new PrincipalMcpSecurityResolver<>(properties, org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken.class, + org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken::getTokenAttributes, + authentication -> authority.test(authentication.getTokenAttributes()), AgentGatewayPluginConfiguration::keyAuthenticationPresent); + } + } + + /** + * Reuse the application's opaque-token introspection result, not the bearer credential. + */ + @Configuration(proxyBeanMethods = false) + @ConditionalOnClass(name = "org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication") + @ConditionalOnProperty(prefix = "shenyu.plugins.agent.gateway.security.principal", name = "enabled", havingValue = "true") + @EnableConfigurationProperties(PrincipalMcpSecurityProperties.class) + static class OpaquePrincipalConfiguration { + + @Bean + @ConditionalOnProperty(prefix = "shenyu.plugins.agent.gateway.security.principal", name = "source", havingValue = "opaque-token") + AgentMcpSecurityResolver agentGatewayPrincipalOpaqueResolver(final PrincipalMcpSecurityProperties properties) { + var authority = tokenAuthority(properties); + return new PrincipalMcpSecurityResolver<>(properties, org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication.class, + org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication::getTokenAttributes, + authentication -> authority.test(authentication.getTokenAttributes()), AgentGatewayPluginConfiguration::keyAuthenticationPresent); + } + } + + /** + * Reuse the authenticated login principal for one explicitly trusted client registration. + */ + @Configuration(proxyBeanMethods = false) + @ConditionalOnClass(name = "org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken") + @ConditionalOnProperty(prefix = "shenyu.plugins.agent.gateway.security.principal", name = "enabled", havingValue = "true") + @EnableConfigurationProperties(PrincipalMcpSecurityProperties.class) + static class LoginPrincipalConfiguration { + + @Bean + @ConditionalOnProperty(prefix = "shenyu.plugins.agent.gateway.security.principal", name = "source", havingValue = "oauth2-login") + AgentMcpSecurityResolver agentGatewayPrincipalLoginResolver(final PrincipalMcpSecurityProperties properties) { + String registration = PrincipalMcpSecurityResolver.text(properties.getRegistrationId()); + if (java.util.Objects.nonNull(properties.getIssuer()) || java.util.Objects.nonNull(properties.getAudience())) { + throw new IllegalArgumentException("Login source is bound by client registration, not token issuer/audience settings"); + } + return new PrincipalMcpSecurityResolver<>(properties, org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken.class, + authentication -> authentication.getPrincipal().getAttributes(), + authentication -> registration.equals(authentication.getAuthorizedClientRegistrationId()), AgentGatewayPluginConfiguration::keyAuthenticationPresent); + } + } + /** * Optional API bridge; SDK, exporters and their lifecycle belong to the application. */ diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityProperties.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityProperties.java new file mode 100644 index 000000000000..3698aea44678 --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityProperties.java @@ -0,0 +1,128 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.List; +import java.util.Set; + +/** + * Deployment-owned authorization bindings, containing rule references but never API keys. + * Bindings are snapshotted at startup; editing this bean cannot change in-flight authorization. + */ +@ConfigurationProperties(prefix = "shenyu.plugins.agent.gateway.security.key-auth", ignoreUnknownFields = false) +public class KeyAuthMcpSecurityProperties { + + private boolean enabled; + + private List bindings = List.of(); + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + + public List getBindings() { + return bindings; + } + + public void setBindings(final List bindings) { + this.bindings = bindings; + } + + /** + * One exact authenticated rule mapped to one service identity and exact tool names. + * Configuration namespace is part of the reference, never an implicit tenant. + */ + public static class Binding { + + private String namespaceId; + + private String selectorId; + + private String ruleId; + + private String tenant; + + private String subject; + + private Set toolGrants = Set.of(); + + private Set toolDenials = Set.of(); + + public String getNamespaceId() { + return namespaceId; + } + + public void setNamespaceId(final String namespaceId) { + this.namespaceId = namespaceId; + } + + public String getSelectorId() { + return selectorId; + } + + public void setSelectorId(final String selectorId) { + this.selectorId = selectorId; + } + + public String getRuleId() { + return ruleId; + } + + public void setRuleId(final String ruleId) { + this.ruleId = ruleId; + } + + public String getTenant() { + return tenant; + } + + public void setTenant(final String tenant) { + this.tenant = tenant; + } + + public String getSubject() { + return subject; + } + + public void setSubject(final String subject) { + this.subject = subject; + } + + public Set getToolGrants() { + return toolGrants; + } + + public void setToolGrants(final Set toolGrants) { + this.toolGrants = toolGrants; + } + + public Set getToolDenials() { + return toolDenials; + } + + public void setToolDenials(final Set toolDenials) { + this.toolDenials = toolDenials; + } + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityResolver.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityResolver.java new file mode 100644 index 000000000000..a57b4730cbf8 --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityResolver.java @@ -0,0 +1,93 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpIdentity; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; +import org.apache.shenyu.plugin.key.auth.KeyAuthAuthentication; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Reuses key-auth's verified result, never reinterpreting wire credentials as identity. + * A key-auth rule denotes a service identity; it does not identify individual users sharing a key. + */ +public final class KeyAuthMcpSecurityResolver implements AgentMcpSecurityResolver { + + private final Map, AgentMcpIdentity> identities; + + public KeyAuthMcpSecurityResolver(final KeyAuthMcpSecurityProperties properties) { + if (Objects.requireNonNull(properties.getBindings(), "bindings").size() > 1024) { + throw new IllegalArgumentException("Too many key-auth authorization bindings"); + } + Map, AgentMcpIdentity> snapshot = new HashMap<>(); + for (KeyAuthMcpSecurityProperties.Binding binding : Objects.requireNonNull(properties.getBindings(), "bindings")) { + List reference = List.of(text(binding.getNamespaceId(), "namespaceId"), text(binding.getSelectorId(), "selectorId"), text(binding.getRuleId(), "ruleId")); + AgentMcpIdentity identity = new AgentMcpIdentity(text(binding.getTenant(), "tenant"), text(binding.getSubject(), "subject"), + tools(binding.getToolGrants()), tools(binding.getToolDenials())); + if (Objects.nonNull(snapshot.putIfAbsent(reference, identity))) { + throw new IllegalArgumentException("Duplicate key-auth authorization binding"); + } + } + if (snapshot.isEmpty()) { + throw new IllegalArgumentException("Key-auth authorization requires explicit bindings"); + } + identities = Map.copyOf(snapshot); + } + + @Override + public Mono resolve(final ServerWebExchange exchange) { + return Mono.defer(() -> exchange.getPrincipal().hasElement().flatMap(hasPrincipal -> { + if (hasPrincipal) { + return Mono.empty(); + } + return KeyAuthAuthentication.from(exchange).flatMap(authentication -> { + if (Objects.isNull(authentication.getNamespaceId()) || Objects.isNull(authentication.getSelectorId()) || Objects.isNull(authentication.getRuleId())) { + return Mono.empty(); + } + AgentMcpIdentity identity = identities.get(List.of(authentication.getNamespaceId(), authentication.getSelectorId(), authentication.getRuleId())); + return Mono.justOrEmpty(identity); + }); + })); + } + + private static String text(final String value, final String name) { + if (Objects.isNull(value) || value.isBlank() || value.length() > 256 || !value.equals(value.strip()) || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(name + " must be bounded nonblank text without surrounding whitespace or controls"); + } + return value; + } + + private static Set tools(final Set names) { + if (Objects.requireNonNull(names, "tool names").size() > 1024) { + throw new IllegalArgumentException("Too many tool permissions"); + } + for (String name : Objects.requireNonNull(names, "tool names")) { + if (!text(name, "tool name").matches("[A-Za-z0-9_.-]{1,128}")) { + throw new IllegalArgumentException("Tool grants and denials require exact tool names"); + } + } + return Set.copyOf(names); + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityProperties.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityProperties.java new file mode 100644 index 000000000000..91d0d99ea48f --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityProperties.java @@ -0,0 +1,136 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.List; +import java.util.Set; + +/** + * Explicit application-authenticated principal policy; never a credential source. + */ +@ConfigurationProperties(prefix = "shenyu.plugins.agent.gateway.security.principal", ignoreUnknownFields = false) +public class PrincipalMcpSecurityProperties { + + private boolean enabled; + + private String source; + + private String issuer; + + private String audience; + + private String registrationId; + + private String defaultTenant; + + private List scopeMappings = List.of(); + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + + public String getSource() { + return source; + } + + public void setSource(final String source) { + this.source = source; + } + + public String getIssuer() { + return issuer; + } + + public void setIssuer(final String issuer) { + this.issuer = issuer; + } + + public String getAudience() { + return audience; + } + + public void setAudience(final String audience) { + this.audience = audience; + } + + public String getRegistrationId() { + return registrationId; + } + + public void setRegistrationId(final String registrationId) { + this.registrationId = registrationId; + } + + public String getDefaultTenant() { + return defaultTenant; + } + + public void setDefaultTenant(final String defaultTenant) { + this.defaultTenant = defaultTenant; + } + + public List getScopeMappings() { + return scopeMappings; + } + + public void setScopeMappings(final List scopeMappings) { + this.scopeMappings = scopeMappings; + } + + /** + * One exact scope maps to exact tools; names are never implicitly grants. + */ + public static class ScopeMapping { + + private String scope; + + private Set toolGrants = Set.of(); + + private Set toolDenials = Set.of(); + + public String getScope() { + return scope; + } + + public void setScope(final String scope) { + this.scope = scope; + } + + public Set getToolGrants() { + return toolGrants; + } + + public void setToolGrants(final Set toolGrants) { + this.toolGrants = toolGrants; + } + + public Set getToolDenials() { + return toolDenials; + } + + public void setToolDenials(final Set toolDenials) { + this.toolDenials = toolDenials; + } + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityResolver.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityResolver.java new file mode 100644 index 000000000000..8e497c4d544a --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityResolver.java @@ -0,0 +1,161 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpIdentity; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; +import org.springframework.security.core.Authentication; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * Maps one configured, application-authenticated principal type into immutable tool permissions. + * Authentication, token validation and the filter chain remain application-owned. + * @param the sole accepted authentication type + */ +public final class PrincipalMcpSecurityResolver implements AgentMcpSecurityResolver { + + private final Class type; + + private final Function> attributes; + + private final Predicate authority; + + private final Function> conflict; + + private final String defaultTenant; + + private final Map> grants; + + private final Map> denials; + + public PrincipalMcpSecurityResolver(final PrincipalMcpSecurityProperties properties, final Class type, + final Function> attributes, final Predicate authority, + final Function> conflict) { + this.type = Objects.requireNonNull(type); + this.attributes = Objects.requireNonNull(attributes); + this.authority = Objects.requireNonNull(authority); + this.conflict = Objects.requireNonNull(conflict); + defaultTenant = Objects.isNull(properties.getDefaultTenant()) ? null : text(properties.getDefaultTenant()); + Map> allowed = new HashMap<>(); + Map> denied = new HashMap<>(); + if (properties.getScopeMappings().size() > 1024) { + throw new IllegalArgumentException("Too many scope mappings"); + } + for (PrincipalMcpSecurityProperties.ScopeMapping mapping : properties.getScopeMappings()) { + String scope = scope(mapping.getScope()); + if (Objects.nonNull(allowed.putIfAbsent(scope, names(mapping.getToolGrants(), true)))) { + throw new IllegalArgumentException("Duplicate scope mapping"); + } + denied.put(scope, names(mapping.getToolDenials(), true)); + } + grants = Map.copyOf(allowed); + denials = Map.copyOf(denied); + } + + @Override + public Mono resolve(final ServerWebExchange exchange) { + return Mono.defer(() -> conflict.apply(exchange).flatMap(ambiguous -> ambiguous ? Mono.empty() + : exchange.getPrincipal().ofType(type).filter(Authentication::isAuthenticated).flatMap(authentication -> { + try { + if (!authority.test(authentication)) { + return Mono.empty(); + } + Map claims = attributes.apply(authentication); + String subject = text(claims.get("sub")); + if (!subject.equals(authentication.getName())) { + return Mono.empty(); + } + String tenant = text(claims.containsKey("tenant_id") ? claims.get("tenant_id") : defaultTenant); + Set allowed = new HashSet<>(names(claims.getOrDefault("tool_grants", Set.of()), true)); + Set denied = new HashSet<>(names(claims.getOrDefault("tool_denies", Set.of()), true)); + for (String scope : scopes(claims)) { + allowed.addAll(grants.getOrDefault(scope, Set.of())); + denied.addAll(denials.getOrDefault(scope, Set.of())); + } + return Mono.just(new AgentMcpIdentity(tenant, subject, allowed, denied)); + } catch (IllegalArgumentException error) { + // Invalid trusted attributes fail closed; do not log claims or credentials. + return Mono.empty(); + } + }))); + } + + static String text(final Object value) { + if (!(value instanceof String string) || string.isBlank() || string.length() > 256 + || !string.equals(string.strip()) || string.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Invalid identity attribute or policy"); + } + return string; + } + + static Set names(final Object value, final boolean tools) { + if (!(value instanceof Collection values) || values.size() > 1024) { + throw new IllegalArgumentException("Invalid permission or audience attributes"); + } + Set result = new HashSet<>(); + for (Object item : values) { + String name = text(item); + if (tools && !name.matches("[A-Za-z0-9_.-]{1,128}")) { + throw new IllegalArgumentException("Tool permissions must be exact names"); + } + result.add(name); + } + return Set.copyOf(result); + } + + private static Set scopes(final Map claims) { + Set scope = claims.containsKey("scope") ? scopeNames(claims.get("scope")) : Set.of(); + Set scp = claims.containsKey("scp") ? scopeNames(claims.get("scp")) : Set.of(); + if (claims.containsKey("scope") && claims.containsKey("scp") && !scope.equals(scp)) { + throw new IllegalArgumentException("Conflicting scope attributes"); + } + return claims.containsKey("scope") ? scope : scp; + } + + private static Set scopeNames(final Object value) { + Object values = value; + if (value instanceof String string) { + if (string.length() > 8192 || !string.equals(string.strip())) { + throw new IllegalArgumentException("Invalid scope string"); + } + values = string.isEmpty() ? Set.of() : Arrays.asList(string.split(" ", -1)); + } + Set result = names(values, false); + result.forEach(PrincipalMcpSecurityResolver::scope); + return result; + } + + private static String scope(final String value) { + String result = text(value); + if (result.chars().anyMatch(character -> character < 33 || character > 126 || character == 34 || character == 92)) { + throw new IllegalArgumentException("Invalid scope name"); + } + return result; + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpHttpTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpHttpTest.java new file mode 100644 index 000000000000..a89a831beb5a --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpHttpTest.java @@ -0,0 +1,208 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import com.google.gson.JsonObject; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.http.HttpHeaders; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Sinks; +import reactor.test.StepVerifier; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Set; + +import static org.apache.shenyu.springboot.starter.plugin.agent.gateway.KeyAuthMcpTestFixture.headers; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Real loopback HTTP through both public plugin entries, rule matching and tool execution. + * The rule cache is a fixture, not an Admin/WebSocket deployment. + */ +class KeyAuthMcpHttpTest { + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void listsAndCallsOnlyEffectiveTools(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, false)) { + JsonObject listed = fixture.success("/a", "key-a", "tools/list", ""); + assertEquals(1, listed.getAsJsonObject("result").getAsJsonArray("tools").size()); + assertEquals("read-a", listed.getAsJsonObject("result").getAsJsonArray("tools").get(0) + .getAsJsonObject().get("name").getAsString()); + fixture.success("/a", "key-a", "tools/call", "read-a"); + fixture.success("/a?X-Api-Key=key-a", "", "tools/call", "read-a"); + assertEquals(2, fixture.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void rejectsDenialsRuleExclusionsAndCrossTenantToolsWithoutExecution(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, false)) { + for (String tool : List.of("read-b", "blocked", "outside", "unknown")) { + fixture.request("/a", "key-a", "tools/call", tool).expectStatus().isForbidden(); + } + assertEquals(0, fixture.calls()); + fixture.success("/b", "key-b", "tools/call", "read-b"); + assertEquals(1, fixture.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void invalidUnboundAndUnmatchedCredentialsDoNotGrantIdentity(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, false)) { + fixture.request("/a", "wrong", "tools/call", "read-a").expectBody(String.class) + .value(body -> assertFalse(body.contains("\"isError\":false"))); + fixture.request("/a", "", "tools/call", "read-a").expectBody(); + fixture.request("/unbound", "key-unbound", "tools/call", "read-a").expectStatus().isUnauthorized(); + fixture.request("/unmatched", "key-a", "tools/call", "read-a").expectStatus().isUnauthorized(); + assertEquals(0, fixture.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void concurrentTenantsKeepIdentityAcrossSchedulers(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, false)) { + WebClient client = WebClient.create(fixture.url()); + StepVerifier.create(Flux.range(0, 24).flatMap(index -> { + String tenant = index % 2 == 0 ? "a" : "b"; + return client.post().uri("/" + tenant) + .headers(headers -> headers(headers, "key-" + tenant, "tools/call", "read-" + tenant)) + .bodyValue(fixture.body("tools/call", "read-" + tenant)).retrieve().bodyToMono(byte[].class) + .doOnNext(bytes -> { + JsonObject result = KeyAuthMcpTestFixture.parse(new String(bytes, StandardCharsets.UTF_8)) + .getAsJsonObject("result").getAsJsonObject("structuredContent"); + assertEquals("tenant-" + tenant, result.get("tenant").getAsString()); + assertEquals("service", result.get("subject").getAsString()); + }); + }, 8).then()).expectComplete().verify(Duration.ofSeconds(45)); + assertEquals(24, fixture.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void principalConflictIsRejectedInsteadOfOverridden(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, true)) { + fixture.request("/a", "key-a", "tools/list", "").expectStatus().isUnauthorized(); + fixture.request("/a", "key-a", "tools/call", "read-a").expectStatus().isUnauthorized(); + assertEquals(0, fixture.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void disabledAuthenticationAndKeyRotationFailClosed(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, false)) { + fixture.rotateKey(); + fixture.request("/a", "key-a", "tools/call", "read-a").expectBody(); + assertEquals(0, fixture.calls()); + fixture.success("/a", "rotated", "tools/call", "read-a"); + fixture.disableAuthentication(); + fixture.request("/a", "rotated", "tools/call", "read-a").expectStatus().isUnauthorized(); + assertEquals(1, fixture.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void policyIsFrozenAndRuleRevocationAppliesToNewRequests(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, false)) { + fixture.mutateBinding(); + JsonObject result = fixture.success("/a", "key-a", "tools/call", "read-a") + .getAsJsonObject("result").getAsJsonObject("structuredContent"); + assertEquals("tenant-a", result.get("tenant").getAsString()); + fixture.revokeTools(); + fixture.request("/a", "key-a", "tools/call", "read-a").expectStatus().isForbidden(); + assertEquals(0, fixture.success("/a", "key-a", "tools/list", "") + .getAsJsonObject("result").getAsJsonArray("tools").size()); + assertEquals(1, fixture.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void cancellationIsIsolatedFromLaterRequests(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, false)) { + fixture.pending(Sinks.one()); + HttpHeaders requestHeaders = new HttpHeaders(); + headers(requestHeaders, "key-a", "tools/call", "read-a"); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/a") + .headers(requestHeaders) + .body(fixture.body("tools/call", "read-a"))); + StepVerifier.create(fixture.execute(exchange)).then(() -> { + assertEquals(1, fixture.calls()); + AgentMcpExecutionContext context = fixture.captured(); + assertEquals("tenant-a", context.getTenant().orElseThrow()); + assertEquals(Set.of("read-a"), context.getAllowedTools()); + }).thenCancel().verify(Duration.ofSeconds(10)); + assertTrue(fixture.cancelled()); + fixture.pending(null); + fixture.request("/unmatched", "key-a", "tools/call", "read-a").expectStatus().isUnauthorized(); + fixture.success("/b", "key-b", "tools/call", "read-b"); + assertEquals(2, fixture.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void namespaceMustMatchTheExplicitBinding(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, false)) { + fixture.changeNamespace("another-namespace"); + fixture.request("/a", "key-a", "tools/call", "read-a").expectStatus().isUnauthorized(); + fixture.changeNamespace(null); + fixture.request("/a", "key-a", "tools/list", "").expectStatus().isUnauthorized(); + assertEquals(0, fixture.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void inflightExecutionRetainsItsSnapshotAfterRevocation(final String mode) { + try (KeyAuthMcpTestFixture fixture = new KeyAuthMcpTestFixture(mode, false)) { + Sinks.One pending = Sinks.one(); + fixture.pending(pending); + HttpHeaders requestHeaders = new HttpHeaders(); + headers(requestHeaders, "key-a", "tools/call", "read-a"); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/a") + .headers(requestHeaders).body(fixture.body("tools/call", "read-a"))); + StepVerifier.create(fixture.execute(exchange)).then(() -> { + final AgentMcpExecutionContext original = fixture.captured(); + fixture.revokeTools(); + fixture.mutateBinding(); + fixture.request("/a", "key-a", "tools/call", "read-a").expectStatus().isForbidden(); + assertEquals(Set.of("read-a"), original.getAllowedTools()); + assertEquals("tenant-a", original.getTenant().orElseThrow()); + assertEquals(Sinks.EmitResult.OK, pending.tryEmitValue(new JsonObject())); + }).verifyComplete(); + assertEquals(200, exchange.getResponse().getStatusCode().value()); + assertEquals(1, fixture.calls()); + } + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityConfigurationTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityConfigurationTest.java new file mode 100644 index 000000000000..833aae2f33cb --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpSecurityConfigurationTest.java @@ -0,0 +1,230 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import org.apache.shenyu.common.dto.AgentGatewayResultFilterConfig; +import org.apache.shenyu.plugin.agent.gateway.AgentGatewayPlugin; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpIdentity; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.test.context.FilteredClassLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.time.Instant; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class KeyAuthMcpSecurityConfigurationTest { + + private static final String PREFIX = "shenyu.plugins.agent.gateway.security.key-auth."; + + private final ApplicationContextRunner runner = new ApplicationContextRunner() + .withUserConfiguration(AgentGatewayPluginConfiguration.class) + .withPropertyValues("shenyu.plugins.agent.gateway.enabled=true"); + + @Test + void principalAdapterIsOptionalAndRequiresExplicitSource() { + runner.withPropertyValues("shenyu.plugins.agent.gateway.security.principal.enabled=true") + .run(context -> assertNotNull(context.getStartupFailure())); + runner.withPropertyValues("shenyu.plugins.agent.gateway.security.principal.enabled=true", + "shenyu.plugins.agent.gateway.security.principal.source=unknown") + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void principalIdentityCanOnlyBeConfiguredOnce() { + runner.withPropertyValues("shenyu.plugins.agent.gateway.security.principal.enabled=true", + "shenyu.plugins.agent.gateway.security.principal.source=jwt", + "shenyu.plugins.agent.gateway.security.principal.issuer=https://issuer.example", + "shenyu.plugins.agent.gateway.security.principal.audience=mcp") + .run(context -> { + assertNull(context.getStartupFailure()); + assertEquals(1, context.getBeansOfType(AgentMcpSecurityResolver.class).size()); + }); + } + + @Test + void principalDependenciesAreOptionalWhenDisabled() { + runner.withClassLoader(new FilteredClassLoader("org.springframework.security")) + .run(context -> assertNull(context.getStartupFailure())); + principalConfigured().withClassLoader(new FilteredClassLoader("org.springframework.security")) + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @ParameterizedTest + @ValueSource(strings = {"org.springframework.security.oauth2.jwt", "org.springframework.security.oauth2.server.resource"}) + void principalRequiresItsSelectedDependency(final String dependency) { + principalConfigured().withClassLoader(new FilteredClassLoader(dependency)) + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void loginRequiresOnlyItsOwnOptionalDependencies() { + runner.withClassLoader(new FilteredClassLoader("org.springframework.security.oauth2.jwt", "org.springframework.security.oauth2.server.resource")) + .withPropertyValues("shenyu.plugins.agent.gateway.security.principal.enabled=true", + "shenyu.plugins.agent.gateway.security.principal.source=oauth2-login", + "shenyu.plugins.agent.gateway.security.principal.registration-id=trusted") + .run(context -> assertNull(context.getStartupFailure())); + } + + @ParameterizedTest + @ValueSource(strings = {"issuer=", "audience=", "default-tenant=", "registration-id=unexpected", + "scope-mappings[0].tool-grants=*", "scope-mappings[0].scope=", "scope-mappings[0].tool-denys=read", "unknown=true"}) + void principalRejectsInvalidPolicy(final String invalid) { + principalConfigured().withPropertyValues("shenyu.plugins.agent.gateway.security.principal." + invalid) + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void principalRejectsDuplicateScopeBindings() { + principalConfigured().withPropertyValues("shenyu.plugins.agent.gateway.security.principal.scope-mappings[1].scope=inventory:read") + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void principalConflictsWithCustomResolverEvenIfPrimary() { + principalConfigured().withBean("other", AgentMcpSecurityResolver.class, () -> exchange -> Mono.empty(), definition -> definition.setPrimary(true)) + .run(context -> assertNotNull(context.getStartupFailure())); + configured().withPropertyValues("shenyu.plugins.agent.gateway.security.principal.enabled=true", + "shenyu.plugins.agent.gateway.security.principal.source=jwt", + "shenyu.plugins.agent.gateway.security.principal.issuer=https://issuer.example", + "shenyu.plugins.agent.gateway.security.principal.audience=mcp") + .run(context -> assertNotNull(context.getStartupFailure())); + } + + private ApplicationContextRunner principalConfigured() { + return runner.withPropertyValues("shenyu.plugins.agent.gateway.security.principal.enabled=true", + "shenyu.plugins.agent.gateway.security.principal.source=jwt", + "shenyu.plugins.agent.gateway.security.principal.issuer=https://issuer.example", + "shenyu.plugins.agent.gateway.security.principal.audience=mcp", + "shenyu.plugins.agent.gateway.security.principal.scope-mappings[0].scope=inventory:read", + "shenyu.plugins.agent.gateway.security.principal.scope-mappings[0].tool-grants=read"); + } + + @Test + void remainsOptionalAndOffByDefault() { + runner.withClassLoader(new FilteredClassLoader("org.apache.shenyu.plugin.key.auth")) + .run(context -> { + assertNull(context.getStartupFailure()); + assertNotNull(context.getBean(AgentGatewayPlugin.class)); + assertFalse(context.containsBean("agentGatewayKeyAuthSecurityResolver")); + }); + } + + @Test + void enabledAdapterRequiresDependency() { + configured().withClassLoader(new FilteredClassLoader("org.apache.shenyu.plugin.key.auth")) + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void bindsExplicitPolicyButDoesNotAuthenticateHeaders() { + configured().run(context -> { + assertNull(context.getStartupFailure()); + AgentMcpSecurityResolver resolver = context.getBean(AgentMcpSecurityResolver.class); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/mcp") + .header("X-Api-Key", "secret").header("X-Tenant-Id", "tenant").header("X-Subject", "service")); + StepVerifier.create(resolver.resolve(exchange)).verifyComplete(); + }); + } + + @ParameterizedTest + @ValueSource(strings = {"namespace-id", "selector-id", "rule-id", "tenant", "subject"}) + void rejectsMissingIdentityFields(final String field) { + configured().withPropertyValues(PREFIX + "bindings[0]." + field + "=") + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void rejectsEmptyPolicy() { + runner.withPropertyValues(PREFIX + "enabled=true").run(context -> assertNotNull(context.getStartupFailure())); + } + + @ParameterizedTest + @ValueSource(strings = {"tool-grants", "tool-denials"}) + void rejectsWildcardPermissions(final String field) { + configured().withPropertyValues(PREFIX + "bindings[0]." + field + "=*") + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void rejectsUnknownConfigurationFields() { + configured().withPropertyValues(PREFIX + "bindings[0].tool-denys=read") + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void rejectsUnboundedOrControlCharacterIdentityBindings() { + configured().withPropertyValues(PREFIX + "bindings[0].tenant=" + "x".repeat(257)) + .run(context -> assertNotNull(context.getStartupFailure())); + configured().withPropertyValues(PREFIX + "bindings[0].subject=service" + (char) 9 + "other") + .run(context -> assertNotNull(context.getStartupFailure())); + KeyAuthMcpSecurityProperties properties = new KeyAuthMcpSecurityProperties(); + properties.setBindings(java.util.Collections.nCopies(1025, new KeyAuthMcpSecurityProperties.Binding())); + assertThrows(IllegalArgumentException.class, () -> new KeyAuthMcpSecurityResolver(properties)); + } + + @Test + void rejectsDuplicateRuleReferences() { + configured().withPropertyValues(PREFIX + "bindings[1].namespace-id=namespace", PREFIX + "bindings[1].selector-id=selector", + PREFIX + "bindings[1].rule-id=rule", PREFIX + "bindings[1].tenant=another", PREFIX + "bindings[1].subject=service") + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void primaryCannotHideConflictingAuthority() { + configured().withBean("other", AgentMcpSecurityResolver.class, () -> exchange -> Mono.empty(), definition -> definition.setPrimary(true)) + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void immutableIdentityDenialsPrecedeRuleIntersection() { + Set grants = new HashSet<>(Set.of("read", "denied", "outside")); + Set denials = new HashSet<>(Set.of("denied")); + AgentMcpIdentity identity = new AgentMcpIdentity("tenant", "service", grants, denials); + grants.clear(); + denials.clear(); + AgentMcpExecutionContext context = new AgentMcpExecutionContext("request", identity.getSubject(), "rule", 1, + Set.of("read", "denied"), identity.getToolGrants(), Instant.MAX, AgentGatewayResultFilterConfig.empty(), identity.getTenant().orElseThrow()); + assertEquals(Set.of("read"), context.getAllowedTools()); + assertEquals(Set.of("denied"), identity.getToolDenials()); + assertEquals("tenant", context.getTenant().orElseThrow()); + assertThrows(UnsupportedOperationException.class, () -> identity.getToolGrants().add("denied")); + assertThrows(IllegalArgumentException.class, () -> new AgentMcpIdentity(" ", "service", Set.of(), Set.of())); + assertFalse(new AgentMcpIdentity("legacy", Set.of()).getTenant().isPresent()); + } + + private ApplicationContextRunner configured() { + return runner.withPropertyValues(PREFIX + "enabled=true", PREFIX + "bindings[0].namespace-id=namespace", + PREFIX + "bindings[0].selector-id=selector", PREFIX + "bindings[0].rule-id=rule", PREFIX + "bindings[0].tenant=tenant", + PREFIX + "bindings[0].subject=service", PREFIX + "bindings[0].tool-grants=read,denied", PREFIX + "bindings[0].tool-denials=denied"); + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpTestFixture.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpTestFixture.java new file mode 100644 index 000000000000..0ef9dfc4cc1d --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/KeyAuthMcpTestFixture.java @@ -0,0 +1,327 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.apache.shenyu.common.config.ShenyuConfig; +import org.apache.shenyu.common.dto.ConditionData; +import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.common.dto.SelectorData; +import org.apache.shenyu.plugin.agent.gateway.AgentGatewayPlugin; +import org.apache.shenyu.plugin.agent.gateway.handler.AgentGatewayPluginDataHandler; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpHttpHandler; +import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolProvider; +import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry; +import org.apache.shenyu.plugin.api.result.DefaultShenyuResult; +import org.apache.shenyu.plugin.api.result.ShenyuResult; +import org.apache.shenyu.plugin.api.utils.SpringBeanUtils; +import org.apache.shenyu.plugin.base.cache.BaseDataCache; +import org.apache.shenyu.plugin.key.auth.KeyAuthPlugin; +import org.apache.shenyu.plugin.key.auth.handler.KeyAuthPluginDataHandler; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; +import reactor.core.scheduler.Schedulers; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; +import reactor.netty.resources.LoopResources; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Public plugin chain and loopback HTTP with a fixture-owned synchronized configuration cache. + */ +final class KeyAuthMcpTestFixture implements AutoCloseable { + + private final KeyAuthPlugin keyPlugin = new KeyAuthPlugin(); + + private final KeyAuthPluginDataHandler keyHandler = new KeyAuthPluginDataHandler(); + + private final AgentGatewayPluginDataHandler gatewayHandler = new AgentGatewayPluginDataHandler(); + + private final KeyAuthMcpSecurityProperties properties = new KeyAuthMcpSecurityProperties(); + + private final List keyRules = new ArrayList<>(); + + private final AtomicInteger calls = new AtomicInteger(); + + private final AtomicBoolean cancelled = new AtomicBoolean(); + + private final AtomicReference captured = new AtomicReference<>(); + + private volatile Sinks.One pending; + + private final PluginData keyData; + + private final RuleData gatewayRule; + + private final AgentGatewayPlugin gateway; + + private final WebTestClient client; + + private final LoopResources loops = LoopResources.create("key-auth-mcp-test", 2, true); + + private final DisposableServer server; + + KeyAuthMcpTestFixture(final String mode, final boolean principal) { + this(mode, principal, null, null); + } + + KeyAuthMcpTestFixture(final String mode, final org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver resolver, + final org.springframework.web.server.WebFilter filter) { + this(mode, false, resolver, filter); + } + + private KeyAuthMcpTestFixture(final String mode, final boolean principal, + final org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver resolver, final org.springframework.web.server.WebFilter filter) { + ConfigurableApplicationContext application = mock(ConfigurableApplicationContext.class); + ShenyuConfig config = new ShenyuConfig(); + config.getSelectorMatchCache().getCache().setEnabled(false); + config.getRuleMatchCache().getCache().setEnabled(false); + when(application.getBean(ShenyuConfig.class)).thenReturn(config); + when(application.getBean(ShenyuResult.class)).thenReturn(new DefaultShenyuResult()); + SpringBeanUtils.getInstance().setApplicationContext(application); + keyData = registerPlugin(keyPlugin.named()); + configureKeys(); + gateway = new AgentGatewayPlugin(new AgentMcpHttpHandler(new AgentMcpDispatcher(new AgentToolRegistry( + List.of(tool("read-a"), tool("read-b"), tool("blocked"), tool("outside"))), "test", "1"), + java.util.Objects.isNull(resolver) ? new KeyAuthMcpSecurityResolver(properties) : resolver)); + registerPlugin(gateway.named()); + gatewayRule = rule(selector(gateway.named(), "gateway-selector", true), "gateway-rule", + "{\"trafficType\":\"mcp\",\"mcp\":{\"responseMode\":\"" + mode + "\",\"allowedTools\":[\"read-a\",\"read-b\",\"blocked\"]}}"); + gatewayHandler.handlerRule(gatewayRule); + BaseDataCache.getInstance().cacheRuleData(gatewayRule); + WebHttpHandlerBuilder builder = WebHttpHandlerBuilder.webHandler(exchange -> execute(principal + ? exchange.mutate().principal(Mono.just(() -> "other-authority")).build() : exchange)); + if (java.util.Objects.nonNull(filter)) { + builder.filter(filter); + } + server = HttpServer.create().host("127.0.0.1").port(0).runOn(loops) + .handle(new ReactorHttpHandlerAdapter(builder.build())) + .bindNow(Duration.ofSeconds(20)); + client = WebTestClient.bindToServer().baseUrl(url()).responseTimeout(Duration.ofSeconds(20)).build(); + } + + Mono execute(final ServerWebExchange exchange) { + return keyPlugin.execute(exchange, authenticated -> gateway.execute(authenticated, + ignored -> Mono.error(new AssertionError("MCP must terminate at Agent Gateway")))); + } + + String url() { + return "http://127.0.0.1:" + server.port(); + } + + int calls() { + return calls.get(); + } + + boolean cancelled() { + return cancelled.get(); + } + + AgentMcpExecutionContext captured() { + return captured.get(); + } + + void pending(final Sinks.One value) { + pending = value; + } + + void rotateKey() { + keyRules.get(0).setHandle("{\"keyName\":\"X-Api-Key\",\"key\":\"rotated\"}"); + keyHandler.handlerRule(keyRules.get(0)); + } + + void disableAuthentication() { + keyData.setEnabled(false); + BaseDataCache.getInstance().cachePluginData(keyData); + } + + void mutateBinding() { + properties.getBindings().get(0).setTenant("mutated"); + properties.getBindings().get(0).setToolGrants(Set.of("read-b")); + } + + void revokeTools() { + gatewayRule.setHandle("{\"trafficType\":\"mcp\",\"mcp\":{\"allowedTools\":[]}}"); + gatewayHandler.handlerRule(gatewayRule); + } + + void changeNamespace(final String namespace) { + keyRules.get(0).setNamespaceId(namespace); + keyHandler.handlerRule(keyRules.get(0)); + } + + WebTestClient.ResponseSpec request(final String path, final String key, final String method, final String tool) { + return client.post().uri(path).headers(headers -> headers(headers, key, method, tool)).bodyValue(body(method, tool)).exchange(); + } + + JsonObject success(final String path, final String key, final String method, final String tool) { + return parse(request(path, key, method, tool).expectStatus().isOk().expectBody(String.class) + .returnResult().getResponseBody()); + } + + static JsonObject parse(final String body) { + String json = body; + if (body.startsWith("event: message\ndata: ")) { + assertEquals(1, body.split("event: message", -1).length - 1); + assertTrue(body.endsWith("\n\n")); + json = body.substring("event: message\ndata: ".length()).trim(); + } + return JsonParser.parseString(json).getAsJsonObject(); + } + + String body(final String method, final String tool) { + JsonObject request = new JsonObject(); + request.addProperty("jsonrpc", "2.0"); + request.addProperty("id", 1); + request.addProperty("method", method); + JsonObject params = JsonParser.parseString("{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\"," + + "\"io.modelcontextprotocol/clientCapabilities\":{}}}").getAsJsonObject(); + if (!tool.isEmpty()) { + params.addProperty("name", tool); + params.add("arguments", new JsonObject()); + } + request.add("params", params); + return request.toString(); + } + + static void headers(final HttpHeaders headers, final String key, final String method, final String tool) { + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Accept", "application/json, text/event-stream"); + headers.set("MCP-Protocol-Version", "2026-07-28"); + headers.set("Mcp-Method", method); + if (!tool.isEmpty()) { + headers.set("Mcp-Name", tool); + } + if (!key.isEmpty()) { + headers.set("X-Api-Key", key); + } + headers.set("X-Tenant-Id", "forged"); + headers.set("X-Subject", "forged"); + } + + private void configureKeys() { + SelectorData selector = selector(keyPlugin.named(), "auth-selector", false); + List bindings = new ArrayList<>(); + for (String tenant : List.of("a", "b", "unbound")) { + final RuleData rule = rule(selector, "rule-" + tenant, "{\"keyName\":\"X-Api-Key\",\"key\":\"key-" + tenant + "\"}"); + ConditionData condition = new ConditionData(); + condition.setParamType("uri"); + condition.setOperator("="); + condition.setParamValue("/" + tenant); + rule.setConditionDataList(List.of(condition)); + keyHandler.handlerRule(rule); + BaseDataCache.getInstance().cacheRuleData(rule); + keyRules.add(rule); + if (!"unbound".equals(tenant)) { + KeyAuthMcpSecurityProperties.Binding binding = new KeyAuthMcpSecurityProperties.Binding(); + binding.setNamespaceId("namespace"); + binding.setSelectorId(selector.getId()); + binding.setRuleId(rule.getId()); + binding.setTenant("tenant-" + tenant); + binding.setSubject("service"); + binding.setToolGrants(Set.of("read-" + tenant, "blocked", "outside")); + binding.setToolDenials(Set.of("blocked")); + bindings.add(binding); + } + } + properties.setBindings(bindings); + } + + private AgentToolProvider tool(final String name) { + AgentToolProvider provider = mock(AgentToolProvider.class); + when(provider.getName()).thenReturn(name); + when(provider.getDescription()).thenReturn("Test tool " + name); + when(provider.getInputSchema()).thenReturn(JsonParser.parseString("{\"type\":\"object\"}").getAsJsonObject()); + when(provider.getRequiredClientCapabilities()).thenReturn(new JsonObject()); + when(provider.invoke(any())).thenAnswer(ignored -> Mono.deferContextual(context -> { + AgentMcpExecutionContext identity = context.get(AgentMcpExecutionContext.class); + captured.set(identity); + calls.incrementAndGet(); + JsonObject result = new JsonObject(); + result.addProperty("tenant", identity.getTenant().orElseThrow()); + result.addProperty("subject", identity.getSubject()); + Sinks.One current = pending; + return java.util.Objects.isNull(current) ? Mono.just(result).publishOn(Schedulers.parallel()) + : current.asMono().doOnCancel(() -> cancelled.set(true)); + })); + return provider; + } + + private PluginData registerPlugin(final String name) { + PluginData data = new PluginData(); + data.setName(name); + data.setEnabled(true); + BaseDataCache.getInstance().cachePluginData(data); + return data; + } + + private SelectorData selector(final String pluginName, final String id, final boolean full) { + ConditionData condition = new ConditionData(); + condition.setParamType("uri"); + condition.setOperator("match"); + condition.setParamValue("/**"); + SelectorData data = SelectorData.builder().id(id).pluginName(pluginName).enabled(true).continued(true) + .logged(false).sort(0).type(full ? 0 : 1).matchMode(0).conditionList(List.of(condition)).build(); + BaseDataCache.getInstance().cacheSelectData(data); + return data; + } + + private RuleData rule(final SelectorData route, final String id, final String handle) { + return RuleData.builder().id(id).selectorId(route.getId()).pluginName(route.getPluginName()) + .namespaceId("namespace").enabled(true).loged(false).sort(0).matchMode(0).handle(handle).build(); + } + + @Override + public void close() { + server.disposeNow(Duration.ofSeconds(10)); + loops.disposeLater().block(Duration.ofSeconds(10)); + keyRules.forEach(keyHandler::removeRule); + gatewayHandler.removeRule(gatewayRule); + BaseDataCache cache = BaseDataCache.getInstance(); + cache.removeRuleDataBySelectorId("auth-selector"); + cache.removeRuleDataBySelectorId("gateway-selector"); + for (String name : List.of(keyPlugin.named(), gateway.named())) { + cache.removeSelectDataByPluginName(name); + cache.removePluginDataByPluginName(name); + } + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OAuthLoginMcpHttpTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OAuthLoginMcpHttpTest.java new file mode 100644 index 000000000000..3b74e269e779 --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OAuthLoginMcpHttpTest.java @@ -0,0 +1,188 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository; +import org.springframework.security.oauth2.client.web.server.WebSessionServerOAuth2AuthorizedClientRepository; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.web.server.WebFilterChainProxy; +import org.springframework.security.web.server.csrf.CsrfToken; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.server.WebFilter; +import org.springframework.web.util.UriComponentsBuilder; +import reactor.core.publisher.Mono; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; +import reactor.netty.resources.LoopResources; + +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Application OAuth login against a loopback identity provider, including session and CSRF. + */ +class OAuthLoginMcpHttpTest { + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void loginSessionHasTrustedToolsAndRetainsCsrfProtection(final String mode) { + try (Fixture fixture = new Fixture(mode)) { + fixture.call("tools/call", "read-a", null).expectStatus().isForbidden(); + fixture.login(); + assertEquals(1, fixture.tokenExchanges.get()); + assertEquals(1, fixture.userInfoRequests.get()); + fixture.call("tools/call", "read-a", null).expectStatus().isForbidden(); + assertEquals(0, fixture.gateway.calls()); + String csrf = fixture.csrf(); + fixture.call("tools/list", "", csrf).expectStatus().isOk().expectBody(String.class).value(body -> { + assertTrue(body.contains("\"name\":\"read-a\"")); + assertTrue(!body.contains("\"name\":\"blocked\"")); + }); + fixture.call("tools/call", "blocked", csrf).expectStatus().isForbidden(); + fixture.call("tools/call", "read-a", csrf).expectStatus().isOk().expectBody(String.class).value(body -> { + assertTrue(body.contains("\"tenant\":\"tenant-login\"")); + assertTrue(body.contains("\"subject\":\"login-service\"")); + }); + assertEquals(1, fixture.gateway.calls()); + fixture.gateway.revokeTools(); + fixture.call("tools/call", "read-a", csrf).expectStatus().isForbidden(); + assertEquals(1, fixture.gateway.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void invalidAuthorizationStateDoesNotCreateIdentity(final String mode) { + try (Fixture fixture = new Fixture(mode)) { + fixture.client.get().uri("/login/oauth2/code/trusted?code=fixture-code&state=forged") + .exchange().expectStatus().is3xxRedirection(); + assertEquals(0, fixture.tokenExchanges.get()); + fixture.call("tools/call", "read-a", "forged").expectStatus().isForbidden(); + assertEquals(0, fixture.gateway.calls()); + } + } + + private static final class Fixture implements AutoCloseable { + + private final AtomicInteger tokenExchanges = new AtomicInteger(); + + private final AtomicInteger userInfoRequests = new AtomicInteger(); + + private final LoopResources loops = LoopResources.create("oauth-login-provider", 2, true); + + private final DisposableServer provider; + + private final KeyAuthMcpTestFixture gateway; + + private final WebTestClient client; + + private final Map cookies = new HashMap<>(); + + private Fixture(final String mode) { + provider = HttpServer.create().host("127.0.0.1").port(0).runOn(loops).route(routes -> routes + .post("/token", (request, response) -> request.receive().aggregate().asString().flatMap(body -> { + assertTrue(body.contains("code=fixture-code")); + tokenExchanges.incrementAndGet(); + return response.header("Content-Type", "application/json").sendString(Mono.just( + "{\"access_token\":\"fixture-access-token\",\"token_type\":\"Bearer\",\"expires_in\":300,\"scope\":\"inventory:read\"}")).then(); + })) + .get("/userinfo", (request, response) -> { + assertEquals("Bearer fixture-access-token", request.requestHeaders().get("Authorization")); + userInfoRequests.incrementAndGet(); + return response.header("Content-Type", "application/json").sendString(Mono.just( + "{\"sub\":\"login-service\",\"tenant_id\":\"tenant-login\",\"scope\":\"inventory:read\",\"tool_grants\":[\"blocked\"]}")); + })).bindNow(Duration.ofSeconds(20)); + String base = "http://127.0.0.1:" + provider.port(); + ClientRegistration registration = ClientRegistration.withRegistrationId("trusted").clientId("fixture-client").clientSecret("fixture-secret") + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("inventory:read").authorizationUri(base + "/authorize").tokenUri(base + "/token").userInfoUri(base + "/userinfo").userNameAttributeName("sub").build(); + final var security = ServerHttpSecurity.http().authorizeExchange(exchanges -> exchanges.anyExchange().authenticated()) + .oauth2Login(login -> login.clientRegistrationRepository(new InMemoryReactiveClientRegistrationRepository(registration)) + .authorizedClientRepository(new WebSessionServerOAuth2AuthorizedClientRepository())).build(); + PrincipalMcpSecurityProperties policy = new PrincipalMcpSecurityProperties(); + policy.setRegistrationId("trusted"); + PrincipalMcpSecurityProperties.ScopeMapping scope = new PrincipalMcpSecurityProperties.ScopeMapping(); + scope.setScope("inventory:read"); + scope.setToolGrants(Set.of("read-a")); + scope.setToolDenials(Set.of("blocked")); + policy.setScopeMappings(List.of(scope)); + WebFilterChainProxy proxy = new WebFilterChainProxy(security); + WebFilter filter = (exchange, chain) -> proxy.filter(exchange, authenticated -> { + if ("/csrf".equals(authenticated.getRequest().getPath().value())) { + Mono csrf = authenticated.getAttribute(CsrfToken.class.getName()); + return csrf.flatMap(token -> { + authenticated.getResponse().getHeaders().set("X-Fixture-CSRF", token.getToken()); + return authenticated.getResponse().setComplete(); + }); + } + return chain.filter(authenticated); + }); + gateway = new KeyAuthMcpTestFixture(mode, new AgentGatewayPluginConfiguration.LoginPrincipalConfiguration().agentGatewayPrincipalLoginResolver(policy), filter); + client = WebTestClient.bindToServer().baseUrl(gateway.url()).responseTimeout(Duration.ofSeconds(20)).build(); + } + + private void login() { + EntityExchangeResult start = client.get().uri("/oauth2/authorization/trusted").exchange().expectStatus().is3xxRedirection().expectBody().returnResult(); + start.getResponseCookies().forEach((name, values) -> cookies.put(name, values.get(0).getValue())); + String state = UriComponentsBuilder.fromUri(start.getResponseHeaders().getLocation()).build().getQueryParams().getFirst("state"); + assertNotNull(state); + EntityExchangeResult callback = client.get().uri(java.net.URI.create(gateway.url() + "/login/oauth2/code/trusted?code=fixture-code&state=" + state)) + .cookies(values -> cookies.forEach(values::set)).exchange().expectStatus().is3xxRedirection() + .expectHeader().valueEquals("Location", "/").expectBody().returnResult(); + callback.getResponseCookies().forEach((name, values) -> cookies.put(name, values.get(0).getValue())); + } + + private String csrf() { + EntityExchangeResult result = client.get().uri("/csrf").cookies(values -> cookies.forEach(values::set)).exchange().expectStatus().isOk() + .expectBody().returnResult(); + result.getResponseCookies().forEach((name, values) -> cookies.put(name, values.get(0).getValue())); + String token = result.getResponseHeaders().getFirst("X-Fixture-CSRF"); + assertNotNull(token); + return token; + } + + private WebTestClient.ResponseSpec call(final String method, final String tool, final String csrf) { + return client.post().uri("/mcp").cookies(values -> cookies.forEach(values::set)).headers(headers -> { + KeyAuthMcpTestFixture.headers(headers, "", method, tool); + if (java.util.Objects.nonNull(csrf)) { + headers.set("X-CSRF-TOKEN", csrf); + } + }).bodyValue(gateway.body(method, tool)).exchange(); + } + + @Override + public void close() { + gateway.close(); + provider.disposeNow(Duration.ofSeconds(10)); + loops.disposeLater().block(Duration.ofSeconds(10)); + } + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpHttpTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpHttpTest.java new file mode 100644 index 000000000000..a58e265f7f31 --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpHttpTest.java @@ -0,0 +1,281 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import com.google.gson.Gson; +import com.nimbusds.jose.jwk.source.ImmutableSecret; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.oauth2.jose.jws.MacAlgorithm; +import org.springframework.security.oauth2.jwt.JwtClaimsSet; +import org.springframework.security.oauth2.jwt.JwtEncoderParameters; +import org.springframework.security.oauth2.jwt.JwtValidators; +import org.springframework.security.oauth2.jwt.JwsHeader; +import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; +import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder; +import org.springframework.security.oauth2.server.resource.introspection.NimbusReactiveOpaqueTokenIntrospector; +import org.springframework.security.web.server.WebFilterChainProxy; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; +import reactor.test.StepVerifier; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; +import reactor.netty.resources.LoopResources; + +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Real signature/introspection authentication and public key-auth/Agent Gateway plugin chain. + */ +class PrincipalMcpHttpTest { + + private static final String ISSUER = "https://issuer.example"; + + private static final byte[] KEY = "p0-02-loopback-test-key-not-a-production-secret".getBytes(StandardCharsets.UTF_8); + + @ParameterizedTest + @CsvSource({"jwt,json", "jwt,sse", "opaque-token,json", "opaque-token,sse"}) + void authenticatedScopeControlsListAndCallWithRuleIntersection(final String source, final String mode) { + try (Fixture fixture = new Fixture(source, mode)) { + String token = fixture.token(Map.of("scope", "inventory:read", "tool_grants", List.of("blocked", "outside"))); + fixture.request(token, "tools/list", "").exchange().expectStatus().isOk().expectBody(String.class).value(body -> { + assertTrue(body.contains("\"name\":\"read-a\"")); + assertTrue(!body.contains("\"name\":\"blocked\"") && !body.contains("\"name\":\"outside\"")); + }); + fixture.request(token, "tools/call", "blocked").exchange().expectStatus().isForbidden(); + fixture.request(token, "tools/call", "outside").exchange().expectStatus().isForbidden(); + assertEquals(0, fixture.gateway.calls()); + fixture.request(token, "tools/call", "read-a").exchange().expectStatus().isOk().expectBody(String.class) + .value(body -> assertTrue(body.contains("\"tenant\":\"tenant-a\""))); + assertEquals(1, fixture.gateway.calls()); + fixture.gateway.revokeTools(); + fixture.request(token, "tools/list", "").exchange().expectStatus().isOk().expectBody(String.class) + .value(body -> assertTrue(body.contains("\"tools\":[]"))); + fixture.request(token, "tools/call", "read-a").exchange().expectStatus().isForbidden(); + assertEquals(1, fixture.gateway.calls()); + } + } + + @ParameterizedTest + @CsvSource({"jwt,json", "jwt,sse", "opaque-token,json", "opaque-token,sse"}) + void invalidOrConflictingIdentityNeverExecutesTool(final String source, final String mode) { + try (Fixture fixture = new Fixture(source, mode)) { + fixture.request("invalid-token", "tools/call", "read-a").exchange().expectStatus().isUnauthorized(); + fixture.request(fixture.token(Map.of("iss", "https://other.example")), "tools/call", "read-a").exchange().expectStatus().isUnauthorized(); + fixture.request(fixture.token(Map.of("aud", List.of("wrong"))), "tools/call", "read-a").exchange().expectStatus().isUnauthorized(); + fixture.request(fixture.token(Map.of("tenant_id", "")), "tools/call", "read-a").exchange().expectStatus().isUnauthorized(); + fixture.request(fixture.token(Map.of("scope", "inventory:read", "scp", List.of("other"))), "tools/call", "read-a") + .exchange().expectStatus().isUnauthorized(); + fixture.request(fixture.token(Map.of("tool_grants", List.of("*"))), "tools/call", "read-a").exchange().expectStatus().isUnauthorized(); + String token = fixture.token(Map.of("scope", "inventory:read")); + fixture.request(token, "tools/call", "read-a", "/a", "key-a").exchange().expectStatus().isUnauthorized(); + assertEquals(0, fixture.gateway.calls()); + fixture.request(token, "tools/call", "read-a").exchange().expectStatus().isOk(); + assertEquals(1, fixture.gateway.calls()); + } + } + + @ParameterizedTest + @CsvSource({"jwt,json", "jwt,sse", "opaque-token,json", "opaque-token,sse"}) + void sameRpcIdConcurrentTenantsRemainIsolated(final String source, final String mode) { + try (Fixture fixture = new Fixture(source, mode)) { + WebClient client = WebClient.create(fixture.gateway.url()); + Flux.range(0, 16).flatMap(index -> { + String tenant = "tenant-" + index; + String token = fixture.token(Map.of("sub", "service-" + index, "tenant_id", tenant, "scope", "inventory:read")); + return client.post().uri("/mcp").headers(headers -> { + KeyAuthMcpTestFixture.headers(headers, "", "tools/call", "read-a"); + headers.setBearerAuth(token); + }).bodyValue(fixture.gateway.body("tools/call", "read-a")).retrieve().bodyToMono(String.class).doOnNext(body -> { + assertTrue(body.contains("\"tenant\":\"" + tenant + "\"")); + assertTrue(body.contains("\"subject\":\"service-" + index + "\"")); + }); + }, 8).collectList().block(Duration.ofSeconds(30)); + assertEquals(16, fixture.gateway.calls()); + } + } + + @ParameterizedTest + @CsvSource({"jwt,json", "jwt,sse", "opaque-token,json", "opaque-token,sse"}) + void credentialRevocationAndMissingScopesCannotGrantTools(final String source, final String mode) { + try (Fixture fixture = new Fixture(source, mode)) { + fixture.request(fixture.token(Map.of("scope", "read-a")), "tools/list", "").exchange().expectStatus().isOk().expectBody(String.class) + .value(body -> assertTrue(body.contains("\"tools\":[]"))); + if ("jwt".equals(source)) { + Instant now = Instant.now(); + String expired = fixture.token(Map.of("iat", now.minusSeconds(300), "exp", now.minusSeconds(120))); + fixture.request(expired, "tools/call", "read-a").exchange().expectStatus().isUnauthorized(); + JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(now).expiresAt(now.plusSeconds(120)) + .issuer(ISSUER).subject("service").audience(List.of("mcp")).claim("tenant_id", "tenant-a").claim("scope", "inventory:read").build(); + String forged = new NimbusJwtEncoder(new ImmutableSecret<>("untrusted-signature-key-at-least-32-bytes".getBytes(StandardCharsets.UTF_8))) + .encode(JwtEncoderParameters.from(JwsHeader.with(MacAlgorithm.HS256).build(), claims)).getTokenValue(); + fixture.request(forged, "tools/call", "read-a").exchange().expectStatus().isUnauthorized(); + } else { + String revoked = fixture.token(Map.of("scope", "inventory:read")); + fixture.tokens.remove(revoked); + fixture.request(revoked, "tools/call", "read-a").exchange().expectStatus().isUnauthorized(); + } + assertEquals(0, fixture.gateway.calls()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"jwt", "opaque-token"}) + void inFlightPrincipalSnapshotAndCancellationRemainRequestLocal(final String source) { + PrincipalMcpSecurityProperties policy = new PrincipalMcpSecurityProperties(); + policy.setIssuer(ISSUER); + policy.setAudience("mcp"); + org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver resolver = "jwt".equals(source) + ? new AgentGatewayPluginConfiguration.JwtPrincipalConfiguration().agentGatewayPrincipalJwtResolver(policy) + : new AgentGatewayPluginConfiguration.OpaquePrincipalConfiguration().agentGatewayPrincipalOpaqueResolver(policy); + try (KeyAuthMcpTestFixture gateway = new KeyAuthMcpTestFixture("json", resolver, null)) { + Map claims = Map.of("iss", ISSUER, "aud", List.of("mcp"), "sub", "service", + "tenant_id", "tenant-a", "tool_grants", List.of("read-a")); + org.springframework.security.core.Authentication authentication; + if ("jwt".equals(source)) { + authentication = new org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken( + new org.springframework.security.oauth2.jwt.Jwt("test", Instant.now(), Instant.now().plusSeconds(300), Map.of("alg", "HS256"), claims), List.of()); + } else { + authentication = new org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication( + new org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal(claims, List.of()), + new org.springframework.security.oauth2.core.OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken.TokenType.BEARER, + "test", Instant.now(), Instant.now().plusSeconds(300)), List.of()); + } + var request = org.springframework.mock.http.server.reactive.MockServerHttpRequest.post("/mcp") + .headers(headers()).body(gateway.body("tools/call", "read-a")); + var exchange = org.springframework.mock.web.server.MockServerWebExchange.from(request).mutate().principal(Mono.just(authentication)).build(); + gateway.pending(Sinks.one()); + StepVerifier.create(gateway.execute(exchange)).then(() -> { + assertEquals(1, gateway.calls()); + gateway.revokeTools(); + assertEquals(Set.of("read-a"), gateway.captured().getAllowedTools()); + assertEquals("tenant-a", gateway.captured().getTenant().orElseThrow()); + }).thenCancel().verify(Duration.ofSeconds(10)); + assertTrue(gateway.cancelled()); + assertEquals(1, gateway.calls()); + } + } + + private static org.springframework.http.HttpHeaders headers() { + org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders(); + KeyAuthMcpTestFixture.headers(headers, "", "tools/call", "read-a"); + return headers; + } + + private static final class Fixture implements AutoCloseable { + + private final String source; + + private final Map> tokens = new ConcurrentHashMap<>(); + + private final LoopResources loops = LoopResources.create("principal-introspection", 2, true); + + private final DisposableServer introspection; + + private final KeyAuthMcpTestFixture gateway; + + private final WebTestClient client; + + private Fixture(final String source, final String mode) { + this.source = source; + introspection = HttpServer.create().host("127.0.0.1").port(0).runOn(loops).handle((request, response) -> request.receive().aggregate().asString() + .flatMap(body -> { + Map claims = tokens.get(body.replace("token=", "")); + return response.header("Content-Type", "application/json").sendString(Mono.just(new Gson().toJson( + Objects.isNull(claims) ? Map.of("active", false) : claims))).then(); + })).bindNow(Duration.ofSeconds(20)); + PrincipalMcpSecurityProperties policy = new PrincipalMcpSecurityProperties(); + policy.setIssuer(ISSUER); + policy.setAudience("mcp"); + PrincipalMcpSecurityProperties.ScopeMapping mapping = new PrincipalMcpSecurityProperties.ScopeMapping(); + mapping.setScope("inventory:read"); + mapping.setToolGrants(Set.of("read-a", "blocked")); + mapping.setToolDenials(Set.of("blocked")); + policy.setScopeMappings(List.of(mapping)); + ServerHttpSecurity security = ServerHttpSecurity.http().authorizeExchange(exchanges -> exchanges.anyExchange().authenticated()); + org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver resolver; + if ("jwt".equals(source)) { + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withSecretKey(new SecretKeySpec(KEY, "HmacSHA256")).macAlgorithm(MacAlgorithm.HS256).build(); + decoder.setJwtValidator(JwtValidators.createDefaultWithIssuer(ISSUER)); + security.oauth2ResourceServer(resource -> resource.jwt(jwt -> jwt.jwtDecoder(decoder))); + resolver = new AgentGatewayPluginConfiguration.JwtPrincipalConfiguration().agentGatewayPrincipalJwtResolver(policy); + } else { + var inspector = new NimbusReactiveOpaqueTokenIntrospector("http://127.0.0.1:" + introspection.port() + "/introspect", "fixture-client", "fixture-secret"); + security.oauth2ResourceServer(resource -> resource.opaqueToken(opaque -> opaque.introspector(inspector))); + resolver = new AgentGatewayPluginConfiguration.OpaquePrincipalConfiguration().agentGatewayPrincipalOpaqueResolver(policy); + } + gateway = new KeyAuthMcpTestFixture(mode, resolver, new WebFilterChainProxy(security.build())); + client = WebTestClient.bindToServer().baseUrl(gateway.url()).responseTimeout(Duration.ofSeconds(30)).build(); + } + + private String token(final Map extra) { + Map claims = new HashMap<>(); + claims.put("sub", "service"); + claims.put("tenant_id", "tenant-a"); + claims.put("iss", ISSUER); + claims.put("aud", List.of("mcp")); + claims.put("active", true); + claims.putAll(extra); + if ("jwt".equals(source)) { + JwtClaimsSet.Builder builder = JwtClaimsSet.builder().issuedAt(Instant.now().minusSeconds(10)).expiresAt(Instant.now().plusSeconds(300)); + claims.forEach(builder::claim); + return new NimbusJwtEncoder(new ImmutableSecret<>(KEY)).encode( + JwtEncoderParameters.from(JwsHeader.with(MacAlgorithm.HS256).build(), builder.build())).getTokenValue(); + } + String token = UUID.randomUUID().toString(); + tokens.put(token, claims); + return token; + } + + private WebTestClient.RequestHeadersSpec request(final String token, final String method, final String tool) { + return request(token, method, tool, "/mcp", ""); + } + + private WebTestClient.RequestHeadersSpec request(final String token, final String method, final String tool, final String path, final String key) { + return client.post().uri(path).headers(headers -> { + KeyAuthMcpTestFixture.headers(headers, key, method, tool); + headers.setBearerAuth(token); + }).bodyValue(gateway.body(method, tool)); + } + + @Override + public void close() { + gateway.close(); + introspection.disposeNow(Duration.ofSeconds(10)); + loops.disposeLater().block(Duration.ofSeconds(10)); + } + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityResolverTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityResolverTest.java new file mode 100644 index 000000000000..a7e9a64bcaa0 --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/PrincipalMcpSecurityResolverTest.java @@ -0,0 +1,235 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpIdentity; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; +import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.user.DefaultOAuth2User; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrincipalMcpSecurityResolverTest { + + @ParameterizedTest + @ValueSource(strings = {"jwt", "opaque-token", "oauth2-login"}) + void explicitScopeMappingIsImmutableAndDenyWins(final String source) { + PrincipalMcpSecurityProperties policy = policy(source); + PrincipalMcpSecurityProperties.ScopeMapping mapping = mapping("inventory:read"); + mapping.setToolGrants(Set.of("read", "denied")); + mapping.setToolDenials(Set.of("denied")); + policy.setScopeMappings(List.of(mapping)); + final AgentMcpSecurityResolver resolver = resolver(policy); + mapping.setToolGrants(Set.of("admin")); + Map claims = claims(); + claims.put("scope", "inventory:read admin"); + claims.put("tool_grants", List.of("direct", "denied")); + claims.put("tool_denies", List.of("direct")); + AgentMcpIdentity identity = resolve(resolver, authentication(source, claims)); + assertEquals(Set.of("read"), identity.getToolGrants()); + assertEquals(Set.of("direct", "denied"), identity.getToolDenials()); + assertThrows(UnsupportedOperationException.class, () -> identity.getToolGrants().clear()); + } + + @ParameterizedTest + @ValueSource(strings = {"jwt", "opaque-token", "oauth2-login"}) + void missingScopeMappingNeverGrantsNamedTools(final String source) { + Map claims = claims(); + claims.remove("tool_grants"); + claims.put("scope", "read admin"); + assertTrue(resolve(resolver(policy(source)), authentication(source, claims)).getToolGrants().isEmpty()); + } + + @ParameterizedTest + @ValueSource(strings = {"jwt", "opaque-token", "oauth2-login"}) + void rejectsUnverifiedWrongTypeAndMissingPrincipal(final String source) { + AgentMcpSecurityResolver resolver = resolver(policy(source)); + Authentication authentication = authentication(source, claims()); + authentication.setAuthenticated(false); + assertNull(resolve(resolver, authentication)); + assertNull(resolve(resolver, null)); + assertNull(resolve(resolver, authentication("jwt".equals(source) ? "opaque-token" : "jwt", claims()))); + } + + @ParameterizedTest + @ValueSource(strings = {"jwt", "opaque-token", "oauth2-login"}) + void defaultTenantOnlyFillsAuthenticatedMissingTenant(final String source) { + PrincipalMcpSecurityProperties properties = policy(source); + Map claims = claims(); + claims.remove("tenant_id"); + assertNull(resolve(resolver(properties), authentication(source, claims))); + properties.setDefaultTenant("explicit-default"); + AgentMcpSecurityResolver resolver = resolver(properties); + assertEquals("explicit-default", resolve(resolver, authentication(source, claims)).getTenant().orElseThrow()); + assertNull(resolve(resolver, null)); + for (Object malformed : List.of("", " tenant", 42, "tenant" + (char) 10)) { + claims.put("tenant_id", malformed); + assertNull(resolve(resolver, authentication(source, claims))); + } + } + + @ParameterizedTest + @ValueSource(strings = {"jwt", "opaque-token", "oauth2-login"}) + void rejectsMalformedScopesAndClaims(final String source) { + AgentMcpSecurityResolver resolver = resolver(policy(source)); + for (Object malformed : List.of(42, "read write", "read" + (char) 9 + "write", List.of("read", 42), " read", "read\\write")) { + Map claims = claims(); + claims.put("scope", malformed); + assertNull(resolve(resolver, authentication(source, claims))); + } + for (Object malformed : List.of("read", List.of("*"), List.of("a".repeat(129)), List.of(42))) { + Map claims = claims(); + claims.put("tool_grants", malformed); + assertNull(resolve(resolver, authentication(source, claims))); + } + Map claims = claims(); + claims.put("scope", "read"); + claims.put("scp", List.of("write")); + assertNull(resolve(resolver, authentication(source, claims))); + claims.put("scp", List.of("read")); + assertEquals(Set.of("read"), resolve(resolver, authentication(source, claims)).getToolGrants()); + } + + @ParameterizedTest + @ValueSource(strings = {"jwt", "opaque-token"}) + void rejectsWrongIssuerAndAudience(final String source) { + AgentMcpSecurityResolver resolver = resolver(policy(source)); + Map claims = claims(); + claims.put("iss", "https://untrusted.example"); + assertNull(resolve(resolver, authentication(source, claims))); + claims = claims(); + claims.put("aud", List.of("other")); + assertNull(resolve(resolver, authentication(source, claims))); + } + + @Test + void rejectsConflictingLoginRegistrationAndJwtSubjectAlias() { + OAuth2AuthenticationToken login = (OAuth2AuthenticationToken) authentication("oauth2-login", claims()); + assertNull(resolve(resolver(policy("oauth2-login")), new OAuth2AuthenticationToken(login.getPrincipal(), login.getAuthorities(), "untrusted"))); + JwtAuthenticationToken jwt = (JwtAuthenticationToken) authentication("jwt", claims()); + assertNull(resolve(resolver(policy("jwt")), new JwtAuthenticationToken(jwt.getToken(), List.of(), "alias"))); + } + + @Test + void rejectsDuplicateOrMalformedMappingsAndCredentialSourceConflict() { + PrincipalMcpSecurityProperties policy = policy("jwt"); + policy.setScopeMappings(List.of(mapping("read"), mapping("read"))); + assertThrows(IllegalArgumentException.class, () -> resolver(policy)); + policy.setScopeMappings(List.of(mapping("read write"))); + assertThrows(IllegalArgumentException.class, () -> resolver(policy)); + policy.setScopeMappings(List.of()); + AgentMcpSecurityResolver resolver = new PrincipalMcpSecurityResolver<>(policy, JwtAuthenticationToken.class, + JwtAuthenticationToken::getTokenAttributes, authentication -> true, exchange -> Mono.just(true)); + assertNull(resolve(resolver, authentication("jwt", claims()))); + } + + @ParameterizedTest + @ValueSource(strings = {"jwt", "opaque-token", "oauth2-login"}) + void concurrentIdentitiesRemainTenantBound(final String source) { + AgentMcpSecurityResolver resolver = resolver(policy(source)); + List identities = Flux.range(0, 32).flatMap(index -> { + Map claims = claims(); + claims.put("tenant_id", "tenant-" + index); + return resolver.resolve(exchange(authentication(source, claims))).subscribeOn(Schedulers.parallel()); + }).collectList().block(); + assertEquals(32, identities.stream().map(identity -> identity.getTenant().orElseThrow()).distinct().count()); + } + + private static PrincipalMcpSecurityProperties policy(final String source) { + PrincipalMcpSecurityProperties properties = new PrincipalMcpSecurityProperties(); + properties.setEnabled(true); + properties.setSource(source); + if ("oauth2-login".equals(source)) { + properties.setRegistrationId("trusted"); + } else { + properties.setIssuer("https://issuer.example"); + properties.setAudience("mcp"); + } + return properties; + } + + private static PrincipalMcpSecurityProperties.ScopeMapping mapping(final String scope) { + PrincipalMcpSecurityProperties.ScopeMapping mapping = new PrincipalMcpSecurityProperties.ScopeMapping(); + mapping.setScope(scope); + mapping.setToolGrants(Set.of("read")); + return mapping; + } + + private static AgentMcpSecurityResolver resolver(final PrincipalMcpSecurityProperties properties) { + return switch (properties.getSource()) { + case "jwt" -> new AgentGatewayPluginConfiguration.JwtPrincipalConfiguration().agentGatewayPrincipalJwtResolver(properties); + case "opaque-token" -> new AgentGatewayPluginConfiguration.OpaquePrincipalConfiguration().agentGatewayPrincipalOpaqueResolver(properties); + case "oauth2-login" -> new AgentGatewayPluginConfiguration.LoginPrincipalConfiguration().agentGatewayPrincipalLoginResolver(properties); + default -> throw new IllegalArgumentException("Unknown fixture source"); + }; + } + + private static Map claims() { + Map claims = new HashMap<>(); + claims.put("sub", "service"); + claims.put("tenant_id", "tenant-a"); + claims.put("iss", "https://issuer.example"); + claims.put("aud", List.of("mcp")); + claims.put("tool_grants", List.of("read")); + return claims; + } + + private static Authentication authentication(final String source, final Map claims) { + List authorities = List.of(new SimpleGrantedAuthority("SCOPE_unmapped")); + return switch (source) { + case "jwt" -> new JwtAuthenticationToken(new Jwt("fixture-token", Instant.now(), Instant.now().plusSeconds(300), Map.of("alg", "HS256"), claims), authorities); + case "opaque-token" -> new BearerTokenAuthentication(new DefaultOAuth2AuthenticatedPrincipal(claims, authorities), + new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "fixture-token", Instant.now(), Instant.now().plusSeconds(300)), authorities); + case "oauth2-login" -> new OAuth2AuthenticationToken(new DefaultOAuth2User(authorities, claims, "sub"), authorities, "trusted"); + default -> throw new IllegalArgumentException("Unknown fixture source"); + }; + } + + private static AgentMcpIdentity resolve(final AgentMcpSecurityResolver resolver, final Authentication authentication) { + return resolver.resolve(exchange(authentication)).block(); + } + + private static org.springframework.web.server.ServerWebExchange exchange(final Authentication authentication) { + return MockServerWebExchange.from(MockServerHttpRequest.post("/mcp").header("X-Tenant-Id", "forged").header("tool_grants", "admin")) + .mutate().principal(Mono.justOrEmpty(authentication)).build(); + } +} From 19eea6ff995f848aba6d242c633a66b1b6df0425 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 19 Oct 2026 19:45:52 +0800 Subject: [PATCH 02/36] feat(agent-gateway): unify request context and terminal observation --- db/init/mysql/schema.sql | 6 +- db/init/oracle/schema.sql | 6 +- db/init/pg/create-table.sql | 6 +- db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql | 4 +- db/upgrade/2.7.1-upgrade-2.7.2-ob.sql | 4 +- db/upgrade/2.7.1-upgrade-2.7.2-og.sql | 4 +- db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql | 4 +- db/upgrade/2.7.1-upgrade-2.7.2-pg.sql | 4 +- db/upgrade/2.7.2-agent-gateway-order.sql | 34 ++ docs/agent-gateway-governance-order.md | 185 +++++++ docs/agent-gateway-request-context.md | 139 +++++ docs/agent-gateway-terminal-events.md | 36 ++ .../main/resources/sql-script/h2/schema.sql | 8 +- .../common/dto/AgentRequestContext.java | 133 +++++ .../shenyu/common/enums/PluginEnum.java | 2 +- .../common/metrics/AgentMcpTerminalEvent.java | 110 ++++ .../metrics/AgentMcpTerminalObserver.java | 34 ++ .../shenyu/common/metrics/AiAttemptEvent.java | 44 ++ .../shenyu/common/metrics/AiCallObserver.java | 39 ++ .../shenyu/common/metrics/AiCallOutcome.java | 25 + .../common/metrics/AiRequestObservation.java | 265 +++++++++ .../common/metrics/AiTerminalEvent.java | 33 ++ .../apache/shenyu/common/metrics/AiUsage.java | 39 ++ .../common/tracing/AgentTraceContext.java | 91 ++++ .../common/dto/AgentRequestContextTest.java | 58 ++ .../enums/AgentGatewayPluginOrderTest.java | 125 +++++ .../metrics/AiRequestObservationTest.java | 170 ++++++ .../agent/gateway/AgentGatewayPlugin.java | 48 +- .../agent/gateway/AgentTrafficContext.java | 6 + .../gateway/protocol/AgentMcpHttpHandler.java | 54 +- .../protocol/AgentMcpTerminalObservation.java | 130 +++++ .../remote/ManagedRemoteMcpCatalog.java | 5 +- .../remote/RequestScopedMcpClient.java | 7 +- .../agent/gateway/AgentGatewayPluginTest.java | 72 +++ .../AgentMcpTerminalObservationTest.java | 504 ++++++++++++++++++ .../remote/RequestScopedMcpClientTest.java | 130 ++++- .../shenyu-plugin-ai-proxy/pom.xml | 6 + .../ai/proxy/enhanced/AiProxyPlugin.java | 33 +- .../service/AiObservationSupport.java | 72 +++ .../proxy/enhanced/service/AiProxyEngine.java | 123 +++-- .../enhanced/service/AiUpstreamUsageTap.java | 202 +++++++ .../transport/AiOutboundTraceContext.java | 55 ++ .../transport/WebClientAiProxyTransport.java | 20 +- .../ai/proxy/enhanced/AiProxyPluginTest.java | 103 +++- .../AiProxyEngineOrchestrationTest.java | 3 +- .../service/AiProxyObservationTest.java | 243 +++++++++ .../service/AiUpstreamUsageTapTest.java | 150 ++++++ .../transport/AiOutboundTraceContextTest.java | 181 +++++++ .../UpstreamCircuitBreakerTest.java | 2 +- .../plugin/tracing/TraceContinuityTest.java | 11 +- .../pom.xml | 30 ++ .../AgentGatewayPluginConfiguration.java | 18 +- .../OpenTelemetryAgentMcpCallTracer.java | 15 +- .../AgentGatewayPluginConfigurationTest.java | 13 + .../gateway/AgentGovernanceHttpTest.java | 334 ++++++++++++ .../OpenTelemetryAgentMcpCallTracerTest.java | 64 ++- ...penTelemetryAgentMcpRemoteTracingTest.java | 358 +++++++++++++ .../ai/proxy/AiProxyPluginConfiguration.java | 21 +- .../proxy/AiProxyPluginConfigurationTest.java | 12 + .../AgentGatewayPluginOrderingTest.java | 190 +++++++ 60 files changed, 4733 insertions(+), 90 deletions(-) create mode 100644 db/upgrade/2.7.2-agent-gateway-order.sql create mode 100644 docs/agent-gateway-governance-order.md create mode 100644 docs/agent-gateway-request-context.md create mode 100644 docs/agent-gateway-terminal-events.md create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentRequestContext.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalEvent.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalObserver.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiAttemptEvent.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiCallObserver.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiCallOutcome.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiTerminalEvent.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiUsage.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/tracing/AgentTraceContext.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentRequestContextTest.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/enums/AgentGatewayPluginOrderTest.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/metrics/AiRequestObservationTest.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java create mode 100644 shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiObservationSupport.java create mode 100644 shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiUpstreamUsageTap.java create mode 100644 shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/AiOutboundTraceContext.java create mode 100644 shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyObservationTest.java create mode 100644 shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiUpstreamUsageTapTest.java create mode 100644 shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/AiOutboundTraceContextTest.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpRemoteTracingTest.java create mode 100644 shenyu-web/src/test/java/org/apache/shenyu/web/handler/AgentGatewayPluginOrderingTest.java diff --git a/db/init/mysql/schema.sql b/db/init/mysql/schema.sql index f6699a41fe1a..afdbb13b32c4 100644 --- a/db/init/mysql/schema.sql +++ b/db/init/mysql/schema.sql @@ -890,7 +890,7 @@ INSERT INTO `plugin` VALUES ('52', 'aiPrompt', null, 'Ai', 170, 0, '2023-12-20 1 INSERT INTO `plugin` VALUES ('53', 'aiRequestTransformer', NULL, 'Ai', 65, 0, '2023-12-20 18:02:53', '2023-12-20 18:02:53', null); INSERT INTO `plugin` VALUES ('61', 'mcpServer', null, 'MCP', 180, 0, '2023-12-20 18:02:53', '2023-12-20 18:02:53', null); -INSERT INTO `plugin` VALUES ('68', 'agentGateway', null, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); +INSERT INTO `plugin` VALUES ('68', 'agentGateway', null, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); INSERT INTO `plugin` VALUES ('66', 'aiResponseTransformer', NULL, 'Ai', 66, 0, '2023-12-20 18:02:53', '2023-12-20 18:02:53', null); -- ---------------------------- @@ -2263,11 +2263,11 @@ INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, ` INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822187','649330b6-c2d7-4edc-be8e-8a54df9eb385','50', '{\"provider\":\"OpenAI\",\"baseUrl\":\"https://api.openai.com/v1/chat/completions\",\"model\":\"gpt-4o-mini\",\"apiKey\":\"your_api_key\",\"temperature\":\"0.5\",\"maxTokens\":\"1000\",\"stream\":\"false\",\"proxyEnabled\":\"false\",\"fallbackEnabled\":\"false\",\"fallbackProvider\":\"OpenAI\",\"fallbackModel\":\"gpt-4.1\"}', 199, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822188','649330b6-c2d7-4edc-be8e-8a54df9eb385','51', NULL, 171, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); -INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822189','649330b6-c2d7-4edc-be8e-8a54df9eb385','52', NULL, 171, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); +INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822189','649330b6-c2d7-4edc-be8e-8a54df9eb385','52', NULL, 170, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822190','649330b6-c2d7-4edc-be8e-8a54df9eb385','53', NULL, 65, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882832189','649330b6-c2d7-4edc-be8e-8a54df9eb385','61', NULL, 180, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); -INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822300','649330b6-c2d7-4edc-be8e-8a54df9eb385','66', NULL, 66, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); diff --git a/db/init/oracle/schema.sql b/db/init/oracle/schema.sql index bb6338ea2c9a..2db3ea2f2f28 100644 --- a/db/init/oracle/schema.sql +++ b/db/init/oracle/schema.sql @@ -3082,7 +3082,7 @@ INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(shenyu_dict(id)) */ INTO shenyu_dict (id, VALUES ('1679002911061737583', 'postRole', 'ROLE_TYPE_USER', 'USER', 'user', 'user', 1, 1, to_timestamp('2024-02-07 14:31:49', 'YYYY-MM-DD HH24:MI:SS'), to_timestamp('2024-02-07 14:31:49', 'YYYY-MM-DD HH24:MI:SS')); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(namespace_plugin_rel(id)) */ INTO namespace_plugin_rel (id, namespace_id, plugin_id, config, sort, enabled, date_created, date_updated) -VALUES ('1801816010882822189', '649330b6-c2d7-4edc-be8e-8a54df9eb385', '52', NULL, 171, 0, to_timestamp('2022-05-25 18:02:53', 'YYYY-MM-DD HH24:MI:SS'), to_timestamp('2022-05-25 18:02:53', 'YYYY-MM-DD HH24:MI:SS')); +VALUES ('1801816010882822189', '649330b6-c2d7-4edc-be8e-8a54df9eb385', '52', NULL, 170, 0, to_timestamp('2022-05-25 18:02:53', 'YYYY-MM-DD HH24:MI:SS'), to_timestamp('2022-05-25 18:02:53', 'YYYY-MM-DD HH24:MI:SS')); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(resource(id)) */ INTO "resource" (id, parent_id, title, name, url, component, resource_type, sort, icon, is_leaf, is_route, perms, status) @@ -3327,9 +3327,9 @@ VALUES ('1722804548510507240', '53', 'provider', 'provider', 3, 3, 0, '{"require INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(plugin(id)) */ INTO plugin (id, name, config, role, sort, enabled, date_created, date_updated) VALUES ('61', 'mcpServer', NULL, 'MCP', 180, 0, sysdate, sysdate); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(plugin(id)) */ INTO plugin (id, name, config, role, sort, enabled, date_created, date_updated) -VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, sysdate, sysdate); +VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, sysdate, sysdate); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX (namespace_plugin_rel(id)) */ INTO namespace_plugin_rel (id,namespace_id,plugin_id, config, sort, enabled) -VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0); +VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(namespace_plugin_rel(id)) */ INTO namespace_plugin_rel (id, namespace_id, plugin_id, config, sort, enabled, date_created, date_updated) VALUES ('1801816010882832189', '649330b6-c2d7-4edc-be8e-8a54df9eb385', '61', NULL, 180, 0, sysdate, sysdate); diff --git a/db/init/pg/create-table.sql b/db/init/pg/create-table.sql index d772c42102ff..546de6f2c1cc 100644 --- a/db/init/pg/create-table.sql +++ b/db/init/pg/create-table.sql @@ -2748,7 +2748,7 @@ INSERT INTO "public"."shenyu_dict" VALUES ('1679002911061737581', 'preRole', 'RO INSERT INTO "public"."shenyu_dict" VALUES ('1679002911061737582', 'postRole', 'ROLE_TYPE_SYSTEM', 'SYSTEM', 'system', 'system', 0, 1, '2024-02-07 14:31:49', '2024-02-07 14:31:49'); INSERT INTO "public"."shenyu_dict" VALUES ('1679002911061737583', 'postRole', 'ROLE_TYPE_USER', 'USER', 'user', 'user', 1, 1, '2024-02-07 14:31:49', '2024-02-07 14:31:49'); -INSERT INTO "public"."namespace_plugin_rel" ("id","namespace_id","plugin_id", "config", "sort", "enabled", "date_created", "date_updated") VALUES ('1801816010882822189','649330b6-c2d7-4edc-be8e-8a54df9eb385','52', NULL, 171, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); +INSERT INTO "public"."namespace_plugin_rel" ("id","namespace_id","plugin_id", "config", "sort", "enabled", "date_created", "date_updated") VALUES ('1801816010882822189','649330b6-c2d7-4edc-be8e-8a54df9eb385','52', NULL, 170, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); INSERT INTO "public"."resource" VALUES ('1844026099075534859', '1346775491550474240', 'aiTokenLimiter', 'aiTokenLimiter', '/plug/aiTokenLimiter', 'aiTokenLimiter', 1, 0, 'pic-center', 0, 0, '', 1, '2022-05-25 18:02:58', '2022-05-25 18:02:58'); @@ -2818,8 +2818,8 @@ INSERT INTO "public"."permission" VALUES ('1697146860569742759', '13463585604272 INSERT INTO "public"."permission" VALUES ('1697146860569742760', '1346358560427216896', '1844026099075564868', '2023-08-31 07:18:37', '2023-08-31 07:18:37'); INSERT INTO "public"."plugin" VALUES ('61', 'mcpServer', NULL, 'MCP', 180, 0, '2023-12-20 18:02:53', '2023-12-20 18:02:53', NULL); -INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); -INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); +INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); INSERT INTO "public"."namespace_plugin_rel" VALUES ('1801816010882832189', '649330b6-c2d7-4edc-be8e-8a54df9eb385', '61', NULL, 180, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); INSERT INTO "public"."plugin_handle" VALUES ('1942847622591684608', '61', 'messageEndpoint', 'messageEndpoint', 2, 1, 0, '{"required":"0","defaultValue":"/message","rule":""}', '2025-07-09 07:25:44.249', '2025-07-09 07:25:44.249'); INSERT INTO "public"."plugin_handle" VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql b/db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql index 6c2771ce99ca..8d2247e7a443 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql @@ -59,7 +59,7 @@ ALTER TABLE `selector` ADD INDEX `idx_selector_plugin_id` (`plugin_id`) USING BT ALTER TABLE `permission` ADD INDEX `idx_permission_resource_id` (`resource_id`) USING BTREE; -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. -INSERT INTO `plugin` VALUES ('68', 'agentGateway', null, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); +INSERT INTO `plugin` VALUES ('68', 'agentGateway', null, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); INSERT INTO `plugin_handle` VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `plugin_handle` VALUES ('1960000000000001001', '68', 'responseRequestId', 'responseRequestId', 3, 2, 1, '{"required":"0","defaultValue":"false","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `resource` VALUES ('1960000000000001010', '1346775491550474240', 'agentGateway', 'agentGateway', '/plug/agentGateway', 'agentGateway', 1, 0, 'pic-center', 0, 0, '', 1, '2026-09-19 00:00:00', '2026-09-19 00:00:00'); @@ -82,7 +82,7 @@ INSERT INTO `permission` VALUES ('1960000000000001026', '1346358560427216896', ' INSERT INTO `permission` VALUES ('1960000000000001027', '1346358560427216896', '1960000000000001017', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `permission` VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `permission` VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); -INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); -- add index to speed up the meta data path uniqueness check ALTER TABLE `meta_data` ADD INDEX `idx_meta_data_namespace_path` (`namespace_id`, `path`) USING BTREE; diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-ob.sql b/db/upgrade/2.7.1-upgrade-2.7.2-ob.sql index 3f576e7f4489..ae2eafea7368 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-ob.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-ob.sql @@ -62,7 +62,7 @@ ALTER TABLE `resource` ADD INDEX `idx_resource_parent_id` (`parent_id`) USING BT ALTER TABLE `user_role` ADD INDEX `idx_user_role_user_id` (`user_id`) USING BTREE; -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. -INSERT INTO `plugin` VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); +INSERT INTO `plugin` VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); INSERT INTO `plugin_handle` VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `plugin_handle` VALUES ('1960000000000001001', '68', 'responseRequestId', 'responseRequestId', 3, 2, 1, '{"required":"0","defaultValue":"false","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `resource` VALUES ('1960000000000001010', '1346775491550474240', 'agentGateway', 'agentGateway', '/plug/agentGateway', 'agentGateway', 1, 0, 'pic-center', 0, 0, '', 1, '2026-09-19 00:00:00', '2026-09-19 00:00:00'); @@ -85,7 +85,7 @@ INSERT INTO `permission` VALUES ('1960000000000001026', '1346358560427216896', ' INSERT INTO `permission` VALUES ('1960000000000001027', '1346358560427216896', '1960000000000001017', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `permission` VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `permission` VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); -INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); -- add index to speed up the meta data path uniqueness check ALTER TABLE `meta_data` ADD INDEX `idx_meta_data_namespace_path` (`namespace_id`, `path`) USING BTREE; ALTER TABLE `operation_record_log` ADD INDEX `idx_operation_log_time` (`operation_time`) USING BTREE; diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-og.sql b/db/upgrade/2.7.1-upgrade-2.7.2-og.sql index b2afcdc7b6ee..c420e90725e2 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-og.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-og.sql @@ -62,7 +62,7 @@ CREATE INDEX IF NOT EXISTS "idx_resource_parent_id" ON "public"."resource" USING CREATE INDEX IF NOT EXISTS "idx_user_role_user_id" ON "public"."user_role" USING btree ("user_id"); -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. -INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); +INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); INSERT INTO "public"."plugin_handle" VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."plugin_handle" VALUES ('1960000000000001001', '68', 'responseRequestId', 'responseRequestId', 3, 2, 1, '{"required":"0","defaultValue":"false","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."resource" VALUES ('1960000000000001010', '1346775491550474240', 'agentGateway', 'agentGateway', '/plug/agentGateway', 'agentGateway', 1, 0, 'pic-center', 0, 0, '', 1, '2026-09-19 00:00:00', '2026-09-19 00:00:00'); @@ -85,7 +85,7 @@ INSERT INTO "public"."permission" VALUES ('1960000000000001026', '13463585604272 INSERT INTO "public"."permission" VALUES ('1960000000000001027', '1346358560427216896', '1960000000000001017', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."permission" VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."permission" VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); -INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); -- add index to speed up the meta data path uniqueness check CREATE INDEX "idx_meta_data_namespace_path" ON "public"."meta_data" USING btree ("namespace_id","path"); CREATE INDEX "idx_operation_log_time" ON "public"."operation_record_log" USING btree ("operation_time"); diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql b/db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql index 136dc1b497fc..99184645c35d 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql @@ -63,7 +63,7 @@ create index idx_user_role_user_id on user_role (user_id); -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(plugin(id)) */ INTO plugin (id, name, config, role, sort, enabled, date_created, date_updated) -VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, sysdate, sysdate); +VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, sysdate, sysdate); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(plugin_handle(id)) */ INTO plugin_handle (id, plugin_id, field, label, data_type, type, sort, ext_obj, date_created, date_updated) VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', sysdate, sysdate); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(plugin_handle(id)) */ INTO plugin_handle (id, plugin_id, field, label, data_type, type, sort, ext_obj, date_created, date_updated) @@ -99,7 +99,7 @@ INSERT INTO permission (id, object_id, resource_id, date_created, date_updated) INSERT INTO permission (id, object_id, resource_id, date_created, date_updated) VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', sysdate, sysdate); INSERT INTO permission (id, object_id, resource_id, date_created, date_updated) VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', sysdate, sysdate); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX (namespace_plugin_rel(id)) */ INTO namespace_plugin_rel (id,namespace_id,plugin_id, config, sort, enabled) -VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0); +VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0); -- add index to speed up the meta data path uniqueness check create index idx_meta_data_namespace_path on meta_data (namespace_id, path); create index idx_operation_log_time on operation_record_log (operation_time); diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-pg.sql b/db/upgrade/2.7.1-upgrade-2.7.2-pg.sql index 750b9085640d..8e9c4cf73cbd 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-pg.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-pg.sql @@ -62,7 +62,7 @@ CREATE INDEX IF NOT EXISTS "idx_resource_parent_id" ON "public"."resource" USING CREATE INDEX IF NOT EXISTS "idx_user_role_user_id" ON "public"."user_role" USING btree ("user_id"); -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. -INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); +INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); INSERT INTO "public"."plugin_handle" VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."plugin_handle" VALUES ('1960000000000001001', '68', 'responseRequestId', 'responseRequestId', 3, 2, 1, '{"required":"0","defaultValue":"false","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."resource" VALUES ('1960000000000001010', '1346775491550474240', 'agentGateway', 'agentGateway', '/plug/agentGateway', 'agentGateway', 1, 0, 'pic-center', 0, 0, '', 1, '2026-09-19 00:00:00', '2026-09-19 00:00:00'); @@ -85,7 +85,7 @@ INSERT INTO "public"."permission" VALUES ('1960000000000001026', '13463585604272 INSERT INTO "public"."permission" VALUES ('1960000000000001027', '1346358560427216896', '1960000000000001017', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."permission" VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."permission" VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); -INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); -- add index to speed up the meta data path uniqueness check CREATE INDEX "idx_meta_data_namespace_path" ON "public"."meta_data" USING btree ("namespace_id","path"); CREATE INDEX "idx_operation_log_time" ON "public"."operation_record_log" USING btree ("operation_time"); diff --git a/db/upgrade/2.7.2-agent-gateway-order.sql b/db/upgrade/2.7.2-agent-gateway-order.sql new file mode 100644 index 000000000000..8c53fafb4460 --- /dev/null +++ b/db/upgrade/2.7.2-agent-gateway-order.sql @@ -0,0 +1,34 @@ +-- 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. + +-- Explicit, repeatable migration for an EXISTING Agent Gateway installation. +-- Use the application's database/schema; these statements use common SQL. +-- Before running, follow docs/agent-gateway-governance-order.md: back up and +-- review BOTH plugin and namespace_plugin_rel rows, including disabled rows. +-- A custom value equal to the old default 198 cannot be distinguished by SQL. +-- If any 198 row was deliberately customized, do NOT run this whole script; +-- restrict each UPDATE to the explicitly approved row IDs instead. +-- No plugin is enabled, no credentials/configuration are changed, and values +-- other than 198 are preserved. Prompt/limiter/proxy sorts are NOT migrated. +-- Run both UPDATEs in one operator-managed transaction, verify, then commit. +-- Database writes alone do not refresh Admin/gateway caches: resynchronize +-- all affected namespaces before routing traffic through the updated gateway. + +UPDATE plugin SET sort = 169 WHERE name = 'agentGateway' AND sort = 198; + +UPDATE namespace_plugin_rel SET sort = 169 +WHERE sort = 198 + AND plugin_id IN (SELECT id FROM plugin WHERE name = 'agentGateway'); diff --git a/docs/agent-gateway-governance-order.md b/docs/agent-gateway-governance-order.md new file mode 100644 index 000000000000..e1532e4c0af5 --- /dev/null +++ b/docs/agent-gateway-governance-order.md @@ -0,0 +1,185 @@ + + +# Agent Gateway governance: execution order and upgrade + +## Single matched entry + +The default AI path is `authentication -> agentGateway -> aiPrompt -> aiTokenLimiter -> aiProxy`. +KeyAuth and BasicAuth default to 150, Agent Gateway to 169, Prompt to 170, +Token Limiter to 171 and AI Proxy to 199. JWT/OAuth2 remain earlier. +169 was unused in PluginEnum before this change; 170 is already used by both +Prompt and RocketMQ logging. No other plugin enum or sorting algorithm changes. + +Agent Gateway keeps its existing selector/rule matching and is the only AG entry. +A matched LLM request establishes its context before continuing through the +existing AI chain. AG must not read, buffer or subscribe to the LLM request body; +body consumption remains with the existing AI plugins. A matched MCP request +terminates in AG and does not enter Prompt, the LLM Token Limiter or AI Proxy. +Unmatched/disabled AG continues the original chain. Moving the terminal entry +earlier also bypasses later plugins for matched MCP, including RocketMQ logging +and sensitiveWord. Do not assume those plugins still observe or filter MCP; +review any deployment relying on their old position. Authentication plugins +must still be enabled and match the intended paths; order alone is not authentication. + +## Effective order is configuration, not only the enum + +`ShenyuWebHandler.sortPlugins` uses cached `PluginData.sort`, falling back to +`getOrder()` only when no cached sort exists. Its constructor retains the supplied +list; sort/enable events perform the runtime sort. The namespace mapper selects +`namespace_plugin_rel.sort` for synchronized configuration. New namespace plugin +relations inherit plugin defaults via `NamespacePluginRelDO`. Therefore changing +only PluginEnum or only the global plugin row does not repair an existing deployment. + +Custom values remain authoritative, even if they put AG after the limiter or +before authentication. Equal sort values do not establish a safe relative order. +This change neither forbids custom ordering nor claims to correct arbitrary +custom mistakes, missing plugins or stale gateway caches. The required invariant +for each enabled LLM path is strictly: + +`authentication < agentGateway < aiPrompt < aiTokenLimiter < aiProxy` + +If Prompt is absent/disabled, use `authentication < agentGateway < aiTokenLimiter < aiProxy`. +Also check extension plugins for a local collision at 169. + +## Default SQL changes + +- MySQL/OceanBase: `db/init/mysql/schema.sql`. +- PostgreSQL/openGauss: `db/init/pg/create-table.sql`. +- Oracle: `db/init/oracle/schema.sql`. +- H2: `shenyu-admin/src/main/resources/sql-script/h2/schema.sql`. +- Agent Gateway seeds in all five `db/upgrade/2.7.1-upgrade-2.7.2-*.sql` dialects. + +Both `plugin` and the default `namespace_plugin_rel` AG values are 169. Fresh-install +namespace Prompt values previously set to 171 are aligned to 170; H2 global Proxy +171 and namespace Proxy 200 are aligned to 199. These are seed corrections, not +instructions to overwrite existing custom values. Older 2.7.0 -> 2.7.1 scripts +remain historical; upgrading through them still requires the inspection below. + +## Existing installations: inspect before migration + +Do not rerun destructive initialization scripts or the full insert-based version +upgrade on a database that already contains AG. H2 `INSERT IGNORE` also does not +update existing rows. Use the configured database/schema and back up these rows +before changing anything. The following queries intentionally omit credentials: + +```sql +SELECT id, name, sort, enabled +FROM plugin +WHERE name IN ('jwt', 'oauth2', 'keyAuth', 'basicAuth', + 'agentGateway', 'aiPrompt', 'aiTokenLimiter', 'aiProxy') + OR sort = 169 +ORDER BY sort, name; + +SELECT n.id, n.namespace_id, p.name, p.sort AS plugin_sort, + n.sort AS namespace_sort, n.enabled +FROM namespace_plugin_rel n JOIN plugin p ON p.id = n.plugin_id +WHERE p.name IN ('jwt', 'oauth2', 'keyAuth', 'basicAuth', + 'agentGateway', 'aiPrompt', 'aiTokenLimiter', 'aiProxy') + OR n.sort = 169 +ORDER BY n.namespace_id, n.sort, p.name; + +-- All AG migration candidates, including disabled namespace relations. +SELECT n.id, n.namespace_id, n.sort, n.enabled +FROM namespace_plugin_rel n JOIN plugin p ON p.id = n.plugin_id +WHERE p.name = 'agentGateway' AND n.sort = 198 +ORDER BY n.namespace_id; + +-- Enabled adjacent AI plugins that violate the required strict order. +SELECT a.namespace_id, pa.name AS earlier_plugin, a.sort AS earlier_sort, + pb.name AS later_plugin, b.sort AS later_sort +FROM namespace_plugin_rel a +JOIN plugin pa ON pa.id = a.plugin_id +JOIN namespace_plugin_rel b ON b.namespace_id = a.namespace_id +JOIN plugin pb ON pb.id = b.plugin_id +WHERE a.enabled = 1 AND b.enabled = 1 AND a.sort >= b.sort + AND ((pa.name IN ('jwt', 'oauth2', 'keyAuth', 'basicAuth') AND pb.name = 'agentGateway') + OR (pa.name = 'agentGateway' AND pb.name IN ('aiPrompt', 'aiTokenLimiter', 'aiProxy')) + OR (pa.name = 'aiPrompt' AND pb.name = 'aiTokenLimiter') + OR (pa.name = 'aiTokenLimiter' AND pb.name = 'aiProxy')); +``` + +An empty last query is not proof of a valid complete deployment: missing/disabled +plugins, selector matching and unsynchronized caches require separate inspection. + +## Explicit upgrade procedure + +1. Drain affected traffic and coordinate Admin writers and the gateway rollout. + Record the global row and every affected namespace row's old sort; review + custom extension plugins and the checks above. +2. Confirm that each AG value of 198 is the old default. SQL cannot distinguish + an intentional custom 198 from the default. If any such row is custom, do not + run the broad script: restrict each UPDATE to explicitly approved row IDs. + Other custom values, including invalid ones, are left untouched. +3. For approved default-only deployments, run + `db/upgrade/2.7.2-agent-gateway-order.sql` in one client-managed transaction. + It updates only AG rows with `sort = 198` to 169, globally and in all namespaces, + and is repeatable. It does not change enabled/config fields or other plugins. + MySQL/OceanBase use `START TRANSACTION`; PostgreSQL/openGauss use `BEGIN`; + disable autocommit for H2/Oracle as appropriate. Inspect affected counts before + committing; roll back if they differ from the reviewed candidate list. +4. Inspect legacy Prompt/Proxy drift separately. For each reviewed row, use the + Admin namespace plugin editor to set Prompt 170 or Proxy 199, or an explicit + row-ID-and-old-sort-guarded UPDATE. Never blanket-normalize custom orders. + For example, after replacing the placeholder with an approved ID: + + ```sql + UPDATE namespace_plugin_rel SET sort = 170 + WHERE id = '' AND sort = 171; + UPDATE namespace_plugin_rel SET sort = 199 + WHERE id = '' AND sort = 200; + UPDATE plugin SET sort = 199 + WHERE id = '' AND name = 'aiProxy' AND sort = 171; + ``` + + The older version-upgrade Proxy default may be 200 globally too; review and + guard against that actual old value if applicable. Do not run placeholders. +5. Direct SQL does not publish configuration-change events. Reload/restart Admin + as required, then use its supported namespace synchronization operation for + every affected namespace and ensure gateway cache refresh/sort events complete. + Do not assume an updated database means an updated running chain. +6. Verify effective order on every gateway before restoring traffic: a matched + LLM request follows AG -> Prompt -> Limiter -> Proxy, a limiter rejection sees + the established AG context, and matched MCP never reaches the LLM chain. + Verify unmatched/disabled AG retains existing behavior. +7. To roll back, drain traffic again and restore only the recorded row IDs/old + values, then resynchronize. Do not globally replace all 169 values with 198. + +## Regression scope and handoff + +`AgentGatewayPluginOrderTest` checks the enum's relative order/slot uniqueness, +AG plugin/namespace seeds in nine scripts, the full fresh-install AI chain in +four schemas, and the explicit default-only migration statement contract. +`AgentGatewayPluginOrderingTest` exercises the real handler/cache sorting path +with lightweight recording plugins: defaults, cached defaults, old 198 values, +unsafe custom values, dynamic sort events/cache removal, LLM continuation, terminal +AG and disabled AG. Assertions use plugin names/relative order, not a hardcoded +170 AG value. These are ordering tests, not proof of real MCP/LLM body handling. + +Mainline owns Maven execution; this change must not launch a concurrent Maven run. +The focused command for that owner (from the repository root) is: + +```powershell +.\mvnw.cmd -B -pl shenyu-web -am test '-Dtest=AgentGatewayPluginOrderTest,PluginEnumTest,AgentGatewayPluginOrderingTest,ShenyuWebHandlerTest' -Dsurefire.failIfNoSpecifiedTests=false -DskipRemoteResources=true -Dmaven.javadoc.skip=true +``` + +The reported common Checkstyle null-comparison violation was replaced with +`Objects.nonNull`. Java test success must be recorded from the mainline run, not +inferred from source checks. Native multi-database execution and end-to-end Admin +synchronization are not established by the seed-pattern or handler unit tests. +No AG/context/AI/Starter production implementation, main progress document, +generic sorting algorithm or other plugin enum is changed by this order slice. diff --git a/docs/agent-gateway-request-context.md b/docs/agent-gateway-request-context.md new file mode 100644 index 000000000000..f5da650d6dc5 --- /dev/null +++ b/docs/agent-gateway-request-context.md @@ -0,0 +1,139 @@ + + +# Agent Gateway request context and terminal facts + +## Governance entry + +The matched Agent Gateway rule creates a fresh request identifier at subscription time. +The default order is authentication (key-auth 150), Agent Gateway 169, AI Prompt 170, +AI Token Limiter 171, and AI Proxy 199. MCP terminates at Agent Gateway and does not +enter the LLM limiter/proxy. LLM continues through the existing AI plugins. No second +selector/rule matcher, request-body subscription, or request-body cache is introduced. + +Admin's persisted plugin and namespace-plugin order overrides the Java default. +Apply the documented default-order migration and check custom orders before enabling +governance; an incorrect custom order is not automatically corrected. See +[order and upgrade contract](agent-gateway-governance-order.md). + +## Trusted immutable context + +`AgentRequestContext` is shared from `shenyu-common` in Reactor Context under +`AgentRequestContext.REACTOR_KEY`. It carries server-generated request identity, +matched selector/rule, a node-local rule generation, trusted tenant/subject when +resolved, and the target/operation/version when actually known. New facts produce +new immutable snapshots; cancellation and concurrent requests never share a global +request map or a thread-local context. Existing `AgentTrafficContext` remains for +compatibility and uses the same request identifier. + +The rule generation is **not** an Admin revision or an authorization-policy version. +No policy revision is fabricated where an existing identity adapter supplies none. +MCP records only its validated inbound protocol version. The AI protocol identifier +is reported separately on attempts and is not a fabricated protocol version. +The stateless inbound endpoint has no session: its session is always unknown. A +remote transport session, client RPC id, trace id, or arbitrary header is not substituted. + +MCP continues to require the existing authoritative security resolver. Its final +authorization remains the intersection of rule tools and effective grants, with +denials already removed by the adapter. Context is not an authorization token. + +LLM identity adaptation is explicitly opt-in: + +```yaml +shenyu: + plugins: + agent: + gateway: + enabled: true + security: + llm: + enabled: true +``` + +This requires exactly one configured `AgentMcpSecurityResolver`, reusing the +existing verified JWT, OAuth principal, API-key binding, or application adapter. +An empty resolution returns 401 before reading the LLM body; a resolver failure +does not silently turn into anonymous access. With the setting disabled, existing +LLM behavior is preserved and tenant/subject remain unknown. Tool grants are not +interpreted as permission to use a model. Existing LLM access and limiter policy +remain responsible for their own admission decisions. + +Authentication plugins that reject **before** Agent Gateway remain outside its +terminal-event scope. This is not an audit of every HTTP request to the gateway. + +## One logical terminal, separate attempts + +Applications may provide one `AgentMcpTerminalObserver` and one `AiCallObserver`. +The matched LLM entry owns `AiRequestObservation` across downstream limiter, proxy, +retry/fallback, response writes and cancellation. AI Proxy and its engine reuse that +owner rather than emitting additional logical terminals. When used without Agent +Gateway, AI Proxy/engine create their own anonymous correlation and own termination. + +MCP snapshots cover matched preflight, identity, parsing, authorization, tool outcome, +timeout, cancellation and write failure. A requested tool does not prove it was +authorized or executed. AI has one event per actual upstream attempt, and one +logical event after the owned chain terminates. A limiter denial has zero attempts. +Cancellation is not success; assigned HTTP status does not prove response delivery. +No event contains request/response text, tool arguments, credentials or exception messages. + +Observer exceptions are isolated from business behavior. Observers must be nonblocking +and use bounded application-owned queues; durable logging, queue policy and audit +storage belong to the later audit feature, not this callback contract. + +## Usage is an observation, not a charge + +The existing AI engine reads each upstream body once. A bounded passive tap observes +raw JSON/SSE before provider adaptation and protocol conversion; it does not subscribe +again, change bytes, or alter retry/fallback policy. Only explicit upstream +`prompt_tokens`, `completion_tokens`, and `total_tokens` are observed. Missing counts +are null, not zero; totals are not calculated. Multiple cumulative SSE usage objects +replace the prior snapshot rather than being added. Invalid, unsupported and +oversized observations are distinguishable from reported usage. + +The logical terminal carries the **last started attempt's** usage and attempt count, +not a fabricated aggregate across retries. Attempt events preserve each attempt's +own observation. These snapshots do not establish billing correctness or settle a +budget. Existing Redis Token Limiter charging behavior is deliberately unchanged. +Provider-specific cached/reasoning tokens, prices, multi-attempt cost aggregation, +and budget settlement remain separate P1 work. + +## Trace propagation + +The optional application-owned MCP tracing bridge reads the gateway's explicit +`TracingConstants.REACTOR_CONTEXT_KEY` parent first, retaining `Context.class` +compatibility. The gateway SERVER span is the parent of the MCP logical-call span. +Only the locally encoded W3C `traceparent`/`tracestate` are passed through the +request-scoped JDK MCP client for `tools/call`. Shared initialization, initialized +notification and catalog discovery are not attributed to the first Agent request. + +AI WebClient transport similarly uses the explicit gateway Reactor tracing parent. +It does not create another SDK, exporter or ambient thread-local scope. Baggage, +client credentials and tenant/subject headers are not copied to the upstream. +Outbound service credentials retain their existing target-owned resolution. +Trace identities are telemetry and never authorization evidence. + +## Acceptance boundary + +Regression coverage includes real loopback HTTP authentication-to-limiter-to-AI +JSON/SSE traffic, single request-body subscription, early denial, actual sorted +plugin cache order, tenant isolation, gateway-to-MCP parentage, real remote MCP +outbound headers, shared-handshake isolation, concurrent/cancelled requests, usage +fragments, retries/fallback and terminal de-duplication. Windows and RISC-V/QEMU +must run the final identical source snapshot before local acceptance. Broader +Admin/WebSocket/Bootstrap, selected external Agents, Java-agent permutations and +distributed failure matrices are tracked separately in P0-04, not implied by unit +or loopback results. diff --git a/docs/agent-gateway-terminal-events.md b/docs/agent-gateway-terminal-events.md new file mode 100644 index 000000000000..f910d7d1bd16 --- /dev/null +++ b/docs/agent-gateway-terminal-events.md @@ -0,0 +1,36 @@ +# Agent Gateway MCP terminal events + +This document describes the MCP terminal-event part of P0-03. The integrated +AI/MCP context, governance and tracing contract is documented in +[request context and terminal facts](agent-gateway-request-context.md). + +An optional application-owned AgentMcpTerminalObserver receives one immutable +event per subscription after execution and response writing terminate, including +recovery, preflight/authentication rejection and downstream cancellation. +Authentication failures do not consume the body for observability. + +Events carry gateway request/rule/selector references, node-local configuration +generation, tenant and subject only after trusted resolution, validated operation/requested +tool and protocol version when available, outcome, monotonic handler duration +and assigned HTTP status. Requested tool does not mean authorized or executed; +assigned status does not prove response delivery, especially on cancellation. +No body, arguments, credentials, RPC ID, invented session or fabricated usage is +retained. Identifiers must not become unrestricted metric labels. Observers must +be nonblocking and bound their queues. Callback failures cannot affect responses, +metrics or tracing. No observer means no event sink is installed. + +Existing tools/call metrics retain their authenticated-and-parsed scope and timing. +The event covers all matched MCP requests and includes authentication duration; +do not count it into the same counter as the existing metrics callback. + +The integrated implementation carries trusted identity from the configured resolver, +enters governance at order 169 before AI Prompt (170), Token Limiter (171) and +AI Proxy (199), and connects the gateway SERVER span to the MCP logical-call span. +MCP tools/call and AI outbound tracing use request-local W3C context without +forwarding identity or baggage. AI usage is observed from the existing response +subscription, with separate attempt events and one logical terminal. + +Node-local configuration generation is not an authorization-policy revision. No +revision is invented when the identity source provides none. Trace IDs are not +identity; missing usage is unknown, not zero. Deployment-wide verification beyond +the feature's loopback integration regressions belongs to P0-04. diff --git a/shenyu-admin/src/main/resources/sql-script/h2/schema.sql b/shenyu-admin/src/main/resources/sql-script/h2/schema.sql index 77a6941a53bc..d8be74cc4e85 100644 --- a/shenyu-admin/src/main/resources/sql-script/h2/schema.sql +++ b/shenyu-admin/src/main/resources/sql-script/h2/schema.sql @@ -592,7 +592,7 @@ INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `enabled`) VALUES ('4 INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `enabled`) VALUES ('42','tcp','Proxy', 320, '1'); INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `config`, `enabled`) VALUES ('44', 'basicAuth', 'Authentication', 150, '{"defaultHandleJson":"{\"authorization\":\"test:test123\"}"}', '0'); -INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `config`, `enabled`) VALUES ('50', 'aiProxy', 'Ai', 171, '{"provider":"OpenAI","baseUrl":"https://api.openai.com/v1/chat/completions","model":"gpt-4o-mini","apiKey":"your_api_key","temperature":"0.5","maxTokens":"1000","stream":"false","proxyEnabled":"false","fallbackEnabled":"false","fallbackProvider":"OpenAI","fallbackModel":"gpt-4.1","prompt":""}', '0'); +INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `config`, `enabled`) VALUES ('50', 'aiProxy', 'Ai', 199, '{"provider":"OpenAI","baseUrl":"https://api.openai.com/v1/chat/completions","model":"gpt-4o-mini","apiKey":"your_api_key","temperature":"0.5","maxTokens":"1000","stream":"false","proxyEnabled":"false","fallbackEnabled":"false","fallbackProvider":"OpenAI","fallbackModel":"gpt-4.1","prompt":""}', '0'); INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `config`, `enabled`) VALUES ('52', 'aiPrompt', 'Ai', 170, null, '0'); @@ -601,7 +601,7 @@ INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `config`, `enabled`) INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `config`, `enabled`) VALUES ('53', 'aiRequestTransformer', 'Ai', 65, null, '0'); INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `config`, `enabled`) VALUES ('61', 'mcpServer', 'MCP', 180, null, '0'); -INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `config`, `enabled`) VALUES ('68', 'agentGateway', 'Ai', 198, null, '0'); +INSERT IGNORE INTO `plugin` (`id`, `name`, `role`, `sort`, `config`, `enabled`) VALUES ('68', 'agentGateway', 'Ai', 169, null, '0'); /*insert plugin_handle data for sentinel*/ INSERT IGNORE INTO plugin_handle (`id`, `plugin_id`,`field`,`label`,`data_type`,`type`,`sort`,`ext_obj`) VALUES ('1529402613195784246', '10', 'flowRuleGrade', 'flowRuleGrade', 3, 2, 8, '{"required":"1","defaultValue":"1","rule":""}'); @@ -1314,7 +1314,7 @@ INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `con INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822181','649330b6-c2d7-4edc-be8e-8a54df9eb385','44', '{"defaultHandleJson":"{\"authorization\":\"test:test123\"}"}', 150, 0, '2022-07-24 19:00:00.000', '2022-07-24 19:00:00.000'); INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822183','649330b6-c2d7-4edc-be8e-8a54df9eb385','5', '{"multiSelectorHandle":"1","multiRuleHandle":"0"}', 200, 1, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822184','649330b6-c2d7-4edc-be8e-8a54df9eb385','6', '{"register":"zookeeper://localhost:2181","multiSelectorHandle":"1","threadpool":"shared","corethreads":0,"threads":2147483647,"queues":0}', 310, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); -INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822187','649330b6-c2d7-4edc-be8e-8a54df9eb385','50', '{"provider":"OpenAI","baseUrl":"https://api.openai.com/v1/chat/completions","model":"gpt-4o-mini","apiKey":"your_api_key","temperature":"0.5","maxTokens":"1000","stream":"false","prompt":""}', 200, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); +INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822187','649330b6-c2d7-4edc-be8e-8a54df9eb385','50', '{"provider":"OpenAI","baseUrl":"https://api.openai.com/v1/chat/completions","model":"gpt-4o-mini","apiKey":"your_api_key","temperature":"0.5","maxTokens":"1000","stream":"false","prompt":""}', 199, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822188','649330b6-c2d7-4edc-be8e-8a54df9eb385','51', NULL, 171, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1801816010882822189','649330b6-c2d7-4edc-be8e-8a54df9eb385','52', NULL, 170, 0, '2022-05-25 18:02:53.000', '2022-05-25 18:02:53.000'); @@ -1323,7 +1323,7 @@ INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `con INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1907261515594055680','649330b6-c2d7-4edc-be8e-8a54df9eb385','61', NULL, 180, 0, '2025-04-02 10:39:15.000', '2025-04-02 10:39:15.000'); -INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT IGNORE INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentRequestContext.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentRequestContext.java new file mode 100644 index 000000000000..fbf3b8d85c0f --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentRequestContext.java @@ -0,0 +1,133 @@ +/* + * 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.dto; + +import java.util.Objects; + +/** + * Immutable subscription-local correlation snapshot shared by AI and MCP. + * Identity must come from the configured authentication adapter, never wire metadata. + * Nullable facts are unknown; neither an RPC id nor a trace id is an identity or session. + * This is diagnostic context, not an authorization grant or a set of metric labels. + */ +public final class AgentRequestContext { + + public static final String REACTOR_KEY = AgentRequestContext.class.getName(); + + public static final String EXCHANGE_ATTRIBUTE = REACTOR_KEY; + + private final String requestId; + + private final String trafficType; + + private final String selectorId; + + private final String ruleId; + + private final Long configurationVersion; + + private final String tenant; + + private final String subject; + + private final String target; + + private final String operation; + + private final String protocolVersion; + + private final String sessionId; + + public AgentRequestContext(final String requestId, final String trafficType, final String selectorId, final String ruleId) { + this(requestId, trafficType, selectorId, ruleId, null, null, null, null, null, null, null); + } + + public AgentRequestContext(final String requestId, final String trafficType, final String selectorId, final String ruleId, + final Long configurationVersion, final String tenant, final String subject, final String target, + final String operation, final String protocolVersion, final String sessionId) { + this.requestId = Objects.requireNonNull(requestId, "requestId"); + this.trafficType = Objects.requireNonNull(trafficType, "trafficType"); + this.selectorId = selectorId; + this.ruleId = ruleId; + this.configurationVersion = configurationVersion; + this.tenant = tenant; + this.subject = subject; + this.target = target; + this.operation = operation; + this.protocolVersion = protocolVersion; + this.sessionId = sessionId; + } + + public AgentRequestContext withIdentity(final String trustedTenant, final String trustedSubject) { + return new AgentRequestContext(requestId, trafficType, selectorId, ruleId, configurationVersion, trustedTenant, trustedSubject, + target, operation, protocolVersion, sessionId); + } + + public AgentRequestContext withTarget(final String resolvedTarget, final String resolvedOperation, final String resolvedProtocolVersion) { + return new AgentRequestContext(requestId, trafficType, selectorId, ruleId, configurationVersion, tenant, subject, + resolvedTarget, resolvedOperation, resolvedProtocolVersion, sessionId); + } + + public AgentRequestContext withConfigurationVersion(final long version) { + return new AgentRequestContext(requestId, trafficType, selectorId, ruleId, version, tenant, subject, target, operation, protocolVersion, sessionId); + } + + public String getRequestId() { + return requestId; + } + + public String getTrafficType() { + return trafficType; + } + + public String getSelectorId() { + return selectorId; + } + + public String getRuleId() { + return ruleId; + } + + public Long getConfigurationVersion() { + return configurationVersion; + } + + public String getTenant() { + return tenant; + } + + public String getSubject() { + return subject; + } + + public String getTarget() { + return target; + } + + public String getOperation() { + return operation; + } + + public String getProtocolVersion() { + return protocolVersion; + } + + public String getSessionId() { + return sessionId; + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/enums/PluginEnum.java b/shenyu-common/src/main/java/org/apache/shenyu/common/enums/PluginEnum.java index 360d59c1276b..06ff63d71a0e 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/enums/PluginEnum.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/enums/PluginEnum.java @@ -296,7 +296,7 @@ public enum PluginEnum { /** * Agent gateway plugin enum. */ - AGENT_GATEWAY(198, 0, "agentGateway"), + AGENT_GATEWAY(169, 0, "agentGateway"), /** * Ai-token-limiter plugin enum. diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalEvent.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalEvent.java new file mode 100644 index 000000000000..083d2e052c7b --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalEvent.java @@ -0,0 +1,110 @@ +/* + * 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.metrics; + +import org.apache.shenyu.common.dto.AgentRequestContext; + +import java.util.Objects; + +/** + * Immutable terminal snapshot for one matched MCP request subscription. + * Nullable metadata was unavailable or unvalidated, not inferred from headers. + * Requested tools do not prove authorization or execution; assigned HTTP status + * does not prove delivery. Identifiers must not become unbounded metric labels. + */ +public final class AgentMcpTerminalEvent { + + private final AgentRequestContext context; + + private final AgentMcpCallObserver.Outcome outcome; + + private final long elapsedMillis; + + private final Integer httpStatus; + + public AgentMcpTerminalEvent(final String requestId, final String selectorId, final String ruleId, final long configurationVersion, + final String subject, final String method, final String requestedTool, final String protocolVersion, + final AgentMcpCallObserver.Outcome outcome, final long elapsedMillis, final Integer httpStatus) { + this(new AgentRequestContext(requestId, "mcp", selectorId, ruleId, configurationVersion, null, subject, requestedTool, method, protocolVersion, null), + outcome, elapsedMillis, httpStatus); + } + + public AgentMcpTerminalEvent(final AgentRequestContext context, final AgentMcpCallObserver.Outcome outcome, final long elapsedMillis, final Integer httpStatus) { + this.context = Objects.requireNonNull(context, "context"); + Objects.requireNonNull(context.getConfigurationVersion(), "configurationVersion"); + this.outcome = outcome; + this.elapsedMillis = elapsedMillis; + this.httpStatus = httpStatus; + } + + public AgentRequestContext getContext() { + return context; + } + + public String getTenant() { + return context.getTenant(); + } + + public String getSessionId() { + return context.getSessionId(); + } + + public String getRequestId() { + return context.getRequestId(); + } + + public String getSelectorId() { + return context.getSelectorId(); + } + + public String getRuleId() { + return context.getRuleId(); + } + + public long getConfigurationVersion() { + return context.getConfigurationVersion(); + } + + public String getSubject() { + return context.getSubject(); + } + + public String getMethod() { + return context.getOperation(); + } + + public String getRequestedTool() { + return context.getTarget(); + } + + public String getProtocolVersion() { + return context.getProtocolVersion(); + } + + public AgentMcpCallObserver.Outcome getOutcome() { + return outcome; + } + + public long getElapsedMillis() { + return elapsedMillis; + } + + public Integer getHttpStatus() { + return httpStatus; + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalObserver.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalObserver.java new file mode 100644 index 000000000000..80cafe67cd9e --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalObserver.java @@ -0,0 +1,34 @@ +/* + * 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.metrics; + +/** + * Optional application-owned sink for matched MCP request terminal events. + * Implementations must be nonblocking and bound any queues and retention. + * This covers authentication and parsing failures as well as validated calls; + * do not count these events into the parsed tools/call metrics counter. + */ +@FunctionalInterface +public interface AgentMcpTerminalObserver { + + /** + * Record once after execution, recovery and response writing terminate. + * @param event immutable, body-free per-subscription snapshot + */ + void record(AgentMcpTerminalEvent event); +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiAttemptEvent.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiAttemptEvent.java new file mode 100644 index 000000000000..f204869f2130 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiAttemptEvent.java @@ -0,0 +1,44 @@ +/* + * 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.metrics; + +import org.apache.shenyu.common.dto.AgentRequestContext; + +/** + * Body-free terminal fact for one upstream attempt. Status is assigned, not proof of delivery. + * @param context immutable trusted request snapshot + * @param attemptNumber one-based sequence within a logical request + * @param kind primary, retry or fallback + * @param provider selected provider identifier + * @param protocol selected client protocol + * @param streaming selected response mode + * @param outcome terminal classification + * @param httpStatus received upstream status, null before headers + * @param elapsedMillis monotonic attempt duration + * @param usage last explicit usage snapshot for this attempt + */ +public record AiAttemptEvent(AgentRequestContext context, int attemptNumber, Kind kind, String provider, String protocol, boolean streaming, + AiCallOutcome outcome, Integer httpStatus, long elapsedMillis, AiUsage usage) { + + /** + * How this actual network attempt was selected. + */ + public enum Kind { + PRIMARY, RETRY, FALLBACK + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiCallObserver.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiCallObserver.java new file mode 100644 index 000000000000..fdfd8ee240ef --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiCallObserver.java @@ -0,0 +1,39 @@ +/* + * 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.metrics; + +/** + * Optional application-owned, nonblocking sink. Implementations must bound queues + * and must not use request identities as unrestricted metric labels. + */ +@FunctionalInterface +public interface AiCallObserver { + + /** + * Receive the single logical request terminal snapshot. + * @param event immutable snapshot without payloads or credentials + */ + void record(AiTerminalEvent event); + + /** + * Receive one snapshot for each actually started upstream attempt. + * @param event immutable attempt snapshot, not another logical request + */ + default void recordAttempt(final AiAttemptEvent event) { + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiCallOutcome.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiCallOutcome.java new file mode 100644 index 000000000000..75b5d3c407c9 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiCallOutcome.java @@ -0,0 +1,25 @@ +/* + * 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.metrics; + +/** + * Bounded outcomes, independent of any AI implementation or exception message. + */ +public enum AiCallOutcome { + SUCCESS, REJECTED, RATE_LIMITED, TIMEOUT, CANCELLED, ERROR +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java new file mode 100644 index 000000000000..f9954343969f --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java @@ -0,0 +1,265 @@ +/* + * 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.metrics; + +import org.apache.shenyu.common.dto.AgentRequestContext; +import reactor.core.publisher.SignalType; + +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * Subscription-local owner shared by the gateway, limiter boundary and AI proxy. + * Only the component that creates the state finishes the logical request. State + * retains no throwable, response body, credentials or unbounded attempt list. + */ +public final class AiRequestObservation { + + public static final String REACTOR_KEY = AiRequestObservation.class.getName(); + + private final AiCallObserver observer; + + private final long started = System.nanoTime(); + + private AgentRequestContext context; + + private Attempt active; + + private int attempts; + + private AiUsage usage = AiUsage.UNKNOWN; + + private AiCallOutcome failure; + + private boolean completed; + + public AiRequestObservation(final AiCallObserver observer, final AgentRequestContext context) { + this.observer = observer; + this.context = Objects.requireNonNull(context, "context"); + } + + public synchronized AgentRequestContext getContext() { + return context; + } + + /** + * Replace immutable facts only within the same logical request. + * @param value trusted snapshot, never client headers + */ + public synchronized void updateContext(final AgentRequestContext value) { + if (!completed && context.getRequestId().equals(value.getRequestId())) { + context = value; + } + } + + /** + * Classify without retaining the exception or its potentially sensitive message. + * @param error terminal execution or response-write failure + */ + public synchronized void error(final Throwable error) { + if (!completed) { + Throwable cause = error; + failure = AiCallOutcome.ERROR; + for (int depth = 0; depth < 16 && Objects.nonNull(cause); depth++) { + if (cause instanceof TimeoutException) { + failure = AiCallOutcome.TIMEOUT; + break; + } + cause = cause.getCause(); + } + } + } + + /** + * Supply a layer-specific bounded classification without implementation coupling. + * @param outcome classification of the logical terminal failure + */ + public synchronized void failure(final AiCallOutcome outcome) { + if (!completed) { + failure = outcome; + } + } + + /** + * Allocate state exactly when an upstream attempt starts, not when preparing it. + * @param target trusted context updated with the actual selected target + * @param kind reason for the attempt + * @param provider selected provider + * @param protocol selected client protocol + * @param streaming actual mode + * @return isolated attempt state + */ + public synchronized Attempt startAttempt(final AgentRequestContext target, final AiAttemptEvent.Kind kind, + final String provider, final String protocol, final boolean streaming) { + if (completed) { + Attempt ignored = new Attempt(this, context, attempts, kind, provider, protocol, streaming); + ignored.completed = true; + return ignored; + } + updateContext(target); + active = new Attempt(this, context, ++attempts, kind, provider, protocol, streaming); + usage = AiUsage.UNKNOWN; + return active; + } + + /** + * Freeze once after the entire owned chain terminates, including recovery writes. + * @param signal logical terminal signal + * @param httpStatus assigned downstream status, nullable before commitment + */ + public void finish(final SignalType signal, final Integer httpStatus) { + final AiAttemptEvent attemptEvent; + final AiTerminalEvent terminalEvent; + synchronized (this) { + if (completed) { + return; + } + completed = true; + attemptEvent = Objects.isNull(active) ? null : active.freeze(signal, AiCallOutcome.ERROR); + AiCallOutcome error = Objects.isNull(failure) && signal == SignalType.ON_ERROR ? AiCallOutcome.ERROR : failure; + AiCallOutcome outcome = signal == SignalType.CANCEL ? AiCallOutcome.CANCELLED : terminalOutcome(httpStatus, error); + terminalEvent = new AiTerminalEvent(context, outcome, httpStatus, elapsed(started), attempts, usage); + } + recordAttempt(attemptEvent); + if (Objects.nonNull(observer)) { + try { + observer.record(terminalEvent); + } catch (RuntimeException ignored) { + // Observation must never change the request; do not log callback text. + } + } + } + + private void recordAttempt(final AiAttemptEvent event) { + if (Objects.nonNull(observer) && Objects.nonNull(event)) { + try { + observer.recordAttempt(event); + } catch (RuntimeException ignored) { + // Observation must not change retry, cancellation or response delivery. + } + } + } + + /** + * Classify explicit HTTP status without treating a cancelled write as delivered. + * @param status assigned status + * @param error bounded failure, or null + * @return bounded outcome + */ + public static AiCallOutcome terminalOutcome(final Integer status, final AiCallOutcome error) { + if (Objects.nonNull(error)) { + return error; + } + if (Objects.equals(status, 504)) { + return AiCallOutcome.TIMEOUT; + } + if (Objects.equals(status, 429)) { + return AiCallOutcome.RATE_LIMITED; + } + if (Objects.nonNull(status) && status >= 400 && status < 500) { + return AiCallOutcome.REJECTED; + } + return Objects.nonNull(status) && status >= 500 ? AiCallOutcome.ERROR : AiCallOutcome.SUCCESS; + } + + private static long elapsed(final long start) { + return TimeUnit.NANOSECONDS.toMillis(Math.max(0, System.nanoTime() - start)); + } + + /** + * Mutable bounded state for one actual attempt, guarded by its logical owner. + */ + public static final class Attempt { + + private final AiRequestObservation owner; + + private final AgentRequestContext context; + + private final int number; + + private final AiAttemptEvent.Kind kind; + + private final String provider; + + private final String protocol; + + private final boolean streaming; + + private final long started = System.nanoTime(); + + private Integer status; + + private AiUsage usage = AiUsage.UNKNOWN; + + private boolean completed; + + private Attempt(final AiRequestObservation owner, final AgentRequestContext context, final int number, final AiAttemptEvent.Kind kind, + final String provider, final String protocol, final boolean streaming) { + this.owner = owner; + this.context = context; + this.number = number; + this.kind = kind; + this.provider = provider; + this.protocol = protocol; + this.streaming = streaming; + } + + public void status(final int value) { + synchronized (owner) { + if (!completed) { + status = value; + } + } + } + + public void usage(final AiUsage value) { + synchronized (owner) { + if (!completed) { + usage = Objects.requireNonNull(value); + } + } + } + + /** + * Complete before retry/fallback recovery starts; repeated calls are harmless. + * @param signal attempt terminal signal + * @param error classified error or null on normal completion + */ + public void finish(final SignalType signal, final AiCallOutcome error) { + final AiAttemptEvent event; + synchronized (owner) { + event = freeze(signal, error); + } + owner.recordAttempt(event); + } + + private AiAttemptEvent freeze(final SignalType signal, final AiCallOutcome error) { + if (completed) { + return null; + } + completed = true; + owner.usage = usage; + if (owner.active == this) { + owner.active = null; + } + AiCallOutcome outcome = signal == SignalType.CANCEL ? AiCallOutcome.CANCELLED : terminalOutcome(status, error); + return new AiAttemptEvent(context, number, kind, provider, protocol, streaming, outcome, status, elapsed(started), usage); + } + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiTerminalEvent.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiTerminalEvent.java new file mode 100644 index 000000000000..c14a80c5cf82 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiTerminalEvent.java @@ -0,0 +1,33 @@ +/* + * 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.metrics; + +import org.apache.shenyu.common.dto.AgentRequestContext; + +/** + * One logical terminal event after recovery and response writing. Usage belongs + * only to the last started attempt; it is not a sum or an inference about costs. + * @param context final actual target and trusted request facts + * @param outcome terminal classification + * @param httpStatus assigned downstream status, not proof of delivery + * @param elapsedMillis monotonic logical duration + * @param attemptCount actual upstream attempts, zero for early rejections + * @param usage last attempt's explicit snapshot, or unknown + */ +public record AiTerminalEvent(AgentRequestContext context, AiCallOutcome outcome, Integer httpStatus, long elapsedMillis, int attemptCount, AiUsage usage) { +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiUsage.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiUsage.java new file mode 100644 index 000000000000..28451b8b4b96 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiUsage.java @@ -0,0 +1,39 @@ +/* + * 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.metrics; + +/** + * Explicit upstream token counts, never estimates. Null means unknown, not zero. + * Total is never calculated from the other fields. A snapshot does not establish + * chargeability or successful delivery, especially on a cancelled stream. + * @param promptTokens upstream-reported input count + * @param completionTokens upstream-reported output count + * @param totalTokens upstream-reported total + * @param status bounded observation quality + */ +public record AiUsage(Long promptTokens, Long completionTokens, Long totalTokens, Status status) { + + public static final AiUsage UNKNOWN = new AiUsage(null, null, null, Status.UNKNOWN); + + /** + * Quality of the raw upstream observation, not a billing decision. + */ + public enum Status { + UNKNOWN, REPORTED, INVALID, LIMIT_EXCEEDED, UNSUPPORTED + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/tracing/AgentTraceContext.java b/shenyu-common/src/main/java/org/apache/shenyu/common/tracing/AgentTraceContext.java new file mode 100644 index 000000000000..f2c86c2541f1 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/tracing/AgentTraceContext.java @@ -0,0 +1,91 @@ +/* + * 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.tracing; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * SDK-independent keys and bounded snapshots for explicitly propagated Agent trace headers. + * These values are telemetry, never authentication or authorization input. + */ +public final class AgentTraceContext { + + /** + * Existing TracingConstants.REACTOR_CONTEXT_KEY, shared without depending on the tracing plugin. + */ + public static final String GATEWAY_REACTOR_CONTEXT_KEY = "org.apache.shenyu.plugin.tracing.context"; + + /** + * Immutable logical-call headers carried in Reactor context and McpTransportContext. + */ + public static final String HEADERS_KEY = "org.apache.shenyu.agent.trace.headers"; + + private static final Pattern TRACEPARENT = Pattern.compile("00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}"); + + private static final Pattern STATE_KEY = Pattern.compile("(?:[a-z][a-z0-9_*/-]{0,255}|[a-z0-9][a-z0-9_*/-]{0,240}@[a-z][a-z0-9_*/-]{0,13})"); + + private AgentTraceContext() { + } + + /** + * Snapshot only locally encoded W3C version-00 trace headers, excluding all other entries. + * Invalid telemetry is omitted instead of breaking an application request. + * @param value explicit header carrier, never the inbound HTTP headers + * @return immutable traceparent and optional tracestate, or an empty map + */ + public static Map headers(final Object value) { + if (!(value instanceof Map headers) || !(headers.get("traceparent") instanceof String parent) + || !TRACEPARENT.matcher(parent).matches() + || "00000000000000000000000000000000".equals(parent.substring(3, 35)) + || "0000000000000000".equals(parent.substring(36, 52))) { + return Map.of(); + } + Object state = headers.get("tracestate"); + if (state instanceof String text && validState(text)) { + return Map.of("traceparent", parent, "tracestate", text); + } + return Map.of("traceparent", parent); + } + + private static boolean validState(final String state) { + if (state.isEmpty() || state.length() > 512 || state.chars().anyMatch(character -> character < 32 || character > 126)) { + return false; + } + String[] entries = state.split(",", -1); + if (entries.length > 32) { + return false; + } + Set keys = new HashSet<>(); + for (String entry : entries) { + String member = entry.trim(); + int separator = member.indexOf('='); + if (separator < 1 || separator != member.lastIndexOf('=') || separator == member.length() - 1 + || member.length() - separator - 1 > 256) { + return false; + } + String key = member.substring(0, separator); + if (!STATE_KEY.matcher(key).matches() || !keys.add(key)) { + return false; + } + } + return true; + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentRequestContextTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentRequestContextTest.java new file mode 100644 index 000000000000..df348c9fe13e --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentRequestContextTest.java @@ -0,0 +1,58 @@ +/* + * 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.dto; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +class AgentRequestContextTest { + + @Test + void snapshotsPreserveCorrelationWithoutMutatingPreviousStages() { + AgentRequestContext initial = new AgentRequestContext("request", "mcp", "selector", "rule"); + AgentRequestContext identity = initial.withIdentity("tenant", "subject"); + final AgentRequestContext execution = identity.withConfigurationVersion(7).withTarget("server.tool", "tools/call", "2025-06-18"); + assertNotSame(identity, initial); + assertNull(initial.getTenant()); + assertNull(initial.getSubject()); + assertNull(identity.getTarget()); + assertNull(identity.getConfigurationVersion()); + assertEquals("request", execution.getRequestId()); + assertEquals("tenant", execution.getTenant()); + assertEquals("subject", execution.getSubject()); + assertEquals("server.tool", execution.getTarget()); + assertEquals("tools/call", execution.getOperation()); + assertEquals("2025-06-18", execution.getProtocolVersion()); + assertEquals(7L, execution.getConfigurationVersion()); + assertNull(execution.getSessionId()); + } + + @Test + void unassignedIdentityAndSessionRemainUnknown() { + AgentRequestContext context = new AgentRequestContext("request", "LLM", null, null) + .withIdentity(null, null).withTarget(null, null, null); + assertNull(context.getSubject()); + assertNull(context.getTenant()); + assertNull(context.getSessionId()); + assertNull(context.getProtocolVersion()); + assertNull(context.getConfigurationVersion()); + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/enums/AgentGatewayPluginOrderTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/enums/AgentGatewayPluginOrderTest.java new file mode 100644 index 000000000000..97409161560d --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/enums/AgentGatewayPluginOrderTest.java @@ -0,0 +1,125 @@ +/* + * 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.enums; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Default order and database seed contract for the single Agent Gateway entry. + */ +class AgentGatewayPluginOrderTest { + + @Test + void shouldPlaceGatewayAfterAuthenticationAndBeforeTheExistingAiChain() { + List ordered = Arrays.stream(new PluginEnum[]{PluginEnum.AI_PROXY, PluginEnum.AI_TOKEN_LIMITER, + PluginEnum.AGENT_GATEWAY, PluginEnum.KEY_AUTH, PluginEnum.AI_PROMPT}) + .sorted(Comparator.comparingInt(PluginEnum::getCode)) + .map(PluginEnum::getName).collect(Collectors.toList()); + assertEquals(Arrays.asList("keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"), ordered); + assertTrue(PluginEnum.BASIC_AUTH.getCode() < PluginEnum.AGENT_GATEWAY.getCode()); + assertTrue(PluginEnum.JWT.getCode() < PluginEnum.AGENT_GATEWAY.getCode()); + assertTrue(PluginEnum.OAUTH2.getCode() < PluginEnum.AGENT_GATEWAY.getCode()); + assertEquals(1, Arrays.stream(PluginEnum.values()) + .filter(plugin -> plugin.getCode() == PluginEnum.AGENT_GATEWAY.getCode()).count()); + } + + @ParameterizedTest + @ValueSource(strings = { + "db/init/mysql/schema.sql", + "db/init/pg/create-table.sql", + "db/init/oracle/schema.sql", + "shenyu-admin/src/main/resources/sql-script/h2/schema.sql", + "db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql", + "db/upgrade/2.7.1-upgrade-2.7.2-pg.sql", + "db/upgrade/2.7.1-upgrade-2.7.2-og.sql", + "db/upgrade/2.7.1-upgrade-2.7.2-ob.sql", + "db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql" + }) + void shouldKeepGatewayAndNamespaceSeedsInSync(final String script) throws IOException { + String sql = Files.readString(repositoryRoot().resolve(script)); + assertSeedOrder(sql, "68", PluginEnum.AGENT_GATEWAY, script); + } + + @ParameterizedTest + @ValueSource(strings = { + "db/init/mysql/schema.sql", + "db/init/pg/create-table.sql", + "db/init/oracle/schema.sql", + "shenyu-admin/src/main/resources/sql-script/h2/schema.sql" + }) + void shouldKeepTheCompleteFreshInstallAiChainInSync(final String script) throws IOException { + String sql = Files.readString(repositoryRoot().resolve(script)); + assertSeedOrder(sql, "40", PluginEnum.KEY_AUTH, script); + assertSeedOrder(sql, "52", PluginEnum.AI_PROMPT, script); + assertSeedOrder(sql, "51", PluginEnum.AI_TOKEN_LIMITER, script); + assertSeedOrder(sql, "50", PluginEnum.AI_PROXY, script); + } + + private void assertSeedOrder(final String sql, final String id, final PluginEnum plugin, final String script) { + String value = Integer.toString(plugin.getCode()); + String field = "(?:NULL|'(?:''|[^'])*')"; + String pluginRow = "'" + id + "'[ ]*,[ ]*'" + plugin.getName() + + "'[ ]*,[ ]*(?:'[^']+'[ ]*,[ ]*" + value + "|" + field + "[ ]*,[ ]*'[^']+'[ ]*,[ ]*" + value + ")[ ]*,"; + String namespaceRow = "'[^']+'[ ]*,[ ]*'649330b6-c2d7-4edc-be8e-8a54df9eb385'[ ]*,[ ]*'" + id + + "'[ ]*,[ ]*" + field + "[ ]*,[ ]*" + value + "[ ]*,"; + String normalized = sql.lines().collect(Collectors.joining(" ")).replace((char) 9, ' '); + assertTrue(Pattern.compile(pluginRow, Pattern.CASE_INSENSITIVE).matcher(normalized).find(), script + ": plugin " + plugin.getName()); + assertTrue(Pattern.compile(namespaceRow, Pattern.CASE_INSENSITIVE).matcher(normalized).find(), script + ": namespace " + plugin.getName()); + } + + @Test + void shouldKeepTheExistingInstallationMigrationExplicitAndDefaultOnly() throws IOException { + String sql = Files.readString(repositoryRoot().resolve("db/upgrade/2.7.2-agent-gateway-order.sql")); + String statements = sql.lines().filter(line -> !line.startsWith("--")) + .map(String::trim).filter(line -> !line.isEmpty()).collect(Collectors.joining(" ")); + assertEquals("UPDATE plugin SET sort = " + PluginEnum.AGENT_GATEWAY.getCode() + + " WHERE name = 'agentGateway' AND sort = 198; UPDATE namespace_plugin_rel SET sort = " + + PluginEnum.AGENT_GATEWAY.getCode() + + " WHERE sort = 198 AND plugin_id IN (SELECT id FROM plugin WHERE name = 'agentGateway');", statements); + assertFalse(statements.contains("enabled")); + assertFalse(statements.contains("config")); + } + + private Path repositoryRoot() { + Path path = Paths.get("").toAbsolutePath(); + while (Objects.nonNull(path)) { + if (Files.isDirectory(path.resolve("db/init")) && Files.isDirectory(path.resolve("shenyu-common"))) { + return path; + } + path = path.getParent(); + } + throw new IllegalStateException("Run the seed contract tests inside the ShenYu checkout"); + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/metrics/AiRequestObservationTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/metrics/AiRequestObservationTest.java new file mode 100644 index 000000000000..3b05667650f6 --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/metrics/AiRequestObservationTest.java @@ -0,0 +1,170 @@ +/* + * 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.metrics; + +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import reactor.core.publisher.SignalType; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +class AiRequestObservationTest { + + @Test + void recordsEachAttemptAndOnlyTheLastUsageWithoutSummation() { + final Sink sink = new Sink(); + final AgentRequestContext base = new AgentRequestContext("request", "llm", "selector", "rule"); + final AiRequestObservation observation = new AiRequestObservation(sink, base); + final AiRequestObservation.Attempt first = observation.startAttempt(base.withTarget("primary", "chat", null), + AiAttemptEvent.Kind.PRIMARY, "openai", "openai-chat", false); + first.status(503); + first.usage(new AiUsage(5L, 2L, null, AiUsage.Status.REPORTED)); + first.finish(SignalType.ON_COMPLETE, null); + first.finish(SignalType.CANCEL, null); + final AiRequestObservation.Attempt second = observation.startAttempt(base.withTarget("fallback", "chat", null), + AiAttemptEvent.Kind.FALLBACK, "openai", "openai-chat", false); + second.status(200); + second.finish(SignalType.ON_COMPLETE, null); + observation.finish(SignalType.ON_COMPLETE, 200); + observation.finish(SignalType.CANCEL, null); + assertEquals(2, sink.attempts.size()); + assertEquals(AiCallOutcome.ERROR, sink.attempts.get(0).outcome()); + assertNull(sink.attempts.get(0).usage().totalTokens()); + assertEquals(1, sink.events.size()); + assertEquals(2, sink.events.get(0).attemptCount()); + assertSame(AiUsage.UNKNOWN, sink.events.get(0).usage()); + assertEquals("fallback", sink.events.get(0).context().getTarget()); + } + + @Test + void cancelSealsActiveAttemptBeforeLogicalEventAndIgnoresLateFacts() { + final Sink sink = new Sink(); + final AgentRequestContext base = new AgentRequestContext("request", "llm", null, null); + final AiRequestObservation observation = new AiRequestObservation(sink, base); + final AiRequestObservation.Attempt attempt = observation.startAttempt(base, AiAttemptEvent.Kind.PRIMARY, "openai", "openai-chat", true); + attempt.status(200); + observation.finish(SignalType.CANCEL, 200); + attempt.usage(new AiUsage(1L, 1L, 2L, AiUsage.Status.REPORTED)); + attempt.finish(SignalType.ON_COMPLETE, null); + observation.updateContext(base.withIdentity("late", "late")); + assertEquals(List.of("attempt", "terminal"), sink.order); + assertEquals(AiCallOutcome.CANCELLED, sink.attempts.get(0).outcome()); + assertEquals(AiCallOutcome.CANCELLED, sink.events.get(0).outcome()); + assertSame(AiUsage.UNKNOWN, sink.events.get(0).usage()); + assertNull(observation.getContext().getTenant()); + } + + @Test + void acceptsOnlySameRequestIdentityUpdatesAndRecordsPreExecutionRejection() { + final Sink sink = new Sink(); + final AgentRequestContext base = new AgentRequestContext("request", "llm", null, null); + final AiRequestObservation observation = new AiRequestObservation(sink, base); + observation.updateContext(base.withIdentity("tenant", "subject")); + observation.updateContext(new AgentRequestContext("different", "llm", null, null)); + observation.finish(SignalType.ON_COMPLETE, 429); + assertEquals("tenant", sink.events.get(0).context().getTenant()); + assertEquals(0, sink.events.get(0).attemptCount()); + assertEquals(AiCallOutcome.RATE_LIMITED, sink.events.get(0).outcome()); + } + + @Test + void observerReentrancyAndFailureCannotDuplicateOrFailTerminalDelivery() { + final AtomicReference owner = new AtomicReference<>(); + final List events = new ArrayList<>(); + final AiCallObserver observer = new AiCallObserver() { + @Override + public void record(final AiTerminalEvent event) { + events.add(event); + owner.get().finish(SignalType.CANCEL, null); + throw new IllegalStateException("private callback text"); + } + + @Override + public void recordAttempt(final AiAttemptEvent event) { + owner.get().finish(SignalType.CANCEL, null); + throw new IllegalStateException("private callback text"); + } + }; + final AgentRequestContext base = new AgentRequestContext("request", "llm", null, null); + owner.set(new AiRequestObservation(observer, base)); + owner.get().startAttempt(base, AiAttemptEvent.Kind.PRIMARY, "openai", "openai-chat", false); + assertDoesNotThrow(() -> owner.get().finish(SignalType.CANCEL, null)); + assertEquals(1, events.size()); + } + + @Test + void classifiesResponseWriteFailureAndTimeoutWithoutRetainingException() { + final Sink sink = new Sink(); + final AiRequestObservation observation = new AiRequestObservation(sink, new AgentRequestContext("request", "llm", null, null)); + observation.error(new TimeoutException("sensitive text")); + observation.finish(SignalType.ON_ERROR, 200); + assertEquals(AiCallOutcome.TIMEOUT, sink.events.get(0).outcome()); + assertEquals(AiCallOutcome.ERROR, AiRequestObservation.terminalOutcome(200, AiCallOutcome.ERROR)); + assertEquals(AiCallOutcome.TIMEOUT, AiRequestObservation.terminalOutcome(504, null)); + } + + @ParameterizedTest + @ValueSource(ints = {200, 400, 401, 429, 500, 504}) + void writeFailureAndCancellationOverrideAssignedStatus(final int status) { + final AgentRequestContext base = new AgentRequestContext("request", "llm", null, null); + final Sink sink = new Sink(); + final AiRequestObservation observation = new AiRequestObservation(sink, base); + observation.failure(AiCallOutcome.TIMEOUT); + observation.error(new IllegalStateException("response write failed")); + observation.finish(SignalType.ON_ERROR, status); + assertEquals(AiCallOutcome.ERROR, sink.events.get(0).outcome()); + final AiRequestObservation cancelled = new AiRequestObservation(sink, base); + cancelled.error(new IllegalStateException("response write failed")); + cancelled.finish(SignalType.CANCEL, status); + assertEquals(AiCallOutcome.CANCELLED, sink.events.get(1).outcome()); + final AiRequestObservation unhandled = new AiRequestObservation(sink, base); + unhandled.finish(SignalType.ON_ERROR, status); + assertEquals(AiCallOutcome.ERROR, sink.events.get(2).outcome()); + } + + private static final class Sink implements AiCallObserver { + + private final List events = new ArrayList<>(); + + private final List attempts = new ArrayList<>(); + + private final List order = new ArrayList<>(); + + @Override + public void record(final AiTerminalEvent event) { + events.add(event); + order.add("terminal"); + } + + @Override + public void recordAttempt(final AiAttemptEvent event) { + attempts.add(event); + order.add("attempt"); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java index 2549a5a31738..98a7a50057e8 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java @@ -19,12 +19,17 @@ import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.common.metrics.AiCallOutcome; +import org.apache.shenyu.common.metrics.AiRequestObservation; import org.apache.shenyu.common.enums.PluginEnum; import org.apache.shenyu.plugin.agent.gateway.handle.AgentGatewayRuleHandle; import org.apache.shenyu.plugin.agent.gateway.handle.AgentGatewayRuleHandleParser; import org.apache.shenyu.plugin.agent.gateway.handler.AgentGatewayPluginDataHandler; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpHttpHandler; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry; import org.apache.shenyu.plugin.api.ShenyuPluginChain; import org.apache.shenyu.plugin.api.result.ShenyuResultWrap; @@ -34,6 +39,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.ResponseStatusException; import reactor.core.publisher.Mono; import java.util.Objects; @@ -50,13 +56,23 @@ public class AgentGatewayPlugin extends AbstractShenyuPlugin { private final AgentMcpHttpHandler mcpHandler; + private final AgentMcpSecurityResolver llmSecurityResolver; + + private final AiCallObserver aiObserver; + public AgentGatewayPlugin() { this(new AgentMcpHttpHandler(new AgentMcpDispatcher(new AgentToolRegistry(List.of()), "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION), exchange -> Mono.empty())); } public AgentGatewayPlugin(final AgentMcpHttpHandler mcpHandler) { + this(mcpHandler, null, null); + } + + public AgentGatewayPlugin(final AgentMcpHttpHandler mcpHandler, final AgentMcpSecurityResolver llmSecurityResolver, final AiCallObserver aiObserver) { this.mcpHandler = Objects.requireNonNull(mcpHandler, "mcpHandler"); + this.llmSecurityResolver = llmSecurityResolver; + this.aiObserver = aiObserver; } @Override @@ -78,12 +94,40 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu registerResponseRequestId(exchange, context.getRequestId()); } return Mono.defer(() -> "mcp".equals(handle.getTrafficType()) - ? mcpHandler.handle(exchange, handle.getMcp(), context, handle.getGeneration()) : chain.execute(exchange)) - .contextWrite(reactorContext -> reactorContext.put(AgentGatewayConstants.REACTOR_CONTEXT_KEY, context)) + ? mcpHandler.handle(exchange, handle.getMcp(), context, handle.getGeneration()) + : handleLlm(exchange, chain, context.toRequestContext(handle.getGeneration()))) + .contextWrite(reactorContext -> reactorContext.put(AgentGatewayConstants.REACTOR_CONTEXT_KEY, context) + .put(AgentRequestContext.REACTOR_KEY, context.toRequestContext(handle.getGeneration()))) .doFinally(signal -> restorePreviousContext(exchange, previousContext, context)); }); } + private Mono handleLlm(final ServerWebExchange exchange, final ShenyuPluginChain chain, final AgentRequestContext initial) { + return Mono.defer(() -> { + AiRequestObservation observation = new AiRequestObservation(aiObserver, initial); + Mono identity = Objects.isNull(llmSecurityResolver) ? Mono.just(initial) + : Mono.defer(() -> llmSecurityResolver.resolve(exchange)) + .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED))) + .map(trusted -> initial.withIdentity(trusted.getTenant().orElse(null), trusted.getSubject())); + // Only identity resolution errors are recovered here. A downstream write failure + // must retain its existing error path and must never trigger another proxy request. + Mono execution = Objects.isNull(llmSecurityResolver) ? Mono.defer(() -> chain.execute(exchange)) : identity.onErrorResume(error -> { + observation.failure(error instanceof ResponseStatusException ? AiCallOutcome.REJECTED : AiCallOutcome.ERROR); + exchange.getResponse().setStatusCode(error instanceof ResponseStatusException status + ? status.getStatusCode() : HttpStatus.INTERNAL_SERVER_ERROR); + return exchange.getResponse().setComplete().then(Mono.empty()); + }).flatMap(context -> { + observation.updateContext(context); + return Mono.defer(() -> chain.execute(exchange)) + .contextWrite(reactorContext -> reactorContext.put(AgentRequestContext.REACTOR_KEY, context)); + }); + return execution.contextWrite(context -> context.put(AiRequestObservation.REACTOR_KEY, observation)) + .doOnError(observation::error) + .doFinally(signal -> observation.finish(signal, Objects.isNull(exchange.getResponse().getStatusCode()) + ? null : exchange.getResponse().getStatusCode().value())); + }); + } + private void restorePreviousContext(final ServerWebExchange exchange, final Object previousContext, final AgentTrafficContext currentContext) { // DefaultServerWebExchange uses a ConcurrentHashMap for attributes. The conditional diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentTrafficContext.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentTrafficContext.java index 71348e390706..a5637b03c4ac 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentTrafficContext.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentTrafficContext.java @@ -17,6 +17,8 @@ package org.apache.shenyu.plugin.agent.gateway; +import org.apache.shenyu.common.dto.AgentRequestContext; + import java.util.Objects; /** @@ -59,6 +61,10 @@ public String getRuleId() { return ruleId; } + public AgentRequestContext toRequestContext(final long configurationVersion) { + return new AgentRequestContext(requestId, trafficType, selectorId, ruleId).withConfigurationVersion(configurationVersion); + } + @Override public String toString() { return "AgentTrafficContext{requestId='" + requestId + "', trafficType='" + trafficType diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java index 1ad669eef207..35cb0ceeb1b4 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java @@ -22,7 +22,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.shenyu.common.constant.Constants; import org.apache.shenyu.common.dto.AgentGatewayMcpConfig; +import org.apache.shenyu.common.dto.AgentRequestContext; import org.apache.shenyu.common.metrics.AgentMcpCallObserver; +import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver; import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; import org.springframework.core.io.buffer.DataBuffer; @@ -61,6 +63,8 @@ public final class AgentMcpHttpHandler { private final AgentMcpCallTracer tracer; + private final AgentMcpTerminalObserver terminalObserver; + private final AgentMcpRequestParser parser = new AgentMcpRequestParser(); private final ObjectMapper mapper = new ObjectMapper(); @@ -70,9 +74,15 @@ public AgentMcpHttpHandler(final AgentMcpDispatcher dispatcher, final AgentMcpSe } public AgentMcpHttpHandler(final AgentMcpDispatcher dispatcher, final AgentMcpSecurityResolver securityResolver, final AgentMcpCallTracer tracer) { + this(dispatcher, securityResolver, tracer, null); + } + + public AgentMcpHttpHandler(final AgentMcpDispatcher dispatcher, final AgentMcpSecurityResolver securityResolver, + final AgentMcpCallTracer tracer, final AgentMcpTerminalObserver terminalObserver) { this.dispatcher = Objects.requireNonNull(dispatcher, "dispatcher"); this.securityResolver = Objects.requireNonNull(securityResolver, "securityResolver"); this.tracer = tracer; + this.terminalObserver = terminalObserver; } /** @@ -87,6 +97,8 @@ public AgentMcpHttpHandler(final AgentMcpDispatcher dispatcher, final AgentMcpSe public Mono handle(final ServerWebExchange exchange, final AgentGatewayMcpConfig config, final AgentTrafficContext traffic, final long configurationVersion) { return Mono.deferContextual(parentContext -> { + final AgentMcpTerminalObservation terminal = Objects.isNull(terminalObserver) ? null + : new AgentMcpTerminalObservation(terminalObserver, traffic, configurationVersion); final Instant deadline = Instant.now().plusMillis(config.getTimeoutMs()); Object callback = exchange.getAttribute(Constants.METRICS_AGENT_MCP_CALL); final AgentMcpCallObservation observation = new AgentMcpCallObservation(callback instanceof AgentMcpCallObserver observer ? observer : null, @@ -95,30 +107,60 @@ public Mono handle(final ServerWebExchange exchange, final AgentGatewayMcp return Mono.fromRunnable(() -> preflight(exchange, config)) .then(Mono.defer(() -> securityResolver.resolve(exchange)) .switchIfEmpty(Mono.error(failure(401, "Trusted identity is required", null)))) + .doOnNext(identity -> { + if (Objects.nonNull(terminal)) { + terminal.identified(identity.getTenant().orElse(null), identity.getSubject()); + } + }) .flatMap(identity -> read(exchange, config).map(body -> parser.parse(body, exchange.getRequest().getHeaders(), config.getMaxRequestBytes())) .flatMap(request -> { rpcId.set(request.getId()); + if (Objects.nonNull(terminal)) { + terminal.parsed(request); + } observation.parsed(request); return dispatcher.dispatch(request, () -> new AgentMcpExecutionContext(traffic.getRequestId(), identity.getSubject(), traffic.getRuleId(), configurationVersion, config.getAllowedTools(), identity.getToolGrants(), deadline, config.getResultFilters(), identity.getTenant().orElse(null))) - .contextWrite(observation::traceContext); + .contextWrite(observation::traceContext) + .contextWrite(context -> context.put(AgentRequestContext.REACTOR_KEY, + traffic.toRequestContext(configurationVersion).withIdentity(identity.getTenant().orElse(null), identity.getSubject()) + .withTarget("tools/call".equals(request.getMethod()) ? request.getParams().path("name").textValue() : null, + request.getMethod(), AgentMcpRequestParser.VERSION))); })) .flatMap(response -> { observation.response(response); + if (Objects.nonNull(terminal)) { + terminal.response(response.path("result").path("isError").asBoolean(false)); + } return write(exchange, response, config, "sse".equals(config.getResponseMode()), 200); }) .timeout(Duration.ofMillis(config.getTimeoutMs())) .onErrorResume(error -> { observation.failure(error); - return handleFailure(exchange, config, rpcId.get(), error); + recordFailure(terminal, error); + return handleFailure(exchange, config, rpcId.get(), error, terminal); }) // Recovery writes can fail independently of the execution error classified above. - .doOnError(observation::failure) - .doFinally(observation::finish); + .doOnError(error -> { + observation.failure(error); + recordFailure(terminal, error); + }) + .doFinally(signal -> { + observation.finish(signal); + if (Objects.nonNull(terminal)) { + terminal.finish(signal, Objects.isNull(exchange.getResponse().getStatusCode()) ? null : exchange.getResponse().getStatusCode().value()); + } + }); }); } + private void recordFailure(final AgentMcpTerminalObservation terminal, final Throwable error) { + if (Objects.nonNull(terminal)) { + terminal.failure(error, error instanceof TransportFailure ? ((TransportFailure) error).status : null); + } + } + private void preflight(final ServerWebExchange exchange, final AgentGatewayMcpConfig config) { HttpHeaders headers = exchange.getRequest().getHeaders(); List origins = headers.get(HttpHeaders.ORIGIN); @@ -179,7 +221,8 @@ private Mono read(final ServerWebExchange exchange, final AgentGatewayMc }).defaultIfEmpty(new byte[0]); } - private Mono handleFailure(final ServerWebExchange exchange, final AgentGatewayMcpConfig config, final JsonNode id, final Throwable error) { + private Mono handleFailure(final ServerWebExchange exchange, final AgentGatewayMcpConfig config, final JsonNode id, + final Throwable error, final AgentMcpTerminalObservation terminal) { if (exchange.getResponse().isCommitted()) { return Mono.error(error); } @@ -206,6 +249,7 @@ private Mono handleFailure(final ServerWebExchange exchange, final AgentGa // Execution is already terminated. Bound the best-effort terminal error write too. return write(exchange, response, config, false, status) .onErrorResume(writeFailure -> { + recordFailure(terminal, writeFailure); if (exchange.getResponse().isCommitted()) { return Mono.error(writeFailure); } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java new file mode 100644 index 000000000000..2d5c334a1d5e --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java @@ -0,0 +1,130 @@ +/* + * 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.plugin.agent.gateway.protocol; + +import org.apache.shenyu.common.metrics.AgentMcpCallObserver.Outcome; +import org.apache.shenyu.common.metrics.AgentMcpTerminalEvent; +import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver; +import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.io.buffer.DataBufferLimitException; +import reactor.core.publisher.SignalType; + +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * Per-subscription state frozen atomically on termination, never keyed by RPC id. + */ +final class AgentMcpTerminalObservation { + + private static final Logger LOG = LoggerFactory.getLogger(AgentMcpTerminalObservation.class); + + private final AgentMcpTerminalObserver observer; + + private final AgentTrafficContext traffic; + + private final long configurationVersion; + + private final long started = System.nanoTime(); + + private String subject; + + private String tenant; + + private String method; + + private String requestedTool; + + private String protocolVersion; + + private Outcome outcome = Outcome.SERVER_ERROR; + + private boolean completed; + + AgentMcpTerminalObservation(final AgentMcpTerminalObserver observer, final AgentTrafficContext traffic, final long configurationVersion) { + this.observer = observer; + this.traffic = traffic; + this.configurationVersion = configurationVersion; + } + + synchronized void identified(final String value) { + if (!completed) { + subject = value; + } + } + + synchronized void identified(final String trustedTenant, final String trustedSubject) { + if (!completed) { + tenant = trustedTenant; + subject = trustedSubject; + } + } + + synchronized void parsed(final AgentMcpRequest request) { + if (!completed) { + method = request.getMethod(); + requestedTool = "tools/call".equals(method) ? request.getParams().path("name").textValue() : null; + protocolVersion = AgentMcpRequestParser.VERSION; + } + } + + synchronized void response(final boolean toolError) { + if (!completed) { + outcome = toolError ? Outcome.TOOL_ERROR : Outcome.SUCCESS; + } + } + + synchronized void failure(final Throwable error, final Integer transportStatus) { + if (completed) { + return; + } + Integer status = transportStatus; + if (error instanceof AgentMcpProtocolException) { + status = ((AgentMcpProtocolException) error).getHttpStatus(); + } + if (error instanceof TimeoutException || Objects.equals(status, 504)) { + outcome = Outcome.TIMEOUT; + } else if (error instanceof DataBufferLimitException || Objects.nonNull(status) && status < 500) { + outcome = Outcome.REJECTED; + } else { + outcome = Outcome.SERVER_ERROR; + } + } + + void finish(final SignalType signal, final Integer status) { + AgentMcpTerminalEvent event; + synchronized (this) { + if (completed) { + return; + } + completed = true; + event = new AgentMcpTerminalEvent(traffic.toRequestContext(configurationVersion).withIdentity(tenant, subject) + .withTarget(requestedTool, method, protocolVersion), signal == SignalType.CANCEL ? Outcome.CANCELLED : outcome, + TimeUnit.NANOSECONDS.toMillis(Math.max(0, System.nanoTime() - started)), status); + } + try { + observer.record(event); + } catch (RuntimeException error) { + // Callback messages may contain sensitive application data. + LOG.debug("MCP terminal event callback failed"); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java index 0a428d8f87ad..0754c6e81b31 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java @@ -24,6 +24,7 @@ import io.modelcontextprotocol.common.McpTransportContext; import org.apache.shenyu.common.dto.AgentGatewayAggregationConfig; import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.tracing.AgentTraceContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpRemoteCatalog; import org.slf4j.Logger; @@ -234,7 +235,9 @@ public Mono invoke(final String name, final JsonObject arguments, fi } return directory .callRaw(name, context.getRuleTools(), context.getAllowedTools(), values) - .contextWrite(value -> value.put(McpTransportContext.KEY, McpTransportContext.create(Map.of("subject", context.getSubject(), "deadline", context.getDeadline())))); + .contextWrite(value -> value.put(McpTransportContext.KEY, McpTransportContext.create(Map.of( + "subject", context.getSubject(), "deadline", context.getDeadline(), + AgentTraceContext.HEADERS_KEY, AgentTraceContext.headers(value.getOrDefault(AgentTraceContext.HEADERS_KEY, null)))))); } } } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java index 1d5a75001d1b..8a7f297f5620 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.modelcontextprotocol.common.McpTransportContext; import io.modelcontextprotocol.spec.McpSchema; +import org.apache.shenyu.common.tracing.AgentTraceContext; import reactor.core.publisher.Mono; import reactor.core.publisher.SignalType; import reactor.core.publisher.Sinks; @@ -130,7 +131,7 @@ public RequestScopedMcpClient(final RemoteServerBinding binding, final java.util .flatMap(result -> request("notifications/initialized", Map.of(), true).thenReturn(result)) .doOnSuccess(ignored -> initialized = true) // Session handshake uses fixed service configuration, never the first Agent's context. - .contextWrite(context -> context.delete(McpTransportContext.KEY)) + .contextWrite(context -> context.delete(McpTransportContext.KEY).delete(AgentTraceContext.HEADERS_KEY)) .cache(); } @@ -209,6 +210,10 @@ private Mono request(final String method, final Object params, final if (Objects.nonNull(session) && !"initialize".equals(method)) { builder.header("MCP-Session-Id", session); } + // A shared handshake, directory refresh or session cleanup never belongs to an Agent call. + if ("tools/call".equals(method)) { + AgentTraceContext.headers(transportContext.get(AgentTraceContext.HEADERS_KEY)).forEach(builder::setHeader); + } HttpRequest outbound = builder.build(); if (active.incrementAndGet() > MAX_IN_FLIGHT) { active.decrementAndGet(); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPluginTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPluginTest.java index 7aa144e0db86..3298cb51e67e 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPluginTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPluginTest.java @@ -19,6 +19,10 @@ import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.metrics.AiTerminalEvent; +import org.apache.shenyu.common.metrics.AiCallOutcome; +import org.apache.shenyu.common.metrics.AiUsage; import org.apache.shenyu.common.enums.PluginEnum; import org.apache.shenyu.plugin.api.ShenyuPluginChain; import org.apache.shenyu.plugin.api.result.DefaultShenyuResult; @@ -53,6 +57,7 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.ConcurrentLinkedQueue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -66,6 +71,73 @@ class AgentGatewayPluginTest { private final AgentGatewayPlugin plugin = new AgentGatewayPlugin(); + @Test + void llmLimiterRejectionKeepsTrustedIdentityAndHasNoFabricatedUsage() { + ConcurrentLinkedQueue events = new ConcurrentLinkedQueue<>(); + AgentGatewayPlugin configured = new AgentGatewayPlugin(new AgentMcpHttpHandler( + new AgentMcpDispatcher(new AgentToolRegistry(List.of()), "server", "1"), ignored -> Mono.empty()), + ignored -> Mono.just(new AgentMcpIdentity("tenant", "subject", Set.of(), Set.of())), events::add); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/llm") + .header("X-Tenant-Id", "forged").header("X-Subject", "forged").body("private")); + StepVerifier.create(configured.doExecute(exchange, next -> Mono.deferContextual(context -> { + AgentRequestContext snapshot = context.get(AgentRequestContext.REACTOR_KEY); + assertEquals("tenant", snapshot.getTenant()); + assertEquals("subject", snapshot.getSubject()); + assertEquals(context.get(AgentGatewayConstants.REACTOR_CONTEXT_KEY).getRequestId(), snapshot.getRequestId()); + next.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); + return next.getResponse().setComplete(); + }), selector(), rule("rule-1"))).verifyComplete(); + assertEquals(1, events.size()); + AiTerminalEvent event = events.element(); + assertEquals(AiCallOutcome.RATE_LIMITED, event.outcome()); + assertEquals(0, event.attemptCount()); + assertEquals(AiUsage.UNKNOWN, event.usage()); + assertEquals("tenant", event.context().getTenant()); + assertTrue(Objects.isNull(event.context().getSessionId())); + } + + @Test + void explicitLlmIdentityRequirementRejectsWithoutReadingBody() { + ConcurrentLinkedQueue events = new ConcurrentLinkedQueue<>(); + AgentGatewayPlugin configured = new AgentGatewayPlugin(new AgentMcpHttpHandler( + new AgentMcpDispatcher(new AgentToolRegistry(List.of()), "server", "1"), ignored -> Mono.empty()), ignored -> Mono.empty(), events::add); + AtomicBoolean consumed = new AtomicBoolean(); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/llm").body(reactor.core.publisher.Flux.defer(() -> { + consumed.set(true); + return reactor.core.publisher.Flux.empty(); + }))); + StepVerifier.create(configured.doExecute(exchange, ignored -> Mono.error(new AssertionError("Unauthenticated request reached downstream")), + selector(), rule("rule-1"))).verifyComplete(); + assertEquals(HttpStatus.UNAUTHORIZED, exchange.getResponse().getStatusCode()); + assertEquals(1, events.size()); + assertEquals(AiCallOutcome.REJECTED, events.element().outcome()); + assertEquals(AiUsage.UNKNOWN, events.element().usage()); + assertTrue(!consumed.get()); + } + + @Test + void llmContextIsIsolatedAcrossConcurrentSubscriptionsAndCancellation() { + ConcurrentLinkedQueue events = new ConcurrentLinkedQueue<>(); + AgentGatewayPlugin configured = new AgentGatewayPlugin(new AgentMcpHttpHandler( + new AgentMcpDispatcher(new AgentToolRegistry(List.of()), "server", "1"), ignored -> Mono.empty()), + exchange -> exchange.getPrincipal().map(principal -> new AgentMcpIdentity(principal.getName(), "subject", Set.of(), Set.of())), events::add); + reactor.core.publisher.Flux executions = reactor.core.publisher.Flux.range(0, 32).flatMap(index -> { + ServerWebExchange exchange = newExchange().mutate().principal(Mono.just(() -> "tenant-" + index)).build(); + return configured.doExecute(exchange, ignored -> Mono.delay(Duration.ofMillis(1)).then(Mono.deferContextual(context -> { + assertEquals("tenant-" + index, context.get(AgentRequestContext.REACTOR_KEY).getTenant()); + return Mono.empty(); + })), selector(), rule("rule-1")); + }, 16); + StepVerifier.create(executions).verifyComplete(); + org.awaitility.Awaitility.await().untilAsserted(() -> assertEquals(32, events.size())); + assertEquals(32, events.stream().map(event -> event.context().getRequestId()).distinct().count()); + assertEquals(32, events.stream().map(event -> event.context().getTenant()).distinct().count()); + ServerWebExchange cancelled = newExchange().mutate().principal(Mono.just(() -> "cancelled")).build(); + StepVerifier.create(configured.doExecute(cancelled, ignored -> Mono.never(), selector(), rule("rule-1"))).thenCancel().verify(); + assertEquals(1, events.stream().filter(event -> event.outcome() == AiCallOutcome.CANCELLED).count()); + assertTrue(Objects.isNull(cancelled.getAttribute(AgentGatewayConstants.REQUEST_CONTEXT_ATTRIBUTE))); + } + @BeforeEach void initResult() { ApplicationContext applicationContext = mock(ApplicationContext.class); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java new file mode 100644 index 000000000000..ef3c93587876 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java @@ -0,0 +1,504 @@ +/* + * 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.plugin.agent.gateway.protocol; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.apache.shenyu.common.constant.Constants; +import org.apache.shenyu.common.dto.AgentGatewayMcpConfig; +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.metrics.AgentMcpCallObserver; +import org.apache.shenyu.common.metrics.AgentMcpCallObserver.Outcome; +import org.apache.shenyu.common.metrics.AgentMcpTerminalEvent; +import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver; +import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpIdentity; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; +import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolExecutionException; +import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolProvider; +import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.core.io.buffer.DataBufferUtils; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; +import reactor.core.publisher.Sinks; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; +import reactor.test.StepVerifier; + +import java.net.Socket; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class AgentMcpTerminalObservationTest { + + private final AgentTrafficContext traffic = new AgentTrafficContext("gateway-id", "mcp", "selector", "rule"); + + @Test + void trustedTenantAndCommonContextReachProviderAndTerminalWithoutSessionFabrication() { + Recording observer = new Recording(); + AtomicReference captured = new AtomicReference<>(); + Mono action = Mono.deferContextual(context -> { + captured.set(context.get(AgentRequestContext.REACTOR_KEY)); + return Mono.just(new JsonObject()); + }); + StepVerifier.create(handler(action, ignored -> Mono.just(new AgentMcpIdentity("tenant", "trusted", Set.of("read"), Set.of())), observer) + .handle(exchange("tools/call"), config("json", 30000), traffic, 7)).verifyComplete(); + AgentMcpTerminalEvent event = observer.only(Outcome.SUCCESS); + assertEquals("tenant", event.getTenant()); + assertEquals("tenant", captured.get().getTenant()); + assertEquals("trusted", captured.get().getSubject()); + assertEquals(event.getRequestId(), captured.get().getRequestId()); + assertEquals("read", captured.get().getTarget()); + assertEquals("tools/call", captured.get().getOperation()); + assertEquals(AgentMcpRequestParser.VERSION, captured.get().getProtocolVersion()); + assertNull(event.getSessionId()); + assertNull(captured.get().getSessionId()); + } + + @ParameterizedTest + @CsvSource({"json,SUCCESS", "sse,SUCCESS", "json,TOOL_ERROR", "sse,TOOL_ERROR"}) + void recordsBusinessResultAfterWriting(final String mode, final Outcome outcome) { + Recording observer = new Recording(); + Mono action = outcome == Outcome.TOOL_ERROR ? Mono.error(new AgentToolExecutionException("private")) : Mono.just(new JsonObject()); + MockServerWebExchange exchange = exchange("tools/call"); + StepVerifier.create(handler(action, identity(), observer).handle(exchange, config(mode, 30000), traffic, 7)).verifyComplete(); + AgentMcpTerminalEvent event = observer.only(outcome); + assertEquals("gateway-id", event.getRequestId()); + assertEquals("selector", event.getSelectorId()); + assertEquals("rule", event.getRuleId()); + assertEquals(7, event.getConfigurationVersion()); + assertEquals("trusted", event.getSubject()); + assertEquals("tools/call", event.getMethod()); + assertEquals("read", event.getRequestedTool()); + assertEquals(AgentMcpRequestParser.VERSION, event.getProtocolVersion()); + assertEquals(200, event.getHttpStatus()); + assertTrue(event.getElapsedMillis() >= 0); + } + + @ParameterizedTest + @ValueSource(strings = {"tools/list", "server/discover"}) + void nonCallMethodsHaveEventsButDoNotBecomeToolCalls(final String method) { + Recording observer = new Recording(); + AtomicInteger metricCalls = new AtomicInteger(); + MockServerWebExchange exchange = exchange(method); + exchange.getAttributes().put(Constants.METRICS_AGENT_MCP_CALL, (AgentMcpCallObserver) (outcome, elapsed) -> metricCalls.incrementAndGet()); + StepVerifier.create(handler(Mono.just(new JsonObject()), identity(), observer).handle(exchange, config("json", 30000), traffic, 1)).verifyComplete(); + AgentMcpTerminalEvent event = observer.only(Outcome.SUCCESS); + assertEquals(method, event.getMethod()); + assertNull(event.getRequestedTool()); + assertEquals(0, metricCalls.get()); + } + + @Test + void unauthenticatedRequestDoesNotConsumeBodyOrTrustMirroredMetadata() { + Recording observer = new Recording(); + AtomicBoolean bodyRead = new AtomicBoolean(); + MockServerWebExchange exchange = MockServerWebExchange.from(builder("tools/call").body(Flux.defer(() -> { + bodyRead.set(true); + return Flux.empty(); + }))); + StepVerifier.create(handler(Mono.never(), ignored -> Mono.empty(), observer).handle(exchange, config("json", 30000), traffic, 1)).verifyComplete(); + AgentMcpTerminalEvent event = observer.only(Outcome.REJECTED); + assertEquals(401, event.getHttpStatus()); + assertNull(event.getSubject()); + assertNull(event.getMethod()); + assertNull(event.getRequestedTool()); + assertNull(event.getProtocolVersion()); + assertFalse(bodyRead.get()); + } + + @Test + void rejectedPreflightNeverResolvesIdentity() { + Recording observer = new Recording(); + AtomicBoolean resolved = new AtomicBoolean(); + MockServerWebExchange exchange = MockServerWebExchange.from(builder("tools/call").header(HttpHeaders.ORIGIN, "https://untrusted.example").body(body("tools/call"))); + StepVerifier.create(handler(Mono.never(), ignored -> { + resolved.set(true); + return identity().resolve(exchange); + }, observer).handle(exchange, config("json", 30000), traffic, 1)).verifyComplete(); + assertEquals(403, observer.only(Outcome.REJECTED).getHttpStatus()); + assertFalse(resolved.get()); + } + + @Test + void malformedBodyRetainsOnlyTrustedSubject() { + Recording observer = new Recording(); + MockServerWebExchange exchange = MockServerWebExchange.from(builder("tools/call").body("{broken")); + StepVerifier.create(handler(Mono.never(), identity(), observer).handle(exchange, config("json", 30000), traffic, 1)).verifyComplete(); + AgentMcpTerminalEvent event = observer.only(Outcome.REJECTED); + assertEquals(400, event.getHttpStatus()); + assertEquals("trusted", event.getSubject()); + assertNull(event.getMethod()); + assertNull(event.getRequestedTool()); + assertNull(event.getProtocolVersion()); + } + + @Test + void authorizationRejectionDoesNotImplyToolExecution() { + Recording observer = new Recording(); + AtomicBoolean invoked = new AtomicBoolean(); + StepVerifier.create(handler(Mono.defer(() -> { + invoked.set(true); + return Mono.just(new JsonObject()); + }), ignored -> Mono.just(new AgentMcpIdentity("trusted", Set.of())), observer) + .handle(exchange("tools/call"), config("json", 30000), traffic, 1)).verifyComplete(); + AgentMcpTerminalEvent event = observer.only(Outcome.REJECTED); + assertEquals(403, event.getHttpStatus()); + assertEquals("read", event.getRequestedTool()); + assertFalse(invoked.get()); + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void deadlinesDuringIdentityResolutionAreTerminalTimeouts(final String mode) { + Recording observer = new Recording(); + AtomicBoolean cancelled = new AtomicBoolean(); + StepVerifier.withVirtualTime(() -> handler(Mono.never(), ignored -> Mono.never().doOnCancel(() -> cancelled.set(true)), observer) + .handle(exchange("tools/call"), config(mode, 1000), traffic, 1)).thenAwait(Duration.ofSeconds(2)).verifyComplete(); + AgentMcpTerminalEvent event = observer.only(Outcome.TIMEOUT); + assertEquals(504, event.getHttpStatus()); + assertNull(event.getSubject()); + assertNull(event.getMethod()); + assertTrue(cancelled.get()); + } + + @ParameterizedTest + @CsvSource({"json,true", "sse,true", "json,false", "sse,false"}) + void recoveredErrorsKeepTheirOriginalClassification(final String mode, final boolean timeout) { + Recording observer = new Recording(); + Throwable error = timeout ? new TimeoutException("private") : new IllegalStateException("private"); + StepVerifier.create(handler(Mono.error(error), identity(), observer).handle(exchange("tools/call"), config(mode, 30000), traffic, 1)).verifyComplete(); + assertEquals(timeout ? 504 : 500, observer.only(timeout ? Outcome.TIMEOUT : Outcome.SERVER_ERROR).getHttpStatus()); + } + + @Test + void explicit504IsClassifiedAsTimeout() { + Recording observer = new Recording(); + StepVerifier.create(handler(Mono.error(new AgentMcpProtocolException(504, -32001, "deadline", null, null)), identity(), observer) + .handle(exchange("tools/call"), config("json", 30000), traffic, 1)).verifyComplete(); + observer.only(Outcome.TIMEOUT); + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void cancellingAStalledWriteIsNotSuccess(final String mode) { + Recording observer = new Recording(); + AtomicBoolean writeStarted = new AtomicBoolean(); + MockServerWebExchange exchange = exchange("tools/call"); + exchange.getResponse().setWriteHandler(buffers -> buffers.doOnNext(DataBufferUtils::release).then(Mono.never().doOnSubscribe(ignored -> writeStarted.set(true)))); + StepVerifier.create(handler(Mono.just(new JsonObject()), identity(), observer).handle(exchange, config(mode, 30000), traffic, 1)) + .then(() -> { + assertTrue(writeStarted.get()); + assertTrue(observer.events.isEmpty()); + }).thenCancel().verify(); + assertEquals(200, observer.only(Outcome.CANCELLED).getHttpStatus()); + } + + @Test + void cancellingAuthenticationHasNoInventedMetadataOrStatus() { + Recording observer = new Recording(); + AtomicBoolean resolving = new AtomicBoolean(); + StepVerifier.create(handler(Mono.never(), ignored -> Mono.never().doOnSubscribe(subscription -> resolving.set(true)), observer) + .handle(exchange("tools/call"), config("json", 30000), traffic, 1)) + .then(() -> assertTrue(resolving.get())).thenCancel().verify(); + AgentMcpTerminalEvent event = observer.only(Outcome.CANCELLED); + assertNull(event.getSubject()); + assertNull(event.getMethod()); + assertNull(event.getHttpStatus()); + } + + @Test + void failedResponseWritingIsNotSuccess() { + Recording observer = new Recording(); + MockServerWebExchange exchange = exchange("tools/call"); + exchange.getResponse().setWriteHandler(buffers -> buffers.doOnNext(DataBufferUtils::release).then(Mono.error(new IllegalStateException("write")))); + StepVerifier.create(handler(Mono.just(new JsonObject()), identity(), observer).handle(exchange, config("json", 30000), traffic, 1)).expectError().verify(); + observer.only(Outcome.SERVER_ERROR); + } + + @Test + void aThrowingSinkDoesNotBreakResponseMetricsOrTracing() { + AtomicInteger metrics = new AtomicInteger(); + AtomicInteger events = new AtomicInteger(); + AgentMcpCallTracer.Trace trace = mock(AgentMcpCallTracer.Trace.class); + when(trace.attach(any())).thenAnswer(invocation -> invocation.getArgument(0)); + MockServerWebExchange exchange = exchange("tools/call"); + exchange.getAttributes().put(Constants.METRICS_AGENT_MCP_CALL, (AgentMcpCallObserver) (outcome, elapsed) -> metrics.incrementAndGet()); + AgentMcpHttpHandler handler = new AgentMcpHttpHandler(dispatcher(Mono.just(new JsonObject())), identity(), ignored -> trace, event -> { + events.incrementAndGet(); + throw new IllegalStateException("sensitive callback exception"); + }); + StepVerifier.create(handler.handle(exchange, config("json", 30000), traffic, 1)).verifyComplete(); + assertEquals(200, exchange.getResponse().getStatusCode().value()); + assertEquals(1, metrics.get()); + assertEquals(1, events.get()); + verify(trace).finish(Outcome.SUCCESS); + } + + @Test + void concurrentRequestsWithIdenticalRpcIdsDoNotShareMetadata() { + Recording observer = new Recording(); + AgentMcpHttpHandler handler = handler(Mono.just(new JsonObject()).delayElement(Duration.ofMillis(1)), + exchange -> Mono.just(new AgentMcpIdentity(exchange.getRequest().getPath().value(), Set.of("read"))), observer); + StepVerifier.create(Flux.range(0, 32).flatMap(index -> handler.handle(MockServerWebExchange.from(MockServerHttpRequest.post("/agent/" + index) + .headers(builder("tools/call").body(body("tools/call")).getHeaders()).body(body("tools/call"))), config("json", 30000), + new AgentTrafficContext("request-" + index, "mcp", "selector", "rule-" + index), index), 32)).verifyComplete(); + await().atMost(Duration.ofSeconds(3)).until(() -> observer.events.size() == 32); + assertEquals(32, observer.events.stream().map(AgentMcpTerminalEvent::getRequestId).distinct().count()); + for (AgentMcpTerminalEvent event : observer.events) { + long index = event.getConfigurationVersion(); + assertEquals("request-" + index, event.getRequestId()); + assertEquals("rule-" + index, event.getRuleId()); + assertEquals("/agent/" + index, event.getSubject()); + assertEquals(Outcome.SUCCESS, event.getOutcome()); + } + } + + @Test + void cancellingOneSubscriptionDoesNotFinishItsSibling() { + Recording cancelled = new Recording(); + Recording successful = new Recording(); + Sinks.One pending = Sinks.one(); + StepVerifier.create(handler(pending.asMono(), identity(), successful).handle(exchange("tools/call"), config("json", 30000), traffic, 1)) + .then(() -> { + AtomicBoolean started = new AtomicBoolean(); + StepVerifier.create(handler(Mono.never().doOnSubscribe(subscription -> started.set(true)), identity(), cancelled) + .handle(exchange("tools/call"), config("json", 30000), traffic, 1)).then(() -> assertTrue(started.get())).thenCancel().verify(); + cancelled.only(Outcome.CANCELLED); + assertTrue(successful.events.isEmpty()); + pending.tryEmitValue(new JsonObject()); + }).verifyComplete(); + successful.only(Outcome.SUCCESS); + } + + @Test + void eachSubscriptionStartsAFreshObservation() { + Recording observer = new Recording(); + AgentMcpHttpHandler handler = handler(Mono.just(new JsonObject()), identity(), observer); + Mono request = Mono.defer(() -> handler.handle(exchange("tools/call"), config("json", 30000), traffic, 1)); + StepVerifier.create(request).verifyComplete(); + StepVerifier.create(request).verifyComplete(); + assertEquals(2, observer.events.size()); + } + + @ParameterizedTest + @ValueSource(strings = {"json", "sse"}) + void realHttpSuccessEmitsOneBodyFreeTerminalEvent(final String mode) throws Exception { + Recording observer = new Recording(); + AgentGatewayMcpConfig config = config(mode, 30000); + AgentTrafficContext requestTraffic = new AgentTrafficContext("http-request", "mcp", "selector", "rule"); + try (TerminalHttpFixture fixture = new TerminalHttpFixture(handler(Mono.just(new JsonObject()), identity(), observer), config, requestTraffic, 1)) { + HttpResponse response = send(fixture); + assertEquals(200, response.statusCode()); + assertTrue(response.body().contains("same-id")); + assertTrue(response.headers().firstValue("Content-Type").orElse("").startsWith( + "sse".equals(mode) ? "text/event-stream" : "application/json")); + AgentMcpTerminalEvent event = observer.only(Outcome.SUCCESS); + assertEquals("http-request", event.getRequestId()); + assertEquals("tools/call", event.getMethod()); + assertEquals("read", event.getRequestedTool()); + assertEquals(200, event.getHttpStatus()); + } + } + + @Test + void realSocketCancellationIsNotSuccess() throws Exception { + Recording cancelled = new Recording(); + AtomicBoolean subscribed = new AtomicBoolean(); + AtomicBoolean toolCancelled = new AtomicBoolean(); + Mono pending = Mono.never().doOnSubscribe(subscription -> subscribed.set(true)).doOnCancel(() -> toolCancelled.set(true)); + AgentGatewayMcpConfig config = config("json", 30000); + AgentTrafficContext cancelledTraffic = new AgentTrafficContext("cancelled", "mcp", "selector", "rule"); + try (TerminalHttpFixture fixture = new TerminalHttpFixture(handler(pending, identity(), cancelled), config, cancelledTraffic, 1)) { + try (Socket socket = new Socket()) { + socket.connect(fixture.address(), 3000); + socket.setSoTimeout(3000); + socket.setSoLinger(true, 0); + String requestBody = body("tools/call"); + socket.getOutputStream().write(("POST /agent HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\n" + + "Accept: application/json, text/event-stream\r\nMCP-Protocol-Version: " + AgentMcpRequestParser.VERSION + + "\r\nMcp-Method: tools/call\r\nMcp-Name: read\r\nContent-Length: " + + requestBody.getBytes(StandardCharsets.UTF_8).length + "\r\n\r\n" + requestBody).getBytes(StandardCharsets.UTF_8)); + socket.getOutputStream().flush(); + await().atMost(Duration.ofSeconds(5)).untilTrue(subscribed); + } + AgentMcpTerminalEvent event = cancelled.only(Outcome.CANCELLED); + assertEquals("cancelled", event.getRequestId()); + assertEquals("trusted", event.getSubject()); + assertEquals("read", event.getRequestedTool()); + await().atMost(Duration.ofSeconds(3)).untilTrue(toolCancelled); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void realHttpIdentityFailureRetainsNoClientMetadata(final boolean timeout) throws Exception { + Recording observer = new Recording(); + AgentMcpSecurityResolver resolver = ignored -> timeout ? Mono.never() : Mono.empty(); + try (TerminalHttpFixture fixture = new TerminalHttpFixture(handler(Mono.just(new JsonObject()), resolver, observer), config("json", 200), traffic, 1)) { + HttpResponse response = send(fixture); + assertEquals(timeout ? 504 : 401, response.statusCode()); + AgentMcpTerminalEvent event = observer.only(timeout ? Outcome.TIMEOUT : Outcome.REJECTED); + assertEquals(response.statusCode(), event.getHttpStatus()); + assertNull(event.getSubject()); + assertNull(event.getMethod()); + assertNull(event.getRequestedTool()); + assertNull(event.getProtocolVersion()); + } + } + + @Test + void lateSignalsCannotAlterOrRepeatAnEvent() { + Recording observer = new Recording(); + AgentMcpTerminalObservation observation = new AgentMcpTerminalObservation(observer, traffic, 1); + observation.identified("original"); + observation.finish(SignalType.CANCEL, null); + observation.identified("late"); + observation.response(false); + observation.failure(new IllegalStateException(), null); + observation.finish(SignalType.ON_COMPLETE, 200); + assertEquals("original", observer.only(Outcome.CANCELLED).getSubject()); + } + + private AgentMcpHttpHandler handler(final Mono action, final AgentMcpSecurityResolver resolver, final AgentMcpTerminalObserver observer) { + return new AgentMcpHttpHandler(dispatcher(action), resolver, null, observer); + } + + private AgentMcpDispatcher dispatcher(final Mono action) { + AgentToolProvider tool = mock(AgentToolProvider.class); + when(tool.getName()).thenReturn("read"); + when(tool.getDescription()).thenReturn("Read test data"); + when(tool.getInputSchema()).thenReturn(JsonParser.parseString("{\"type\":\"object\"}").getAsJsonObject()); + when(tool.getRequiredClientCapabilities()).thenReturn(new JsonObject()); + when(tool.invoke(any())).thenReturn(action); + return new AgentMcpDispatcher(new AgentToolRegistry(List.of(tool)), "test", "1"); + } + + private AgentMcpSecurityResolver identity() { + return ignored -> Mono.just(new AgentMcpIdentity("trusted", Set.of("read"))); + } + + private AgentGatewayMcpConfig config(final String mode, final int timeout) { + return AgentGatewayMcpConfig.parse(JsonParser.parseString("{\"allowedTools\":[\"read\"],\"responseMode\":\"" + mode + + "\",\"timeoutMs\":" + timeout + "}").getAsJsonObject(), true); + } + + private MockServerHttpRequest.BodyBuilder builder(final String method) { + MockServerHttpRequest.BodyBuilder builder = MockServerHttpRequest.post("/agent").contentType(MediaType.APPLICATION_JSON) + .header(HttpHeaders.ACCEPT, "application/json, text/event-stream").header("MCP-Protocol-Version", AgentMcpRequestParser.VERSION).header("Mcp-Method", method); + if ("tools/call".equals(method)) { + builder.header("Mcp-Name", "read"); + } + return builder; + } + + private MockServerWebExchange exchange(final String method) { + return MockServerWebExchange.from(builder(method).body(body(method))); + } + + private String body(final String method) { + return "{\"jsonrpc\":\"2.0\",\"id\":\"same-id\",\"method\":\"" + method + "\",\"params\":{\"name\":\"read\",\"_meta\":{" + + "\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}}}"; + } + + private HttpResponse send(final TerminalHttpFixture fixture) throws Exception { + HttpRequest request = HttpRequest.newBuilder(fixture.uri()).timeout(Duration.ofSeconds(10)) + .header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream") + .header("MCP-Protocol-Version", AgentMcpRequestParser.VERSION) + .header("Mcp-Method", "tools/call").header("Mcp-Name", "read") + .POST(HttpRequest.BodyPublishers.ofString(body("tools/call"), StandardCharsets.UTF_8)).build(); + return HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build().send(request, HttpResponse.BodyHandlers.ofString()); + } + + private static final class TerminalHttpFixture implements AutoCloseable { + + private final DisposableServer server; + + private TerminalHttpFixture(final AgentMcpHttpHandler handler, final AgentGatewayMcpConfig config, + final AgentTrafficContext traffic, final long configurationVersion) { + ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(WebHttpHandlerBuilder + .webHandler(exchange -> handler.handle(exchange, config, traffic, configurationVersion)).build()); + this.server = HttpServer.create().host("127.0.0.1").port(0) + .handle(adapter).bindNow(Duration.ofSeconds(10)); + } + + private java.net.InetSocketAddress address() { + return new java.net.InetSocketAddress("127.0.0.1", server.port()); + } + + private URI uri() { + return URI.create("http://127.0.0.1:" + server.port() + "/agent"); + } + + @Override + public void close() { + server.disposeNow(Duration.ofSeconds(5)); + } + } + + private static final class Recording implements AgentMcpTerminalObserver { + + private final ConcurrentLinkedQueue events = new ConcurrentLinkedQueue<>(); + + @Override + public void record(final AgentMcpTerminalEvent event) { + events.add(event); + } + + private AgentMcpTerminalEvent only(final Outcome outcome) { + await().atMost(Duration.ofSeconds(3)).until(() -> !events.isEmpty()); + assertEquals(1, events.size()); + AgentMcpTerminalEvent event = events.element(); + assertEquals(outcome, event.getOutcome()); + return event; + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientTest.java index e76052a36354..690a2dbbbc7a 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientTest.java @@ -27,6 +27,7 @@ import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; import org.apache.shenyu.common.metrics.AgentMcpCallObserver.Outcome; import org.apache.shenyu.common.metrics.AgentMcpCallObserver; +import org.apache.shenyu.common.tracing.AgentTraceContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpRemoteCatalog; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext; @@ -57,6 +58,7 @@ import java.time.Duration; import java.time.Instant; import java.util.List; +import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -74,6 +76,7 @@ import java.util.function.Consumer; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -82,6 +85,123 @@ class RequestScopedMcpClientTest { private static final Duration WAIT = Duration.ofSeconds(5); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void traceHeadersBelongOnlyToCallsNeverSharedHandshakeOrDiscovery(final boolean sse) throws Exception { + try (Fixture fixture = new Fixture(sse)) { + RequestScopedMcpClient client = fixture.client(); + try { + Map first = traceHeaders(1); + reactor.util.context.Context firstContext = tracedContext(first); + client.initialize().contextWrite(firstContext).block(WAIT); + client.initialize().contextWrite(tracedContext(traceHeaders(2))).block(WAIT); + client.listTools(null).contextWrite(firstContext).block(WAIT); + client.callRaw(new McpSchema.CallToolRequest("lookup", Map.of("token", "first"))).contextWrite(firstContext).block(WAIT); + client.callRaw(new McpSchema.CallToolRequest("lookup", Map.of("token", "second"))) + .contextWrite(tracedContext(traceHeaders(2))).block(WAIT); + client.callRaw(new McpSchema.CallToolRequest("lookup", Map.of("token", "untraced"))) + .contextWrite(context -> context.put(AgentTraceContext.HEADERS_KEY, first)).block(WAIT); + assertEquals(1, fixture.requests.stream().filter(request -> "initialize".equals(request.get("method"))).count()); + assertEquals(1, fixture.requests.stream().filter(request -> "notifications/initialized".equals(request.get("method"))).count()); + for (Map request : fixture.requests) { + String token = request.get("token"); + boolean traced = "first".equals(token) || "second".equals(token); + assertEquals(traced ? "1" : "0", request.get("traceCount")); + assertEquals(traced ? "vendor=opaque" : "", request.get("tracestate")); + assertEquals("first".equals(token) ? first.get("traceparent") + : "second".equals(token) ? traceHeaders(2).get("traceparent") : "", request.get("traceparent")); + assertEquals("", request.get("baggage")); + assertEquals("", request.get("subjectHeader")); + assertEquals("", request.get("cookie")); + assertEquals("Bearer fixed-test-token", request.get("authorization")); + } + } finally { + client.closeGracefully().contextWrite(tracedContext(traceHeaders(1))).block(WAIT); + } + assertFalse(fixture.cleanupHadTrace); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void cancellationDoesNotLeakTraceIntoConcurrentOrLaterPeer(final boolean sse) throws Exception { + try (Fixture fixture = new Fixture(sse)) { + RequestScopedMcpClient client = fixture.client(); + Disposable cancelled = null; + try { + client.initialize().block(WAIT); + cancelled = client.callRaw(new McpSchema.CallToolRequest("lookup", Map.of("token", "cancel-traced", "delay", 600))) + .contextWrite(tracedContext(traceHeaders(1))).subscribe(); + assertTrue(fixture.delayed.await(2, TimeUnit.SECONDS)); + Flux.range(2, 16).flatMap(index -> client.callRaw(new McpSchema.CallToolRequest("lookup", Map.of("token", "trace-" + index))) + .contextWrite(tracedContext(traceHeaders(index))), 16).then().block(Duration.ofSeconds(10)); + cancelled.dispose(); + awaitIdle(client); + client.callRaw(new McpSchema.CallToolRequest("lookup", Map.of("token", "later-untraced"))).block(WAIT); + List> calls = fixture.requests.stream().filter(request -> "tools/call".equals(request.get("method"))).toList(); + assertEquals(18, calls.size()); + for (Map call : calls) { + String token = call.get("token"); + String expected = token.startsWith("trace-") ? traceHeaders(Integer.parseInt(token.substring(6))).get("traceparent") + : "cancel-traced".equals(token) ? traceHeaders(1).get("traceparent") : ""; + assertEquals(expected, call.get("traceparent")); + } + assertEquals(0, fixture.deletes); + } finally { + if (Objects.nonNull(cancelled)) { + cancelled.dispose(); + } + client.closeGracefully().block(WAIT); + } + } + } + + @Test + void traceCarrierSnapshotsRejectInvalidDataAndDropUnrelatedKeys() { + Map mutable = new HashMap<>(traceHeaders(1)); + Map snapshot = AgentTraceContext.headers(mutable); + mutable.put("traceparent", traceHeaders(2).get("traceparent")); + assertEquals(traceHeaders(1).get("traceparent"), snapshot.get("traceparent")); + assertEquals(Set.of("traceparent", "tracestate"), snapshot.keySet()); + assertThrows(UnsupportedOperationException.class, () -> snapshot.put("baggage", "secret")); + assertEquals(Map.of(), AgentTraceContext.headers(null)); + assertEquals(Map.of(), AgentTraceContext.headers("not-a-map")); + assertEquals(Map.of(), AgentTraceContext.headers(Map.of("traceparent", 42))); + for (String invalid : List.of("not-w3c", "00-00000000000000000000000000000000-1111111111111111-01", + "00-11111111111111111111111111111111-0000000000000000-01", traceHeaders(1).get("traceparent") + "\r\nX-Private: secret")) { + assertEquals(Map.of(), AgentTraceContext.headers(Map.of("traceparent", invalid, "tracestate", "vendor=opaque"))); + } + for (String invalid : List.of("vendor=opaque\r\nX-Private: secret", "vendor=one,vendor=two", "UPPER=bad", "vendor=", "vendor=a=b", "a".repeat(513))) { + assertEquals(Map.of("traceparent", traceHeaders(1).get("traceparent")), + AgentTraceContext.headers(Map.of("traceparent", traceHeaders(1).get("traceparent"), "tracestate", invalid))); + } + } + + @Test + void malformedTraceHeadersCannotFailAnOtherwiseValidRemoteCall() throws Exception { + try (Fixture fixture = new Fixture(false)) { + RequestScopedMcpClient client = fixture.client(); + try { + client.initialize().block(WAIT); + client.callRaw(new McpSchema.CallToolRequest("lookup", Map.of("token", "valid"))) + .contextWrite(tracedContext(Map.of("traceparent", "invalid\r\nHeader: secret"))).block(WAIT); + assertTrue(fixture.requests.stream().allMatch(request -> request.get("traceparent").isEmpty())); + } finally { + client.closeGracefully().block(WAIT); + } + } + } + + private static Map traceHeaders(final int index) { + return Map.of("traceparent", String.format("00-%032x-%016x-01", index, index), "tracestate", "vendor=opaque", + "baggage", "subject=private", "X-Spike-Subject", "private", "Authorization", "Bearer agent-secret", "Cookie", "private"); + } + + private static reactor.util.context.Context tracedContext(final Map headers) { + return reactor.util.context.Context.of(AgentTraceContext.HEADERS_KEY, headers, McpTransportContext.KEY, + McpTransportContext.create(Map.of(AgentTraceContext.HEADERS_KEY, headers, "subject", "private", "deadline", Instant.now().plusSeconds(30)))); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void expiredDeadlineIsATimeoutWithoutAnUpstreamRequest(final boolean sse) throws Exception { @@ -383,6 +503,8 @@ private static final class Fixture implements AutoCloseable { private volatile int deletes; + private volatile boolean cleanupHadTrace; + private Fixture(final boolean sse) throws Exception { server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.setExecutor(executor); @@ -394,6 +516,7 @@ private Fixture(final boolean sse) throws Exception { server.createContext("/mcp", exchange -> { try { if ("DELETE".equals(exchange.getRequestMethod())) { + cleanupHadTrace = exchange.getRequestHeaders().containsKey("traceparent") || exchange.getRequestHeaders().containsKey("tracestate"); deletes++; exchange.sendResponseHeaders(deleteStatus, -1); return; @@ -402,7 +525,12 @@ private Fixture(final boolean sse) throws Exception { String method = request.path("method").textValue(); requests.add(Map.of("method", method, "authorization", exchange.getRequestHeaders().getFirst("Authorization"), "subjectHeader", Objects.toString(exchange.getRequestHeaders().getFirst("X-Spike-Subject"), ""), - "cookie", Objects.toString(exchange.getRequestHeaders().getFirst("Cookie"), ""))); + "cookie", Objects.toString(exchange.getRequestHeaders().getFirst("Cookie"), ""), + "traceparent", Objects.toString(exchange.getRequestHeaders().getFirst("traceparent"), ""), + "traceCount", Integer.toString(exchange.getRequestHeaders().getOrDefault("traceparent", List.of()).size()), + "tracestate", Objects.toString(exchange.getRequestHeaders().getFirst("tracestate"), ""), + "baggage", Objects.toString(exchange.getRequestHeaders().getFirst("baggage"), ""), + "token", request.path("params").path("arguments").path("token").asText())); if ("notifications/initialized".equals(method)) { responseBytes.put(request.path("id").asText(), 0); exchange.sendResponseHeaders(202, -1); diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/pom.xml b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/pom.xml index 74ac1bc6e856..c98a429037a4 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/pom.xml +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/pom.xml @@ -26,6 +26,12 @@ shenyu-plugin-ai-proxy + + + io.opentelemetry + opentelemetry-api + true + io.github.agentic-ai-java diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java index 31bcb6d2d4b0..ef4953fa51db 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java @@ -18,16 +18,20 @@ package org.apache.shenyu.plugin.ai.proxy.enhanced; import org.apache.shenyu.common.constant.Constants; +import org.apache.shenyu.common.dto.AgentRequestContext; import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.dto.convert.rule.AiProxyHandle; import org.apache.shenyu.common.enums.PluginEnum; import org.apache.shenyu.common.exception.ShenyuException; +import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.common.metrics.AiRequestObservation; import org.apache.shenyu.plugin.ai.common.config.AiCommonConfig; import org.apache.shenyu.plugin.ai.proxy.enhanced.cache.AiProxyApiKeyCache; import org.apache.shenyu.plugin.ai.proxy.enhanced.handler.AiProxyPluginHandler; import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiProxyException; import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamResponse; +import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiObservationSupport; import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiProxyConfigService; import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiProxyEngine; import org.apache.shenyu.plugin.ai.proxy.enhanced.transport.AiTransportException; @@ -71,14 +75,41 @@ public class AiProxyPlugin extends AbstractShenyuPlugin { private final AiProxyPluginHandler aiProxyPluginHandler; + private final AiCallObserver observer; + public AiProxyPlugin(final AiProxyConfigService aiProxyConfigService, final AiProxyEngine aiProxyEngine, final AiProxyPluginHandler aiProxyPluginHandler) { + this(aiProxyConfigService, aiProxyEngine, aiProxyPluginHandler, null); + } + + public AiProxyPlugin(final AiProxyConfigService aiProxyConfigService, final AiProxyEngine aiProxyEngine, + final AiProxyPluginHandler aiProxyPluginHandler, final AiCallObserver observer) { this.aiProxyConfigService = aiProxyConfigService; this.aiProxyEngine = aiProxyEngine; this.aiProxyPluginHandler = aiProxyPluginHandler; + this.observer = observer; } @Override protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { + return Mono.deferContextual(view -> { + AiRequestObservation inherited = view.getOrDefault(AiRequestObservation.REACTOR_KEY, null); + AiRequestObservation observation = Objects.nonNull(inherited) ? inherited + : new AiRequestObservation(observer, AiObservationSupport.context(view, selector.getId(), rule.getId())); + return executeRequest(exchange, selector) + .doOnError(error -> observation.failure(AiObservationSupport.outcome(error))) + .onErrorResume(error -> handleFailure(exchange.getResponse(), error)) + .doOnError(observation::error) + .doFinally(signal -> { + if (Objects.isNull(inherited)) { + HttpStatusCode status = exchange.getResponse().getStatusCode(); + observation.finish(signal, Objects.isNull(status) ? null : status.value()); + } + }).contextWrite(context -> context.put(AiRequestObservation.REACTOR_KEY, observation) + .put(AgentRequestContext.REACTOR_KEY, observation.getContext())); + }); + } + + private Mono executeRequest(final ServerWebExchange exchange, final SelectorData selector) { return Mono.defer(() -> { AiProxyHandle handle = aiProxyPluginHandler.getSelectorCachedHandle() .obtainHandle(CacheKeyUtils.INST.getKey(selector.getId(), Constants.DEFAULT_RULE)); @@ -106,7 +137,7 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu .or(() -> aiProxyConfigService.resolveAdminFallbackConfig(config, handle)); return aiProxyEngine.execute(body, config, fallback, response -> writeResponse(exchange.getResponse(), response)); }); - }).onErrorResume(error -> handleFailure(exchange.getResponse(), error)); + }); } private Mono writeResponse(final ServerHttpResponse response, final AiUpstreamResponse upstream) { diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiObservationSupport.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiObservationSupport.java new file mode 100644 index 000000000000..5ffe3bc0bb8a --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiObservationSupport.java @@ -0,0 +1,72 @@ +/* + * 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.plugin.ai.proxy.enhanced.service; + +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.exception.ShenyuException; +import org.apache.shenyu.common.metrics.AiCallOutcome; +import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiProxyException; +import org.apache.shenyu.plugin.ai.proxy.enhanced.transport.AiTransportException; +import org.springframework.core.io.buffer.DataBufferLimitException; +import reactor.util.context.ContextView; + +import java.util.UUID; +import java.util.concurrent.TimeoutException; + +/** + * Body-free context resolution and bounded failure classification for AI layers. + */ +public final class AiObservationSupport { + + private AiObservationSupport() { + } + + /** + * Resolve only subscription context; never recover identities from exchange attributes or headers. + * @param view Reactor context + * @param selectorId matched AI selector for standalone requests + * @param ruleId matched AI rule for standalone requests + * @return existing authoritative context or an anonymous standalone request + */ + public static AgentRequestContext context(final ContextView view, final String selectorId, final String ruleId) { + Object value = view.getOrDefault(AgentRequestContext.REACTOR_KEY, null); + return value instanceof AgentRequestContext context ? context : new AgentRequestContext(UUID.randomUUID().toString(), "llm", selectorId, ruleId); + } + + /** + * Convert implementation errors without storing messages or causes in events. + * @param error actual pipeline failure + * @return bounded classification + */ + public static AiCallOutcome outcome(final Throwable error) { + if (error instanceof TimeoutException) { + return AiCallOutcome.TIMEOUT; + } + if (error instanceof AiTransportException transport) { + return switch (transport.getKind()) { + case CONNECT_TIMEOUT, RESPONSE_HEADER_TIMEOUT, STREAM_IDLE_TIMEOUT, STREAM_DURATION_TIMEOUT -> AiCallOutcome.TIMEOUT; + default -> AiCallOutcome.ERROR; + }; + } + if (error instanceof ShenyuException || error instanceof DataBufferLimitException + || error instanceof AiProxyException proxy && proxy.getKind() == AiProxyException.Kind.REQUEST) { + return AiCallOutcome.REJECTED; + } + return AiCallOutcome.ERROR; + } +} diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java index e146623e0699..a7c81045ff8f 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java @@ -22,7 +22,11 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.shenyu.common.dto.AgentRequestContext; import org.apache.shenyu.common.exception.ShenyuException; +import org.apache.shenyu.common.metrics.AiAttemptEvent; +import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.common.metrics.AiRequestObservation; import org.apache.shenyu.plugin.ai.common.config.AiCommonConfig; import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiProxyException; import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamRequest; @@ -36,11 +40,13 @@ import org.apache.shenyu.plugin.ai.proxy.enhanced.transport.AiTransportException; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; import java.time.Duration; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; /** @@ -58,16 +64,24 @@ public final class AiProxyEngine { private final Duration retryBackoff; + private final AiCallObserver observer; + public AiProxyEngine(final AiProxyProtocolFactory protocols, final AiProxyProviderFactory providers, final AiProxyTransport transport) { this(protocols, providers, transport, Duration.ofSeconds(1)); } public AiProxyEngine(final AiProxyProtocolFactory protocols, final AiProxyProviderFactory providers, final AiProxyTransport transport, final Duration retryBackoff) { + this(protocols, providers, transport, retryBackoff, null); + } + + public AiProxyEngine(final AiProxyProtocolFactory protocols, final AiProxyProviderFactory providers, + final AiProxyTransport transport, final Duration retryBackoff, final AiCallObserver observer) { this.aiProxyProtocolFactory = protocols; this.aiProxyProviderFactory = providers; this.aiProxyTransport = transport; this.retryBackoff = retryBackoff; + this.observer = observer; } /** @@ -83,16 +97,31 @@ public AiProxyEngine(final AiProxyProtocolFactory protocols, final AiProxyProvid public Mono execute(final String requestBody, final AiCommonConfig primaryConfig, final Optional fallbackConfig, final Function> responseConsumer) { - return Mono.defer(() -> { - PreparedExchange primary = prepare(requestBody, new AiCommonConfig(primaryConfig)); - Optional fallback = fallbackConfig.map(config -> { - AiCommonConfig copy = new AiCommonConfig(config); - copy.setStream(primary.stream()); - // Fallback changes the upstream, never the already selected client protocol. - copy.setProtocol(primary.protocol().name()); - return copy; - }); - return attempt(requestBody, primary, fallback, primary.stream() ? 1 : 3, responseConsumer, new AtomicBoolean()); + return Mono.deferContextual(view -> { + AiRequestObservation inherited = view.getOrDefault(AiRequestObservation.REACTOR_KEY, null); + AiRequestObservation observation = Objects.nonNull(inherited) ? inherited + : new AiRequestObservation(observer, AiObservationSupport.context(view, null, null)); + AtomicReference status = new AtomicReference<>(); + return Mono.defer(() -> { + PreparedExchange primary = prepare(requestBody, new AiCommonConfig(primaryConfig)); + Optional fallback = fallbackConfig.map(config -> { + AiCommonConfig copy = new AiCommonConfig(config); + copy.setStream(primary.stream()); + // Fallback changes the upstream, never the already selected client protocol. + copy.setProtocol(primary.protocol().name()); + return copy; + }); + return attempt(requestBody, primary, fallback, primary.stream() ? 1 : 3, response -> { + status.set(response.getStatusCode()); + return responseConsumer.apply(response); + }, new AtomicBoolean(), observation, AiAttemptEvent.Kind.PRIMARY); + }).doOnError(error -> observation.failure(AiObservationSupport.outcome(error))) + .doFinally(signal -> { + if (Objects.isNull(inherited)) { + observation.finish(signal, status.get()); + } + }).contextWrite(context -> context.put(AiRequestObservation.REACTOR_KEY, observation) + .put(AgentRequestContext.REACTOR_KEY, observation.getContext())); }); } @@ -109,15 +138,49 @@ public AiUpstreamRequest buildRequest(final String requestBody, final AiCommonCo private Mono attempt(final String requestBody, final PreparedExchange prepared, final Optional fallback, final int retries, - final Function> consumer, final AtomicBoolean emitted) { + final Function> consumer, final AtomicBoolean emitted, + final AiRequestObservation observation, final AiAttemptEvent.Kind kind) { + return Mono.defer(() -> { + // A configured protocol identifier is not a negotiated protocol version. + AgentRequestContext target = observation.getContext().withTarget(prepared.target(), prepared.operation(), null); + AiRequestObservation.Attempt attempt = observation.startAttempt(target, kind, prepared.provider().name(), prepared.protocol().name(), prepared.stream()); + return exchange(prepared, fallback, retries, consumer, emitted, attempt) + .doOnSuccess(ignored -> attempt.finish(SignalType.ON_COMPLETE, null)) + .doOnError(error -> attempt.finish(SignalType.ON_ERROR, error instanceof UpstreamStatusFailure ? null : AiObservationSupport.outcome(error))) + .doOnCancel(() -> attempt.finish(SignalType.CANCEL, null)) + .contextWrite(context -> context.put(AgentRequestContext.REACTOR_KEY, target)); + }).onErrorResume(error -> { + boolean transportFailure = error instanceof AiTransportException + || error instanceof AiProxyException + && ((AiProxyException) error).getKind() == AiProxyException.Kind.TRANSPORT; + boolean statusFailure = error instanceof UpstreamStatusFailure; + if (emitted.get() || !(transportFailure || statusFailure)) { + return Mono.error(error); + } + boolean retryable = transportFailure || retryableStatus(((UpstreamStatusFailure) error).status); + if (retryable && retries > 0) { + Duration delay = prepared.stream() ? Duration.ZERO : retryBackoff.multipliedBy(1L << (3 - retries)); + return Mono.delay(delay).then(attempt(requestBody, prepared, fallback, retries - 1, consumer, emitted, observation, AiAttemptEvent.Kind.RETRY)); + } + if (fallback.isPresent()) { + return Mono.defer(() -> attempt(requestBody, prepare(requestBody, fallback.get()), Optional.empty(), 0, consumer, emitted, observation, AiAttemptEvent.Kind.FALLBACK)); + } + return Mono.error(error); + }); + } + + private Mono exchange(final PreparedExchange prepared, final Optional fallback, final int retries, + final Function> consumer, final AtomicBoolean emitted, final AiRequestObservation.Attempt attempt) { return Mono.defer(() -> aiProxyTransport.execute(prepared.request())) .flatMap(response -> { int status = response.getStatusCode(); + attempt.status(status); + AiUpstreamResponse observed = new AiUpstreamUsageTap(attempt, response.getHeaders(), prepared.stream()).attach(response); if (status >= 400 && ((retryableStatus(status) && retries > 0) || fallback.isPresent())) { // Release this response without accumulating the error body before another attempt. - return response.getBody().then(Mono.error(new UpstreamStatusFailure(status))); + return observed.getBody().then(Mono.error(new UpstreamStatusFailure(status))); } - AiUpstreamResponse adapted = prepared.request().adaptResponse(prepared.provider().adaptResponse(response)); + AiUpstreamResponse adapted = prepared.request().adaptResponse(prepared.provider().adaptResponse(observed)); AiUpstreamResponse encoded = prepared.protocol().encodeResponse(adapted, prepared.stream()); return encoded.getBody().switchOnFirst((signal, body) -> { if (signal.isOnError()) { @@ -127,24 +190,6 @@ private Mono attempt(final String requestBody, final PreparedExchange prep body.doOnNext(bytes -> emitted.set(true))); return Mono.defer(() -> consumer.apply(ready)).flux(); }).then(); - }) - .onErrorResume(error -> { - boolean transportFailure = error instanceof AiTransportException - || error instanceof AiProxyException - && ((AiProxyException) error).getKind() == AiProxyException.Kind.TRANSPORT; - boolean statusFailure = error instanceof UpstreamStatusFailure; - if (emitted.get() || !(transportFailure || statusFailure)) { - return Mono.error(error); - } - boolean retryable = transportFailure || retryableStatus(((UpstreamStatusFailure) error).status); - if (retryable && retries > 0) { - Duration delay = prepared.stream() ? Duration.ZERO : retryBackoff.multipliedBy(1L << (3 - retries)); - return Mono.delay(delay).then(attempt(requestBody, prepared, fallback, retries - 1, consumer, emitted)); - } - if (fallback.isPresent()) { - return Mono.defer(() -> attempt(requestBody, prepare(requestBody, fallback.get()), Optional.empty(), 0, consumer, emitted)); - } - return Mono.error(error); }); } @@ -186,13 +231,25 @@ private PreparedExchange prepare(final String requestBody, final AiCommonConfig provider.capabilities().validate(decoded, stream); try { AiUpstreamRequest request = provider.buildRequest(decoded, config); - return new PreparedExchange(protocol, provider, request, stream); + return new PreparedExchange(protocol, provider, request, stream, selectedModel(request), decoded.getOperation().name()); } catch (IllegalArgumentException error) { throw new AiProxyException(AiProxyException.Kind.PROVIDER, "Invalid AI provider configuration", error); } } - private record PreparedExchange(AiProxyProtocol protocol, AiProxyProvider provider, AiUpstreamRequest request, boolean stream) { + private String selectedModel(final AiUpstreamRequest request) { + // Only inspect the already constructed upstream request, not a second subscription to either HTTP body. + // A custom provider may use a non-JSON body; no target is fabricated in that case. + try { + JsonNode payload = OBJECT_MAPPER.readTree(request.getBody()); + JsonNode model = Objects.isNull(payload) ? null : payload.get("model"); + return Objects.nonNull(model) && model.isTextual() ? model.textValue() : null; + } catch (Exception ignored) { + return null; + } + } + + private record PreparedExchange(AiProxyProtocol protocol, AiProxyProvider provider, AiUpstreamRequest request, boolean stream, String target, String operation) { } private static final class UpstreamStatusFailure extends RuntimeException { diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiUpstreamUsageTap.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiUpstreamUsageTap.java new file mode 100644 index 000000000000..0dc91db5223c --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiUpstreamUsageTap.java @@ -0,0 +1,202 @@ +/* + * 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.plugin.ai.proxy.enhanced.service; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.shenyu.common.metrics.AiRequestObservation; +import org.apache.shenyu.common.metrics.AiUsage; +import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamResponse; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; + +/** + * Bounded raw upstream side tap. Never subscribes, changes bytes, estimates tokens, + * logs payloads or treats protocol-conversion defaults as provider-reported usage. + */ +final class AiUpstreamUsageTap { + + static final int MAX_BYTES = 64 * 1024; + + private static final ObjectMapper MAPPER = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + private final AiRequestObservation.Attempt observation; + + private final boolean streaming; + + private final ByteArrayOutputStream line = new ByteArrayOutputStream(); + + private final StringBuilder event = new StringBuilder(); + + private boolean carriageReturn; + + private boolean stopped; + + private int eventBytes; + + AiUpstreamUsageTap(final AiRequestObservation.Attempt observation, final Map> headers, final boolean stream) { + this.observation = observation; + String contentType = header(headers, "Content-Type").toLowerCase(Locale.ROOT).split(";", 2)[0].trim(); + streaming = contentType.isEmpty() ? stream : "text/event-stream".equals(contentType); + String encoding = header(headers, "Content-Encoding"); + if (!encoding.isEmpty() && !"identity".equalsIgnoreCase(encoding) + || !contentType.isEmpty() && !"text/event-stream".equals(contentType) && !"application/json".equals(contentType) && !contentType.endsWith("+json")) { + unavailable(AiUsage.Status.UNSUPPORTED); + } + } + + AiUpstreamResponse attach(final AiUpstreamResponse response) { + return new AiUpstreamResponse(response.getStatusCode(), response.getHeaders(), response.getBody() + .doOnNext(this::accept).doOnComplete(this::complete).doFinally(ignored -> clear())); + } + + synchronized void accept(final byte[] bytes) { + if (stopped) { + return; + } + try { + if (!streaming) { + if (bytes.length > MAX_BYTES - line.size()) { + unavailable(AiUsage.Status.LIMIT_EXCEEDED); + } else { + line.writeBytes(bytes); + } + return; + } + for (byte value : bytes) { + if (stopped) { + break; + } + if (carriageReturn && value == '\n') { + carriageReturn = false; + continue; + } + carriageReturn = false; + if (++eventBytes > MAX_BYTES) { + unavailable(AiUsage.Status.LIMIT_EXCEEDED); + break; + } + if (value == '\r' || value == '\n') { + readLine(); + carriageReturn = value == '\r'; + } else { + line.write(value); + } + } + } catch (Exception ignored) { + unavailable(AiUsage.Status.INVALID); + } + } + + private void readLine() throws java.io.IOException { + String text = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(line.toByteArray())).toString(); + line.reset(); + if (text.isEmpty()) { + dispatch(); + eventBytes = 0; + } else if ("data".equals(text) || text.startsWith("data:")) { + String value = "data".equals(text) ? "" : text.substring(5); + event.append(value.startsWith(" ") ? value.substring(1) : value).append('\n'); + } + } + + private void dispatch() throws java.io.IOException { + if (event.isEmpty()) { + return; + } + String payload = event.substring(0, event.length() - 1); + event.setLength(0); + if ("[DONE]".equals(payload)) { + stopped = true; + } else { + capture(MAPPER.readTree(payload)); + } + } + + synchronized void complete() { + if (stopped) { + return; + } + try { + if (!streaming && line.size() > 0) { + capture(MAPPER.readTree(line.toByteArray())); + } + } catch (Exception ignored) { + unavailable(AiUsage.Status.INVALID); + } finally { + clear(); + } + } + + private void capture(final JsonNode root) { + if (Objects.isNull(root) || !root.isObject()) { + unavailable(AiUsage.Status.INVALID); + return; + } + JsonNode usage = root.get("usage"); + if (Objects.isNull(usage) || usage.isNull()) { + return; + } + if (!usage.isObject()) { + observation.usage(new AiUsage(null, null, null, AiUsage.Status.INVALID)); + return; + } + Long prompt = count(usage.get("prompt_tokens")); + Long completion = count(usage.get("completion_tokens")); + Long total = count(usage.get("total_tokens")); + AiUsage.Status quality = invalid(usage.get("prompt_tokens")) || invalid(usage.get("completion_tokens")) || invalid(usage.get("total_tokens")) + ? AiUsage.Status.INVALID : Objects.isNull(prompt) && Objects.isNull(completion) && Objects.isNull(total) ? AiUsage.Status.UNKNOWN : AiUsage.Status.REPORTED; + // Replace the snapshot, never sum cumulative SSE counters or fill fields from an older event. + observation.usage(quality == AiUsage.Status.INVALID ? new AiUsage(null, null, null, quality) : new AiUsage(prompt, completion, total, quality)); + } + + private Long count(final JsonNode node) { + return Objects.nonNull(node) && node.isIntegralNumber() && node.canConvertToLong() && node.longValue() >= 0 ? node.longValue() : null; + } + + private boolean invalid(final JsonNode node) { + return Objects.nonNull(node) && !node.isNull() && Objects.isNull(count(node)); + } + + private void unavailable(final AiUsage.Status status) { + observation.usage(new AiUsage(null, null, null, status)); + clear(); + } + + private synchronized void clear() { + stopped = true; + line.reset(); + event.setLength(0); + } + + private String header(final Map> headers, final String key) { + return headers.entrySet().stream().filter(entry -> key.equalsIgnoreCase(entry.getKey())) + .flatMap(entry -> entry.getValue().stream()).findFirst().orElse(""); + } +} diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/AiOutboundTraceContext.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/AiOutboundTraceContext.java new file mode 100644 index 000000000000..471121a796ff --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/AiOutboundTraceContext.java @@ -0,0 +1,55 @@ +/* + * 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.plugin.ai.proxy.enhanced.transport; + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.context.Context; +import org.apache.shenyu.common.tracing.AgentTraceContext; +import reactor.util.context.ContextView; + +import java.util.HashMap; +import java.util.Map; + +/** + * Optional OTel API bridge using explicit Reactor parents only, never ambient context. + */ +final class AiOutboundTraceContext { + + private AiOutboundTraceContext() { + } + + static Map headers(final ContextView view) { + try { + Object parent = view.getOrDefault(AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY, null); + if (!(parent instanceof Context context) || !Span.fromContext(context).getSpanContext().isValid()) { + parent = view.getOrDefault(Context.class, null); + } + if (!(parent instanceof Context context) || !Span.fromContext(context).getSpanContext().isValid()) { + return Map.of(); + } + Context isolated = Context.root().with(Span.wrap(Span.fromContext(context).getSpanContext())); + Map carrier = new HashMap<>(); + W3CTraceContextPropagator.getInstance().inject(isolated, carrier, Map::put); + return AgentTraceContext.headers(carrier); + } catch (RuntimeException ignored) { + // Invalid diagnostic context cannot fail the business request. + return Map.of(); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/WebClientAiProxyTransport.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/WebClientAiProxyTransport.java index 06be8f997f01..08e2940c4e3b 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/WebClientAiProxyTransport.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/WebClientAiProxyTransport.java @@ -24,6 +24,7 @@ import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; +import org.springframework.util.ClassUtils; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -33,6 +34,7 @@ import java.io.IOException; import java.net.UnknownHostException; import java.time.Duration; +import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; @@ -43,6 +45,9 @@ */ public final class WebClientAiProxyTransport implements AiProxyTransport { + private static final boolean OTEL_AVAILABLE = ClassUtils.isPresent( + "io.opentelemetry.api.trace.Span", WebClientAiProxyTransport.class.getClassLoader()); + private final WebClient webClient; private final Duration responseHeaderTimeout; @@ -69,7 +74,11 @@ public WebClientAiProxyTransport(final WebClient webClient) { * @param properties transport properties */ public WebClientAiProxyTransport(final WebClient webClient, final AiProxyTransportProperties properties) { - this.webClient = Objects.requireNonNull(webClient, "webClient must not be null"); + this.webClient = Objects.requireNonNull(webClient, "webClient must not be null").mutate().defaultHeaders(headers -> { + headers.remove("traceparent"); + headers.remove("tracestate"); + headers.remove("baggage"); + }).build(); Objects.requireNonNull(properties, "properties must not be null"); this.responseHeaderTimeout = AiProxyTransportProperties.requirePositive( properties.getResponseHeaderTimeout(), "responseHeaderTimeout"); @@ -83,15 +92,20 @@ public WebClientAiProxyTransport(final WebClient webClient, final AiProxyTranspo @Override public Mono execute(final AiUpstreamRequest request) { - return Mono.defer(() -> exchange(request)); + return Mono.deferContextual(context -> exchange(request, OTEL_AVAILABLE ? AiOutboundTraceContext.headers(context) : Map.of())); } - private Mono exchange(final AiUpstreamRequest request) { + private Mono exchange(final AiUpstreamRequest request, final Map trace) { final WebClient.RequestBodySpec bodySpec = webClient .method(HttpMethod.valueOf(request.getMethod())) .uri(request.getUri()) .headers(headers -> { request.getHeaders().forEach(headers::put); + // Never forward configured or client-carried stale telemetry. + headers.remove("traceparent"); + headers.remove("tracestate"); + headers.remove("baggage"); + trace.forEach(headers::set); }); WebClient.RequestHeadersSpec headersSpec = bodySpec; if (Objects.nonNull(request.getBody()) && request.getBody().length > 0) { diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPluginTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPluginTest.java index bda2653b1f2b..97f20b61749d 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPluginTest.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPluginTest.java @@ -20,11 +20,17 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.shenyu.common.constant.Constants; +import org.apache.shenyu.common.dto.AgentRequestContext; import org.apache.shenyu.common.dto.ProxyApiKeyData; import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.dto.convert.rule.AiProxyHandle; import org.apache.shenyu.common.enums.PluginEnum; +import org.apache.shenyu.common.metrics.AiAttemptEvent; +import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.common.metrics.AiCallOutcome; +import org.apache.shenyu.common.metrics.AiRequestObservation; +import org.apache.shenyu.common.metrics.AiTerminalEvent; import org.apache.shenyu.plugin.ai.proxy.enhanced.cache.AiProxyApiKeyCache; import org.apache.shenyu.plugin.ai.proxy.enhanced.handler.AiProxyPluginHandler; import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamRequest; @@ -50,6 +56,7 @@ import org.springframework.mock.web.server.MockServerWebExchange; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; import reactor.test.StepVerifier; import java.nio.charset.StandardCharsets; @@ -61,6 +68,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -276,14 +285,104 @@ void testGetOrderAndNamed() { assertEquals(PluginEnum.AI_PROXY.getName(), plugin.named()); } + @Test + void standaloneSubscriptionsRemainAnonymousAndCannotRestoreExchangeIdentity() { + final List events = new ArrayList<>(); + final AiProxyPlugin plugin = plugin(request -> Mono.just(response(200, "{}")), events::add); + final Mono execution = Mono.defer(() -> { + // Each HTTP request owns its response; a committed response cannot be written twice. + final MockServerWebExchange current = MockServerWebExchange.from(MockServerHttpRequest.post("/test").body(REQUEST_BODY)); + current.getAttributes().put(AgentRequestContext.EXCHANGE_ATTRIBUTE, + new AgentRequestContext("forged", "llm", null, null).withIdentity("forged-tenant", "forged-subject")); + return plugin.doExecute(current, ignored -> Mono.empty(), selector, rule); + }); + execution.block(); + execution.block(); + assertEquals(2, events.size()); + assertNull(events.get(0).context().getTenant()); + assertNull(events.get(0).context().getSubject()); + assertNull(events.get(1).context().getTenant()); + assertNull(events.get(1).context().getSubject()); + assertNotEquals("forged", events.get(0).context().getRequestId()); + assertNotEquals(events.get(0).context().getRequestId(), events.get(1).context().getRequestId()); + } + + @Test + void gatewayStateIsReusedWithoutDoubleTerminalEmission() { + final List events = new ArrayList<>(); + final AiRequestObservation owner = new AiRequestObservation(events::add, + new AgentRequestContext("gateway", "llm", "selector", "rule").withIdentity("tenant", "subject")); + execute(plugin(request -> Mono.just(response(200, "{}")), event -> { + throw new AssertionError("proxy must not publish a second logical event"); + })).contextWrite(context -> context.put(AiRequestObservation.REACTOR_KEY, owner)).block(); + assertTrue(events.isEmpty()); + owner.finish(SignalType.ON_COMPLETE, 200); + assertEquals(1, events.size()); + assertEquals("subject", events.get(0).context().getSubject()); + assertEquals(1, events.get(0).attemptCount()); + } + + @Test + void preExecutionApiKeyRejectionHasZeroAttempts() { + final List events = new ArrayList<>(); + handle.setProxyEnabled("true"); + execute(plugin(request -> Mono.error(new AssertionError("must not call upstream")), events::add)).block(); + assertEquals(1, events.size()); + assertEquals(401, events.get(0).httpStatus()); + assertEquals(0, events.get(0).attemptCount()); + assertEquals(AiCallOutcome.REJECTED, events.get(0).outcome()); + } + + @ParameterizedTest + @ValueSource(ints = {200, 400, 401, 429, 504}) + void responseWriteFailureOverridesSuccessfulOrErrorHttpStatus(final int status) { + final List events = new ArrayList<>(); + final List attempts = new ArrayList<>(); + final AiCallObserver observer = new AiCallObserver() { + @Override + public void record(final AiTerminalEvent event) { + events.add(event); + } + + @Override + public void recordAttempt(final AiAttemptEvent event) { + attempts.add(event); + } + }; + exchange.getResponse().setWriteHandler(body -> body.doOnNext(DataBufferUtils::release).then(Mono.error(new IllegalStateException("write failed")))); + StepVerifier.withVirtualTime(() -> execute(plugin(request -> Mono.just(response(status, "{}")), observer))) + .thenAwait(Duration.ofSeconds(1)).expectError(IllegalStateException.class).verify(); + assertEquals(1, events.size()); + assertEquals(AiCallOutcome.ERROR, events.get(0).outcome()); + assertEquals(status, events.get(0).httpStatus()); + assertEquals(AiCallOutcome.ERROR, attempts.get(attempts.size() - 1).outcome()); + } + + @ParameterizedTest + @ValueSource(ints = {200, 400, 429, 504}) + void cancellationOfResponseWriteWinsOverAssignedStatus(final int status) { + final List events = new ArrayList<>(); + final AtomicBoolean writing = new AtomicBoolean(); + exchange.getResponse().setWriteHandler(body -> body.doOnNext(DataBufferUtils::release).then(Mono.never()) + .doOnSubscribe(ignored -> writing.set(true))); + StepVerifier.withVirtualTime(() -> execute(plugin(request -> Mono.just(response(status, "{}")), events::add))) + .thenAwait(Duration.ofSeconds(1)).then(() -> assertTrue(writing.get())).thenCancel().verify(); + assertEquals(1, events.size()); + assertEquals(AiCallOutcome.CANCELLED, events.get(0).outcome()); + } + private AiProxyPlugin plugin(final AiProxyTransport transport) { + return plugin(transport, null); + } + + private AiProxyPlugin plugin(final AiProxyTransport transport, final AiCallObserver observer) { handler.getSelectorCachedHandle().cachedHandle(CacheKeyUtils.INST.getKey(SELECTOR_ID, Constants.DEFAULT_RULE), handle); AiProxyEngine engine = new AiProxyEngine(new AiProxyProtocolFactory(List.of(new OpenAiChat())), new AiProxyProviderFactory(List.of(new OpenAi(), new OpenAiCompatible("DeepSeek"))), request -> { requests.add(request); return transport.execute(request); - }, Duration.ZERO); - return new AiProxyPlugin(new AiProxyConfigService(), engine, handler); + }, Duration.ZERO, observer); + return new AiProxyPlugin(new AiProxyConfigService(), engine, handler, observer); } private Mono execute(final AiProxyPlugin plugin) { diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java index b6746a82cab2..2432e3b4162a 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java @@ -46,6 +46,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -275,7 +276,7 @@ void cancellationDuringFallbackReachesOnlyTheActiveBody() { StepVerifier.create(engine.execute(BODY, config(true, "main"), Optional.of(config(true, "fallback")), response -> response.getBody().then())) .thenAwait(Duration.ofMillis(30)).thenCancel().verify(Duration.ofSeconds(3)); assertEquals(3, calls.get()); - assertTrue(cancelled.get()); + await().atMost(Duration.ofSeconds(5)).untilTrue(cancelled); } private AiProxyEngine engine(final AiProxyTransport transport) { diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyObservationTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyObservationTest.java new file mode 100644 index 000000000000..5f474c289054 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyObservationTest.java @@ -0,0 +1,243 @@ +/* + * 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.plugin.ai.proxy.enhanced.service; + +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.metrics.AiAttemptEvent; +import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.common.metrics.AiCallOutcome; +import org.apache.shenyu.common.metrics.AiRequestObservation; +import org.apache.shenyu.common.metrics.AiTerminalEvent; +import org.apache.shenyu.common.metrics.AiUsage; +import org.apache.shenyu.plugin.ai.common.config.AiCommonConfig; +import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamResponse; +import org.apache.shenyu.plugin.ai.proxy.enhanced.protocol.AiProxyProtocolFactory; +import org.apache.shenyu.plugin.ai.proxy.enhanced.protocol.OpenAiChat; +import org.apache.shenyu.plugin.ai.proxy.enhanced.protocol.OpenAiResponses; +import org.apache.shenyu.plugin.ai.proxy.enhanced.provider.AiProxyProviderFactory; +import org.apache.shenyu.plugin.ai.proxy.enhanced.provider.OpenAi; +import org.apache.shenyu.plugin.ai.proxy.enhanced.transport.AiProxyTransport; +import org.apache.shenyu.plugin.ai.proxy.enhanced.transport.AiTransportException; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; +import reactor.test.StepVerifier; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AiProxyObservationTest { + + private static final String BODY = "{\"messages\":[{\"role\":\"user\",\"content\":\"hello\"}]}"; + + @Test + void recordsFourPrimaryAttemptsThenFallbackAndOnlyItsUsageAtLogicalEnd() throws InterruptedException { + final Sink sink = new Sink(); + final AtomicInteger calls = new AtomicInteger(); + final AtomicInteger subscriptions = new AtomicInteger(); + final AiProxyEngine engine = engine(request -> Mono.just(response(calls.incrementAndGet() <= 4 ? 429 : 200, Flux.defer(() -> { + subscriptions.incrementAndGet(); + return Flux.just(bytes("{\"choices\":[],\"usage\":{\"prompt_tokens\":" + calls.get() + "}}")); + }))), sink); + engine.execute(BODY, config(false, "primary"), Optional.of(config(false, "fallback")), result -> result.getBody().then()).block(); + assertTrue(sink.finished.await(5, TimeUnit.SECONDS)); + assertEquals(5, calls.get()); + assertEquals(5, subscriptions.get()); + assertEquals(List.of(AiAttemptEvent.Kind.PRIMARY, AiAttemptEvent.Kind.RETRY, AiAttemptEvent.Kind.RETRY, + AiAttemptEvent.Kind.RETRY, AiAttemptEvent.Kind.FALLBACK), sink.attempts.stream().map(AiAttemptEvent::kind).toList()); + assertEquals(List.of(1, 2, 3, 4, 5), sink.attempts.stream().map(AiAttemptEvent::attemptNumber).toList()); + assertEquals(AiCallOutcome.RATE_LIMITED, sink.attempts.get(0).outcome()); + assertEquals(1L, sink.attempts.get(0).usage().promptTokens()); + assertEquals(1, sink.events.size()); + assertEquals(5L, sink.events.get(0).usage().promptTokens()); + assertNull(sink.events.get(0).usage().totalTokens()); + assertEquals("fallback", sink.events.get(0).context().getTarget()); + assertEquals(AiCallOutcome.SUCCESS, sink.events.get(0).outcome()); + assertEquals(1, sink.attempts.stream().map(event -> event.context().getRequestId()).distinct().count()); + } + + @Test + void inheritedGatewayOwnerAloneFinishesLogicalRequest() { + final Sink sink = new Sink(); + final AgentRequestContext base = new AgentRequestContext("trusted-request", "llm", "selector", "rule").withIdentity("tenant", "subject"); + final AiRequestObservation owner = new AiRequestObservation(sink, base); + final AiProxyEngine engine = engine(request -> Mono.deferContextual(view -> { + AgentRequestContext context = view.get(AgentRequestContext.REACTOR_KEY); + assertEquals("subject", context.getSubject()); + assertEquals("actual", context.getTarget()); + return Mono.just(response(200, Flux.just(bytes("{}")))); + }), sink); + engine.execute(BODY, config(false, "actual"), Optional.empty(), result -> result.getBody().then()) + .contextWrite(context -> context.put(AiRequestObservation.REACTOR_KEY, owner)).block(); + assertEquals(1, sink.attempts.size()); + assertTrue(sink.events.isEmpty()); + owner.finish(SignalType.ON_COMPLETE, 200); + assertEquals(1, sink.events.size()); + assertEquals("actual", sink.events.get(0).context().getTarget()); + assertNull(sink.events.get(0).context().getProtocolVersion()); + assertEquals(OpenAiChat.NAME, sink.attempts.get(0).protocol()); + assertNull(base.getTarget()); + } + + @Test + void cancellationAfterRawUsageProducesOneAttemptAndOneLogicalCancellation() { + final Sink sink = new Sink(); + final AtomicBoolean cancelled = new AtomicBoolean(); + final AiProxyEngine engine = engine(request -> Mono.just(response(200, Flux.just(bytes("data: {\"usage\":{\"total_tokens\":8}}\n\n")) + .concatWith(Flux.never()).doOnCancel(() -> cancelled.set(true)))), sink); + final AtomicInteger chunks = new AtomicInteger(); + StepVerifier.create(engine.execute(BODY, config(true, "main"), Optional.empty(), result -> result.getBody().doOnNext(chunk -> chunks.incrementAndGet()).then())) + .then(() -> assertEquals(1, chunks.get())).thenCancel().verify(); + assertTrue(cancelled.get()); + assertEquals(1, sink.attempts.size()); + assertEquals(AiCallOutcome.CANCELLED, sink.attempts.get(0).outcome()); + assertEquals(1, sink.events.size()); + assertEquals(AiCallOutcome.CANCELLED, sink.events.get(0).outcome()); + assertEquals(8L, sink.events.get(0).usage().totalTokens()); + } + + @Test + void preparationRejectionDoesNotFabricateUpstreamAttempt() { + final Sink sink = new Sink(); + final AiProxyEngine engine = engine(request -> Mono.error(new AssertionError("must not call transport")), sink); + StepVerifier.create(engine.execute("not json", config(false, "main"), Optional.empty(), result -> result.getBody().then())).expectError().verify(); + assertTrue(sink.attempts.isEmpty()); + assertEquals(0, sink.events.get(0).attemptCount()); + assertEquals(AiCallOutcome.REJECTED, sink.events.get(0).outcome()); + } + + @Test + void responseConversionCannotFabricateRawUsageAndSubscriptionsAreIsolated() { + final Sink sink = new Sink(); + final AiProxyEngine engine = engine(request -> Mono.just(response(200, Flux.just(bytes("{\"id\":\"fixture\",\"choices\":[]}")))), sink); + final AiCommonConfig config = config(false, "main"); + config.setProtocol(OpenAiResponses.NAME); + final Mono execution = engine.execute("{\"input\":\"hello\"}", config, Optional.empty(), result -> result.getBody().then()); + execution.block(); + execution.block(); + assertEquals(2, sink.events.size()); + assertNotEquals(sink.events.get(0).context().getRequestId(), sink.events.get(1).context().getRequestId()); + assertNull(sink.events.get(0).context().getTenant()); + assertNull(sink.events.get(0).context().getSubject()); + assertEquals(AiUsage.Status.UNKNOWN, sink.events.get(0).usage().status()); + } + + @Test + void exhaustedTransportTimeoutHasOneTerminalAndNoReportedUsage() throws InterruptedException { + final Sink sink = new Sink(); + final AiProxyEngine engine = engine(request -> Mono.error(new AiTransportException( + AiTransportException.Kind.RESPONSE_HEADER_TIMEOUT, "private upstream message", null)), sink); + StepVerifier.create(engine.execute(BODY, config(false, "main"), Optional.empty(), result -> result.getBody().then())).expectError(AiTransportException.class).verify(); + assertTrue(sink.finished.await(5, TimeUnit.SECONDS)); + assertEquals(4, sink.attempts.size()); + assertFalse(sink.attempts.stream().anyMatch(event -> event.outcome() != AiCallOutcome.TIMEOUT)); + assertEquals(1, sink.events.size()); + assertEquals(AiCallOutcome.TIMEOUT, sink.events.get(0).outcome()); + assertEquals(AiUsage.Status.UNKNOWN, sink.events.get(0).usage().status()); + } + + @Test + void cancellingRetryBackoffDoesNotInventAnotherAttempt() { + final Sink sink = new Sink(); + StepVerifier.withVirtualTime(() -> { + AiProxyEngine engine = new AiProxyEngine(new AiProxyProtocolFactory(List.of(new OpenAiChat())), new AiProxyProviderFactory(List.of(new OpenAi())), + request -> Mono.just(response(503, Flux.just(bytes("{}")))), Duration.ofSeconds(30), sink); + return engine.execute(BODY, config(false, "main"), Optional.empty(), result -> result.getBody().then()); + }).then(() -> assertEquals(1, sink.attempts.size())).thenCancel().verify(); + assertEquals(1, sink.events.size()); + assertEquals(1, sink.events.get(0).attemptCount()); + assertEquals(AiCallOutcome.CANCELLED, sink.events.get(0).outcome()); + } + + @Test + void throwingObserversDoNotChangeResponseOrRetryPolicy() { + final AtomicInteger calls = new AtomicInteger(); + final AiCallObserver observer = new AiCallObserver() { + @Override + public void record(final AiTerminalEvent event) { + throw new IllegalStateException("private observer text"); + } + + @Override + public void recordAttempt(final AiAttemptEvent event) { + throw new IllegalStateException("private observer text"); + } + }; + final AiProxyEngine engine = engine(request -> Mono.just(response(calls.incrementAndGet() <= 1 ? 503 : 200, Flux.just(bytes("{}")))), observer); + StepVerifier.create(engine.execute(BODY, config(false, "main"), Optional.empty(), result -> result.getBody().then())).verifyComplete(); + assertEquals(2, calls.get()); + } + + private AiProxyEngine engine(final AiProxyTransport transport, final AiCallObserver observer) { + return new AiProxyEngine(new AiProxyProtocolFactory(List.of(new OpenAiChat(), new OpenAiResponses())), + new AiProxyProviderFactory(List.of(new OpenAi())), transport, Duration.ZERO, observer); + } + + private AiCommonConfig config(final boolean streaming, final String model) { + final AiCommonConfig config = new AiCommonConfig(); + config.setProvider("OpenAI"); + config.setBaseUrl("https://fixture.invalid"); + config.setApiKey("fixture-key"); + config.setModel(model); + config.setStream(streaming); + return config; + } + + private AiUpstreamResponse response(final int status, final Flux body) { + return new AiUpstreamResponse(status, Map.of(), body); + } + + private byte[] bytes(final String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + private static final class Sink implements AiCallObserver { + + private final List attempts = new ArrayList<>(); + + private final List events = new ArrayList<>(); + + private final CountDownLatch finished = new CountDownLatch(1); + + @Override + public void record(final AiTerminalEvent event) { + events.add(event); + finished.countDown(); + } + + @Override + public void recordAttempt(final AiAttemptEvent event) { + attempts.add(event); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiUpstreamUsageTapTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiUpstreamUsageTapTest.java new file mode 100644 index 000000000000..b25f23ba87d4 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiUpstreamUsageTapTest.java @@ -0,0 +1,150 @@ +/* + * 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.plugin.ai.proxy.enhanced.service; + +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.metrics.AiAttemptEvent; +import org.apache.shenyu.common.metrics.AiRequestObservation; +import org.apache.shenyu.common.metrics.AiTerminalEvent; +import org.apache.shenyu.common.metrics.AiUsage; +import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamResponse; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import reactor.core.publisher.Flux; +import reactor.core.publisher.SignalType; +import reactor.test.StepVerifier; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +class AiUpstreamUsageTapTest { + + @Test + void fragmentedJsonPreservesBytesAndDoesNotInferMissingTotal() { + final AiUsage usage = read("{\"text\":\"秘密\",\"usage\":{\"prompt_tokens\":0,\"completion_tokens\":3}}", false, Map.of()); + assertEquals(AiUsage.Status.REPORTED, usage.status()); + assertEquals(0L, usage.promptTokens()); + assertEquals(3L, usage.completionTokens()); + assertNull(usage.totalTokens()); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"usage\":null}", "{\"usage\":{}}", "{\"usage\":{\"prompt_tokens\":null}}"}) + void absentUsageIsUnknownNotZero(final String body) { + final AiUsage usage = read(body, false, Map.of()); + assertEquals(AiUsage.Status.UNKNOWN, usage.status()); + assertNull(usage.promptTokens()); + assertNull(usage.completionTokens()); + assertNull(usage.totalTokens()); + } + + @ParameterizedTest + @ValueSource(strings = {"-1", "1.5", "\"2\"", "true", "9223372036854775808", "[]"}) + void invalidCountersInvalidateSnapshotWithoutEstimates(final String count) { + final AiUsage usage = read("{\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":" + count + "}}", false, Map.of()); + assertEquals(AiUsage.Status.INVALID, usage.status()); + assertNull(usage.promptTokens()); + assertNull(usage.completionTokens()); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"usage\":[]}", "{\"usage\":{\"total_tokens\":1,\"total_tokens\":2}}", "{}{}", "not JSON"}) + void rejectsAmbiguousOrMalformedUsage(final String body) { + assertEquals(AiUsage.Status.INVALID, read(body, false, Map.of()).status()); + } + + @Test + void sseSupportsUtf8ByteSplitsMultilineCrLfAndLastCompleteSnapshot() { + final String body = ": keepalive\r\nevent: message\r\ndata: {\"text\":\"秘密\",\r\ndata: \"usage\":{\"prompt_tokens\":1,\"total_tokens\":9}}\r\n\r\n" + + "data: {\"usage\":{\"completion_tokens\":4}}\n\n" + + "data: {\"choices\":[]}\n\ndata: [DONE]\n\n"; + final AiUsage usage = read(body, true, Map.of()); + assertEquals(AiUsage.Status.REPORTED, usage.status()); + assertNull(usage.promptTokens()); + assertEquals(4L, usage.completionTokens()); + assertNull(usage.totalTokens()); + } + + @Test + void incompleteSseEventAtEofIsNotInventedAsFinalUsage() { + assertEquals(AiUsage.Status.UNKNOWN, read("data: {\"usage\":{\"total_tokens\":7}}\n", true, Map.of()).status()); + } + + @Test + void capsJsonAndEachSseEventRatherThanEntireStream() { + assertEquals(AiUsage.Status.LIMIT_EXCEEDED, read("x".repeat(AiUpstreamUsageTap.MAX_BYTES + 1), false, Map.of()).status()); + assertEquals(AiUsage.Status.LIMIT_EXCEEDED, read("data: " + "x".repeat(AiUpstreamUsageTap.MAX_BYTES), true, Map.of()).status()); + final String many = "data: {\"choices\":[]}\n\n".repeat(4000) + "data: {\"usage\":{\"total_tokens\":7}}\n\n"; + assertEquals(7L, read(many, true, Map.of()).totalTokens()); + } + + @Test + void contentTypeOverridesRequestedStreamingAndEncodedBodiesAreNotDecoded() { + final String json = "{\"usage\":{\"total_tokens\":7}}"; + assertEquals(7L, read(json, true, Map.of("content-type", List.of("application/json; charset=utf-8"))).totalTokens()); + assertEquals(AiUsage.Status.UNSUPPORTED, read(json, false, Map.of("Content-Encoding", List.of("gzip"))).status()); + assertEquals(AiUsage.Status.UNSUPPORTED, read(json, false, Map.of("Content-Type", List.of("text/plain"))).status()); + } + + @Test + void invalidUtf8InSseDoesNotChangeWireBytes() { + final byte[] body = new byte[] {'d', 'a', 't', 'a', ':', (byte) 0xc3, 0x28, '\n', '\n'}; + assertEquals(AiUsage.Status.INVALID, read(List.of(body), true, Map.of()).status()); + } + + private AiUsage read(final String body, final boolean streaming, final Map> headers) { + final byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + final List chunks = new ArrayList<>(); + // Split within UTF-8 codepoints and every JSON/SSE boundary. + for (int offset = 0; offset < bytes.length; offset++) { + chunks.add(Arrays.copyOfRange(bytes, offset, offset + 1)); + } + return read(chunks, streaming, headers); + } + + private AiUsage read(final List chunks, final boolean streaming, final Map> headers) { + final List events = new ArrayList<>(); + final AgentRequestContext context = new AgentRequestContext("request", "llm", null, null); + final AiRequestObservation owner = new AiRequestObservation(events::add, context); + final AiRequestObservation.Attempt attempt = owner.startAttempt(context, AiAttemptEvent.Kind.PRIMARY, "openai", "openai-chat", streaming); + final AtomicInteger subscriptions = new AtomicInteger(); + final AiUpstreamResponse response = new AiUpstreamResponse(200, headers, Flux.defer(() -> { + subscriptions.incrementAndGet(); + return Flux.fromIterable(chunks); + })); + final List received = new ArrayList<>(); + StepVerifier.create(new AiUpstreamUsageTap(attempt, headers, streaming).attach(response).getBody().doOnNext(received::add).then()).verifyComplete(); + attempt.finish(SignalType.ON_COMPLETE, null); + owner.finish(SignalType.ON_COMPLETE, 200); + assertEquals(1, subscriptions.get()); + assertEquals(chunks.size(), received.size()); + for (int index = 0; index < chunks.size(); index++) { + assertSame(chunks.get(index), received.get(index)); + } + return events.get(0).usage(); + } +} diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/AiOutboundTraceContextTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/AiOutboundTraceContextTest.java new file mode 100644 index 000000000000..211370cbef66 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/transport/AiOutboundTraceContextTest.java @@ -0,0 +1,181 @@ +/* + * 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.plugin.ai.proxy.enhanced.transport; + +import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import org.apache.shenyu.common.tracing.AgentTraceContext; +import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamRequest; +import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamResponse; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.ClientRequest; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +import java.net.URI; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class AiOutboundTraceContextTest { + + private static final String TRACE = "0123456789abcdef0123456789abcdef"; + + private static final String SPAN = "0123456789abcdef"; + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void injectsOnlyExplicitTraceAndDoesNotModifyRequest(final boolean gatewayKey) { + final AtomicReference sent = new AtomicReference<>(); + final WebClient client = client(sent); + final AiUpstreamRequest request = request(); + final Context parent = Baggage.builder().put("subject", "secret").build().storeInContext(parent(SPAN)); + new WebClientAiProxyTransport(client).execute(request).flatMap(result -> result.getBody().then()) + .contextWrite(context -> context.put(gatewayKey ? AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY : Context.class, parent)).block(); + assertEquals("00-" + TRACE + "-" + SPAN + "-01", sent.get().headers().getFirst("traceparent")); + assertEquals("fixture=value", sent.get().headers().getFirst("tracestate")); + assertNull(sent.get().headers().getFirst("baggage")); + assertNull(sent.get().headers().getFirst("X-Spike-Subject")); + assertEquals("Bearer service-key", sent.get().headers().getFirst("Authorization")); + assertEquals(List.of("stale"), request.getHeaders().get("TraceParent")); + } + + @Test + void gatewayParentWinsAndInvalidGatewayFallsBackToExplicitOtelContext() { + final Context other = parent("1111111111111111"); + final reactor.util.context.Context view = reactor.util.context.Context.of(AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY, parent(SPAN), Context.class, other); + assertEquals("00-" + TRACE + "-" + SPAN + "-01", AiOutboundTraceContext.headers(view).get("traceparent")); + assertEquals("00-" + TRACE + "-1111111111111111-01", + AiOutboundTraceContext.headers(view.put(AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY, "invalid")).get("traceparent")); + } + + @Test + void ambientContextAndStaleConfiguredHeadersAreNotForwarded() { + final AtomicReference sent = new AtomicReference<>(); + try (Scope ignored = parent(SPAN).makeCurrent()) { + new WebClientAiProxyTransport(client(sent)).execute(request()).flatMap(result -> result.getBody().then()).block(); + } + assertNull(sent.get().headers().getFirst("traceparent")); + assertNull(sent.get().headers().getFirst("tracestate")); + assertNull(sent.get().headers().getFirst("baggage")); + assertEquals(Map.of(), AiOutboundTraceContext.headers(reactor.util.context.Context.of(Context.class, "wrong-type"))); + } + + @Test + void sameRequestAcrossConcurrentSubscriptionsKeepsEachParentIsolated() { + final Map captured = new ConcurrentHashMap<>(); + final WebClient client = WebClient.builder().exchangeFunction(request -> Mono.deferContextual(context -> { + captured.put(context.get("call"), request.headers().getFirst("traceparent")); + return Mono.just(ClientResponse.create(HttpStatus.OK).body("{}").build()); + })).build(); + final Mono execute = new WebClientAiProxyTransport(client).execute(request()).flatMap(response -> response.getBody().then()); + Flux.range(1, 16).flatMap(number -> { + String span = String.format("%016x", number); + return execute.subscribeOn(Schedulers.parallel()).contextWrite(context -> context.put(Context.class, parent(span)).put("call", span)); + }).blockLast(); + assertEquals(16, captured.size()); + captured.forEach((span, trace) -> assertEquals("00-" + TRACE + "-" + span + "-01", trace)); + } + + @Test + void transportActuallyLoadsAndExecutesWithoutAnyOtelClasses() throws Exception { + final AtomicReference sent = new AtomicReference<>(); + final URL classes = WebClientAiProxyTransport.class.getProtectionDomain().getCodeSource().getLocation(); + try (NoOtelLoader loader = new NoOtelLoader(classes)) { + assertThrows(ClassNotFoundException.class, () -> loader.loadClass("io.opentelemetry.api.trace.Span")); + Class isolated = loader.loadClass(WebClientAiProxyTransport.class.getName()); + assertNotSame(WebClientAiProxyTransport.class, isolated); + Object transport = isolated.getConstructor(WebClient.class).newInstance(client(sent)); + Mono execution = (Mono) isolated.getMethod("execute", AiUpstreamRequest.class).invoke(transport, request()); + AiUpstreamResponse result = (AiUpstreamResponse) execution.block(); + result.getBody().then().block(); + assertEquals(200, result.getStatusCode()); + assertFalse(loader.bridgeLoaded); + assertNull(sent.get().headers().getFirst("traceparent")); + assertNull(sent.get().headers().getFirst("baggage")); + } + } + + private Context parent(final String span) { + return Context.root().with(Span.wrap(SpanContext.create(TRACE, span, TraceFlags.getSampled(), TraceState.builder().put("fixture", "value").build()))); + } + + private WebClient client(final AtomicReference sent) { + return WebClient.builder().defaultHeader("baggage", "configured=secret").exchangeFunction(request -> { + sent.set(request); + return Mono.just(ClientResponse.create(HttpStatus.OK).body("{}").build()); + }).build(); + } + + private AiUpstreamRequest request() { + final AiUpstreamRequest request = new AiUpstreamRequest(); + request.setUri(URI.create("https://fixture.invalid/v1/chat/completions")); + request.setMethod("POST"); + request.setHeaders(Map.of("Authorization", List.of("Bearer service-key"), "TraceParent", List.of("stale"), + "Tracestate", List.of("stale=value"), "Baggage", List.of("subject=secret"))); + return request; + } + + private static final class NoOtelLoader extends URLClassLoader { + + private boolean bridgeLoaded; + + private NoOtelLoader(final URL classes) { + super(new URL[] {classes}, AiOutboundTraceContextTest.class.getClassLoader()); + } + + @Override + protected synchronized Class loadClass(final String name, final boolean resolve) throws ClassNotFoundException { + if (name.startsWith("io.opentelemetry.")) { + throw new ClassNotFoundException(name); + } + if (name.startsWith("org.apache.shenyu.plugin.ai.proxy.enhanced.transport.")) { + bridgeLoaded |= name.equals(AiOutboundTraceContext.class.getName()); + Class loaded = findLoadedClass(name); + if (java.util.Objects.isNull(loaded)) { + loaded = findClass(name); + } + if (resolve) { + resolveClass(loaded); + } + return loaded; + } + return super.loadClass(name, resolve); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/circuitbreaker/UpstreamCircuitBreakerTest.java b/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/circuitbreaker/UpstreamCircuitBreakerTest.java index 35b3c718c3b0..4262d6a9d69c 100644 --- a/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/circuitbreaker/UpstreamCircuitBreakerTest.java +++ b/shenyu-plugin/shenyu-plugin-base/src/test/java/org/apache/shenyu/plugin/base/circuitbreaker/UpstreamCircuitBreakerTest.java @@ -117,7 +117,7 @@ public void testSuccessfulProbeClosesBreaker() throws InterruptedException { @Test public void testConcurrentFailuresOpenBreaker() throws InterruptedException { final int threads = 32; - UpstreamCircuitBreaker breaker = UpstreamCircuitBreaker.create(3, 100L); + UpstreamCircuitBreaker breaker = UpstreamCircuitBreaker.create(3, 100_000L); ExecutorService executor = Executors.newFixedThreadPool(threads); CountDownLatch start = new CountDownLatch(1); CountDownLatch done = new CountDownLatch(threads); diff --git a/shenyu-plugin/shenyu-plugin-tracing/src/test/java/org/apache/shenyu/plugin/tracing/TraceContinuityTest.java b/shenyu-plugin/shenyu-plugin-tracing/src/test/java/org/apache/shenyu/plugin/tracing/TraceContinuityTest.java index 2ae2ec42dc64..2363a5633f11 100644 --- a/shenyu-plugin/shenyu-plugin-tracing/src/test/java/org/apache/shenyu/plugin/tracing/TraceContinuityTest.java +++ b/shenyu-plugin/shenyu-plugin-tracing/src/test/java/org/apache/shenyu/plugin/tracing/TraceContinuityTest.java @@ -47,10 +47,13 @@ import java.io.InputStream; import java.net.InetSocketAddress; import java.net.URI; +import java.time.Duration; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; +import static org.awaitility.Awaitility.await; + /** * The Test Case For the continuity of a trace across the gateway. * @@ -68,6 +71,8 @@ public class TraceContinuityTest { private static final String BAGGAGE = "baggage"; + private static final long TEST_HTTP_TIMEOUT = 30_000L; + private final TraceContextExtractor extractor = new TraceContextExtractor(); private final AtomicReference> receivedTraceParents = new AtomicReference<>(); @@ -181,6 +186,7 @@ private ServerWebExchange createExchange(final String traceparent, final String ShenyuContext shenyuContext = new ShenyuContext(); shenyuContext.setRpcType(RpcTypeEnum.HTTP.getName()); exchange.getAttributes().put(Constants.CONTEXT, shenyuContext); + exchange.getAttributes().put(Constants.HTTP_TIME_OUT, TEST_HTTP_TIMEOUT); exchange.getAttributes().put(Constants.HTTP_URI, URI.create("http://127.0.0.1:" + upstream.getAddress().getPort() + PATH)); return exchange; @@ -199,8 +205,7 @@ private SpanContext upstreamParent(final String traceparent) { } private SpanData onlyFinishedSpan() { - List spans = spanExporter.getFinishedSpanItems(); - Assertions.assertEquals(1, spans.size()); - return spans.get(0); + await().atMost(Duration.ofSeconds(5)).until(() -> spanExporter.getFinishedSpanItems().size() == 1); + return spanExporter.getFinishedSpanItems().get(0); } } diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml index a018ca75c08f..2ff2ec3cface 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml @@ -26,6 +26,36 @@ shenyu-spring-boot-starter-plugin-agent-gateway + + org.apache.shenyu + shenyu-plugin-ai-proxy + ${project.version} + test + + + org.apache.shenyu + shenyu-plugin-ai-token-limiter + ${project.version} + test + + + org.apache.shenyu + shenyu-plugin-ai-prompt + ${project.version} + test + + + org.apache.shenyu + shenyu-plugin-tracing + ${project.version} + test + + + org.apache.shenyu + shenyu-web + ${project.version} + test + org.springframework.security spring-security-oauth2-resource-server diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java index b9467ef27740..1320e186c514 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java @@ -18,6 +18,8 @@ package org.apache.shenyu.springboot.starter.plugin.agent.gateway; import io.opentelemetry.api.OpenTelemetry; +import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver; +import org.apache.shenyu.common.metrics.AiCallObserver; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpCallTracer; import org.apache.shenyu.plugin.agent.gateway.AgentGatewayPlugin; import org.apache.shenyu.plugin.agent.gateway.AgentGatewayConstants; @@ -62,12 +64,16 @@ public class AgentGatewayPluginConfiguration { * @param resolvers trusted identity adapters * @param catalogs optional, unambiguous managed remote catalog * @param tracers optional tracing bridge + * @param terminalObservers optional application-owned terminal event sink + * @param aiObservers optional application-owned AI attempt and terminal sink * @param environment deployment-controlled tracing opt-in * @return the plugin */ @Bean public ShenyuPlugin agentGatewayPlugin(final ObjectProvider providers, final ObjectProvider resolvers, final ObjectProvider catalogs, final ObjectProvider tracers, + final ObjectProvider terminalObservers, + final ObjectProvider aiObservers, final Environment environment) { AgentMcpCallTracer tracer = tracers.getIfAvailable(); if (environment.getProperty("shenyu.plugins.agent.gateway.tracing.enabled", Boolean.class, false) && java.util.Objects.isNull(tracer)) { @@ -81,18 +87,24 @@ public ShenyuPlugin agentGatewayPlugin(final ObjectProvider p && resolvers.stream().noneMatch(resolver -> "org.apache.shenyu.springboot.starter.plugin.agent.gateway.PrincipalMcpSecurityResolver".equals(resolver.getClass().getName()))) { throw new IllegalStateException("Enabled MCP principal authorization requires an explicit source and its optional dependencies"); } - return createPlugin(providers, resolvers, catalogs.getIfAvailable(), tracer); + return createPlugin(providers, resolvers, catalogs.getIfAvailable(), tracer, terminalObservers.getIfAvailable(), + aiObservers.getIfAvailable(), environment.getProperty("shenyu.plugins.agent.gateway.security.llm.enabled", Boolean.class, false)); } private ShenyuPlugin createPlugin(final ObjectProvider providers, final ObjectProvider resolvers, - final AgentMcpRemoteCatalog catalog, final AgentMcpCallTracer tracer) { + final AgentMcpRemoteCatalog catalog, final AgentMcpCallTracer tracer, final AgentMcpTerminalObserver terminalObserver, + final AiCallObserver aiObserver, final boolean llmIdentityEnabled) { AgentToolRegistry registry = new AgentToolRegistry(providers.orderedStream().toList()); List candidates = resolvers.stream().toList(); if (candidates.size() > 1) { throw new IllegalStateException("MCP requires exactly one authoritative security resolver"); } AgentMcpSecurityResolver resolver = candidates.isEmpty() ? exchange -> Mono.empty() : candidates.get(0); - return new AgentGatewayPlugin(new AgentMcpHttpHandler(new AgentMcpDispatcher(registry, "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, catalog), resolver, tracer)); + if (llmIdentityEnabled && candidates.isEmpty()) { + throw new IllegalStateException("Enabled LLM identity mapping requires an authoritative security resolver"); + } + return new AgentGatewayPlugin(new AgentMcpHttpHandler(new AgentMcpDispatcher(registry, "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, catalog), + resolver, tracer, terminalObserver), llmIdentityEnabled ? resolver : null, aiObserver); } /** diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracer.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracer.java index ccc5cc37c347..19e14d8ce6cd 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracer.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracer.java @@ -22,12 +22,16 @@ import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import org.apache.shenyu.common.metrics.AgentMcpCallObserver.Outcome; +import org.apache.shenyu.common.tracing.AgentTraceContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpCallTracer; import reactor.util.context.Context; import reactor.util.context.ContextView; +import java.util.HashMap; import java.util.Locale; +import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; /** @@ -43,7 +47,10 @@ final class OpenTelemetryAgentMcpCallTracer implements AgentMcpCallTracer { @Override public Trace start(final ContextView parentContext) { - Object value = parentContext.getOrDefault(io.opentelemetry.context.Context.class, null); + Object value = parentContext.getOrDefault(AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY, null); + if (!(value instanceof io.opentelemetry.context.Context gateway) || !Span.fromContext(gateway).getSpanContext().isValid()) { + value = parentContext.getOrDefault(io.opentelemetry.context.Context.class, null); + } io.opentelemetry.context.Context parent = io.opentelemetry.context.Context.root(); if (value instanceof io.opentelemetry.context.Context context) { // Keep only the parent span identity, never baggage or unrelated application data. @@ -51,11 +58,15 @@ public Trace start(final ContextView parentContext) { } Span span = tracer.spanBuilder("shenyu.agent_gateway.tools.call").setSpanKind(SpanKind.INTERNAL).setParent(parent).startSpan(); io.opentelemetry.context.Context execution = io.opentelemetry.context.Context.root().with(span); + Map carrier = new HashMap<>(); + // Deliberately do not use application propagators, which may include baggage or other headers. + W3CTraceContextPropagator.getInstance().inject(execution, carrier, Map::put); + Map headers = AgentTraceContext.headers(carrier); AtomicBoolean ended = new AtomicBoolean(); return new Trace() { @Override public Context attach(final Context context) { - return context.put(io.opentelemetry.context.Context.class, execution); + return context.put(io.opentelemetry.context.Context.class, execution).put(AgentTraceContext.HEADERS_KEY, headers); } @Override diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java index 1385178896a8..0349c155e7b4 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java @@ -54,6 +54,19 @@ class AgentGatewayPluginConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(AgentGatewayPluginConfiguration.class); + @Test + void llmIdentityIsOptInAndRequiresOneAuthority() { + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.gateway.security.llm.enabled=true") + .run(context -> assertNotNull(context.getStartupFailure())); + AgentMcpSecurityResolver resolver = ignored -> Mono.empty(); + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.gateway.security.llm.enabled=true") + .withBean(AgentMcpSecurityResolver.class, () -> resolver) + .run(context -> assertEquals(resolver, ReflectionTestUtils.getField(context.getBean(AgentGatewayPlugin.class), "llmSecurityResolver"))); + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true") + .withBean(AgentMcpSecurityResolver.class, () -> resolver) + .run(context -> assertTrue(java.util.Objects.isNull(ReflectionTestUtils.getField(context.getBean(AgentGatewayPlugin.class), "llmSecurityResolver")))); + } + @Test void shouldKeepPluginUnassembledByDefault() { contextRunner.run(context -> { diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java new file mode 100644 index 000000000000..1ba85ad30d6a --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java @@ -0,0 +1,334 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import org.apache.shenyu.common.config.ShenyuConfig; +import org.apache.shenyu.common.constant.Constants; +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.common.dto.SelectorData; +import org.apache.shenyu.common.dto.convert.rule.AiProxyHandle; +import org.apache.shenyu.common.enums.PluginHandlerEventEnum; +import org.apache.shenyu.common.metrics.AiAttemptEvent; +import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.common.metrics.AiCallOutcome; +import org.apache.shenyu.common.metrics.AiTerminalEvent; +import org.apache.shenyu.common.metrics.AiUsage; +import org.apache.shenyu.plugin.agent.gateway.AgentGatewayPlugin; +import org.apache.shenyu.plugin.agent.gateway.handler.AgentGatewayPluginDataHandler; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpHttpHandler; +import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry; +import org.apache.shenyu.plugin.ai.prompt.AiPromptPlugin; +import org.apache.shenyu.plugin.ai.prompt.handler.AiPromptPluginDataHandler; +import org.apache.shenyu.plugin.ai.proxy.enhanced.AiProxyPlugin; +import org.apache.shenyu.plugin.ai.proxy.enhanced.handler.AiProxyPluginHandler; +import org.apache.shenyu.plugin.ai.proxy.enhanced.protocol.AiProxyProtocolFactory; +import org.apache.shenyu.plugin.ai.proxy.enhanced.protocol.OpenAiChat; +import org.apache.shenyu.plugin.ai.proxy.enhanced.provider.AiProxyProviderFactory; +import org.apache.shenyu.plugin.ai.proxy.enhanced.provider.OpenAi; +import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiProxyConfigService; +import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiProxyEngine; +import org.apache.shenyu.plugin.ai.proxy.enhanced.transport.WebClientAiProxyTransport; +import org.apache.shenyu.plugin.ai.token.limiter.AiTokenLimiterPlugin; +import org.apache.shenyu.plugin.ai.token.limiter.handler.AiTokenLimiterPluginHandler; +import org.apache.shenyu.plugin.api.ShenyuPlugin; +import org.apache.shenyu.plugin.api.result.DefaultShenyuResult; +import org.apache.shenyu.plugin.api.result.ShenyuResult; +import org.apache.shenyu.plugin.api.utils.SpringBeanUtils; +import org.apache.shenyu.plugin.base.cache.BaseDataCache; +import org.apache.shenyu.plugin.base.cache.PluginHandlerEvent; +import org.apache.shenyu.plugin.base.utils.CacheKeyUtils; +import org.apache.shenyu.plugin.key.auth.KeyAuthPlugin; +import org.apache.shenyu.plugin.key.auth.handler.KeyAuthPluginDataHandler; +import org.apache.shenyu.plugin.tracing.TracingPlugin; +import org.apache.shenyu.web.handler.ShenyuWebHandler; +import org.apache.shenyu.web.loader.ShenyuLoaderService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.core.ReactiveValueOperations; +import org.springframework.http.codec.ServerCodecConfigurer; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; +import reactor.netty.resources.LoopResources; + +import java.time.Duration; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Loopback HTTP through actual sorted plugin matching and real AI transport. + * Redis is a controlled fixture, not a distributed-budget acceptance test. + */ +class AgentGovernanceHttpTest { + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void keyAuthToLimiterToProxyHasOneTerminalAndOneBodySubscription(final boolean stream) { + try (Fixture fixture = new Fixture(stream, false)) { + String response = fixture.request().expectStatus().isOk().expectBody(String.class).returnResult().getResponseBody(); + assertEquals(fixture.response, response); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> assertEquals(1, fixture.terminals.size())); + assertEquals(1, fixture.attempts.size()); + assertEquals(1, fixture.upstreamCalls.get()); + assertEquals(1, fixture.bodySubscriptions.get()); + AiTerminalEvent event = fixture.terminals.element(); + assertEquals(AiCallOutcome.SUCCESS, event.outcome()); + assertEquals("tenant", event.context().getTenant()); + assertEquals("service", event.context().getSubject()); + assertEquals("model", event.context().getTarget()); + assertEquals(event.context().getRequestId(), fixture.limiterContext.get().getRequestId()); + assertEquals(1, event.attemptCount()); + assertEquals(3L, event.usage().promptTokens()); + assertEquals(2L, event.usage().completionTokens()); + assertEquals(5L, event.usage().totalTokens()); + assertNull(event.context().getSessionId()); + assertEquals(event.context().getRequestId(), fixture.attempts.element().context().getRequestId()); + assertEquals(List.of("tracing", "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"), fixture.handler.getPlugins().stream().map(ShenyuPlugin::named).toList()); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> assertEquals(1, fixture.exporter.getFinishedSpanItems().size())); + var span = fixture.exporter.getFinishedSpanItems().get(0); + assertEquals(SpanKind.SERVER, span.getKind()); + assertEquals("12345678901234567890123456789012", span.getTraceId()); + assertEquals("1234567890123456", span.getParentSpanId()); + assertEquals("00-" + span.getTraceId() + "-" + span.getSpanId() + "-01", fixture.outboundParent.get()); + } + } + + @Test + void tokenDenialHasTrustedContextWithoutCallingModel() { + try (Fixture fixture = new Fixture(false, true)) { + fixture.request().expectStatus().isEqualTo(429).expectBody().consumeWith(ignored -> { }); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> assertEquals(1, fixture.terminals.size())); + AiTerminalEvent event = fixture.terminals.element(); + assertEquals(AiCallOutcome.RATE_LIMITED, event.outcome()); + assertEquals("tenant", event.context().getTenant()); + assertEquals(0, event.attemptCount()); + assertEquals(AiUsage.UNKNOWN, event.usage()); + assertEquals(1, fixture.bodySubscriptions.get()); + assertEquals(0, fixture.upstreamCalls.get()); + assertTrue(fixture.attempts.isEmpty()); + } + } + + private static final class Fixture implements AutoCloseable { + + private final LoopResources loops = LoopResources.create("governance-http", 2, true); + + private final ConcurrentLinkedQueue terminals = new ConcurrentLinkedQueue<>(); + + private final ConcurrentLinkedQueue attempts = new ConcurrentLinkedQueue<>(); + + private final AtomicInteger upstreamCalls = new AtomicInteger(); + + private final AtomicInteger bodySubscriptions = new AtomicInteger(); + + private final AtomicReference limiterContext = new AtomicReference<>(); + + private final AtomicReference outboundParent = new AtomicReference<>(); + + private final InMemorySpanExporter exporter = InMemorySpanExporter.create(); + + private final SdkTracerProvider tracerProvider = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build(); + + private final OpenTelemetrySdk telemetry = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build(); + + private final DisposableServer upstream; + + private final DisposableServer gateway; + + private final ShenyuWebHandler handler; + + private final String response; + + private final boolean stream; + + private final AiProxyPluginHandler proxyHandler = new AiProxyPluginHandler(); + + private final AiPromptPluginDataHandler promptHandler = new AiPromptPluginDataHandler(); + + private final KeyAuthPluginDataHandler keyHandler = new KeyAuthPluginDataHandler(); + + private final AgentGatewayPluginDataHandler agentHandler = new AgentGatewayPluginDataHandler(); + + @SuppressWarnings("unchecked") + private Fixture(final boolean stream, final boolean deny) { + this.stream = stream; + String json = "{\"choices\":[],\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":2,\"total_tokens\":5}}"; + response = stream ? "data: " + json + "\n\ndata: [DONE]\n\n" : json; + upstream = HttpServer.create().host("127.0.0.1").port(0).runOn(loops).handle((request, result) -> { + upstreamCalls.incrementAndGet(); + outboundParent.set(request.requestHeaders().get("traceparent")); + assertNull(request.requestHeaders().get("baggage")); + assertNull(request.requestHeaders().get("X-Tenant-Id")); + assertNull(request.requestHeaders().get("X-Subject")); + assertNull(request.requestHeaders().get("X-Api-Key")); + assertEquals("Bearer upstream-service-key", request.requestHeaders().get("Authorization")); + return request.receive().then(result.header("Content-Type", stream ? "text/event-stream" : "application/json") + .sendString(Flux.just(response.substring(0, 29), response.substring(29))).then()); + }).bindNow(Duration.ofSeconds(20)); + ShenyuConfig config = new ShenyuConfig(); + config.getSelectorMatchCache().getCache().setEnabled(false); + config.getRuleMatchCache().getCache().setEnabled(false); + ConfigurableApplicationContext application = mock(ConfigurableApplicationContext.class); + when(application.getBean(ShenyuConfig.class)).thenReturn(config); + when(application.getBean(ShenyuResult.class)).thenReturn(new DefaultShenyuResult()); + SpringBeanUtils.getInstance().setApplicationContext(application); + KeyAuthPlugin key = new KeyAuthPlugin(); + RuleData keyRule = register(key, "{\"keyName\":\"X-Api-Key\",\"key\":\"fixture-key\"}"); + keyHandler.handlerRule(keyRule); + final KeyAuthMcpSecurityProperties properties = new KeyAuthMcpSecurityProperties(); + KeyAuthMcpSecurityProperties.Binding binding = new KeyAuthMcpSecurityProperties.Binding(); + binding.setNamespaceId("namespace"); + binding.setSelectorId(keyRule.getSelectorId()); + binding.setRuleId(keyRule.getId()); + binding.setTenant("tenant"); + binding.setSubject("service"); + binding.setToolGrants(Set.of()); + binding.setToolDenials(Set.of()); + properties.setBindings(List.of(binding)); + KeyAuthMcpSecurityResolver resolver = new KeyAuthMcpSecurityResolver(properties); + AiCallObserver observer = new AiCallObserver() { + @Override + public void record(final AiTerminalEvent event) { + terminals.add(event); + } + + @Override + public void recordAttempt(final AiAttemptEvent event) { + attempts.add(event); + } + }; + AgentGatewayPlugin agent = new AgentGatewayPlugin(new AgentMcpHttpHandler( + new AgentMcpDispatcher(new AgentToolRegistry(List.of()), "fixture", "1"), resolver), resolver, observer); + agentHandler.handlerRule(register(agent, "{\"trafficType\":\"LLM\"}")); + AiPromptPlugin prompt = new AiPromptPlugin(ServerCodecConfigurer.create().getReaders()); + RuleData promptRule = register(prompt, "{\"prepend\":\"governed\",\"preRole\":\"system\"}"); + promptHandler.handlerRule(promptRule); + AiTokenLimiterPlugin limiter = new AiTokenLimiterPlugin(); + new AiTokenLimiterPluginHandler().handlerRule(register(limiter, "{\"aiTokenLimitType\":\"uri\",\"keyName\":\"unused\",\"tokenLimit\":100,\"timeWindowSeconds\":60}")); + ReactiveRedisTemplate redis = mock(ReactiveRedisTemplate.class); + ReactiveValueOperations values = mock(ReactiveValueOperations.class); + when(redis.opsForValue()).thenReturn(values); + when(values.get(anyString())).thenReturn(Mono.deferContextual(context -> { + limiterContext.set(context.get(AgentRequestContext.REACTOR_KEY)); + return Mono.just(deny ? "100" : "0"); + })); + when(values.setIfAbsent(anyString(), anyString(), any(Duration.class))).thenReturn(Mono.just(true)); + when(values.increment(anyString(), anyLong())).thenReturn(Mono.just(2L)); + AiTokenLimiterPluginHandler.REDIS_CACHED_HANDLE.get().cachedHandle(limiter.named(), redis); + AiProxyEngine engine = new AiProxyEngine(new AiProxyProtocolFactory(List.of(new OpenAiChat())), + new AiProxyProviderFactory(List.of(new OpenAi())), new WebClientAiProxyTransport(WebClient.builder().build()), Duration.ZERO); + AiProxyPlugin proxy = new AiProxyPlugin(new AiProxyConfigService(), engine, proxyHandler); + final RuleData proxyRule = register(proxy, "{}"); + AiProxyHandle handle = new AiProxyHandle(); + handle.setProvider("OpenAI"); + handle.setBaseUrl("http://127.0.0.1:" + upstream.port()); + handle.setApiKey("upstream-service-key"); + handle.setModel("model"); + proxyHandler.getSelectorCachedHandle().cachedHandle(CacheKeyUtils.INST.getKey(proxyRule.getSelectorId(), Constants.DEFAULT_RULE), handle); + TracingPlugin tracing = new TracingPlugin(telemetry.getTracer("governance-fixture")); + handler = new ShenyuWebHandler(List.of(proxy, limiter, prompt, agent, key, tracing), mock(ShenyuLoaderService.class), config); + handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.SORTED, BaseDataCache.getInstance().obtainPluginData(agent.named()))); + gateway = HttpServer.create().host("127.0.0.1").port(0).runOn(loops).handle(new ReactorHttpHandlerAdapter( + WebHttpHandlerBuilder.webHandler(exchange -> { + org.springframework.http.server.reactive.ServerHttpRequestDecorator request = new org.springframework.http.server.reactive.ServerHttpRequestDecorator(exchange.getRequest()) { + @Override + public Flux getBody() { + return Flux.defer(() -> { + bodySubscriptions.incrementAndGet(); + return super.getBody(); + }); + } + }; + return handler.handle(exchange.mutate().request(request).build()); + }).build())).bindNow(Duration.ofSeconds(20)); + } + + private RuleData register(final ShenyuPlugin plugin, final String handle) { + PluginData data = new PluginData(); + data.setName(plugin.named()); + data.setEnabled(true); + data.setSort(plugin.getOrder()); + BaseDataCache cache = BaseDataCache.getInstance(); + cache.cachePluginData(data); + SelectorData selector = SelectorData.builder().id("governance-" + plugin.named()).pluginName(plugin.named()).enabled(true).continued(true) + .logged(false).sort(0).type(0).matchMode(0).build(); + cache.cacheSelectData(selector); + RuleData rule = RuleData.builder().id(selector.getId() + "-rule").selectorId(selector.getId()).pluginName(plugin.named()) + .namespaceId("namespace").enabled(true).loged(false).sort(0).matchMode(0).handle(handle).build(); + cache.cacheRuleData(rule); + return rule; + } + + private WebTestClient.ResponseSpec request() { + return WebTestClient.bindToServer().baseUrl("http://127.0.0.1:" + gateway.port()).responseTimeout(Duration.ofSeconds(20)).build() + .post().uri("/chat").header("X-Api-Key", "fixture-key").header("X-Tenant-Id", "forged").header("X-Subject", "forged") + .header("traceparent", "00-12345678901234567890123456789012-1234567890123456-01").header("baggage", "private=never-forward") + .header("Content-Type", "application/json").bodyValue("{\"messages\":[{\"role\":\"user\",\"content\":\"private\"}],\"stream\":" + stream + "}").exchange(); + } + + @Override + public void close() { + gateway.disposeNow(Duration.ofSeconds(10)); + upstream.disposeNow(Duration.ofSeconds(10)); + loops.disposeLater().block(Duration.ofSeconds(10)); + telemetry.close(); + BaseDataCache cache = BaseDataCache.getInstance(); + for (String name : List.of("keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy")) { + cache.removeRuleDataBySelectorId("governance-" + name); + cache.removeSelectDataByPluginName(name); + cache.removePluginDataByPluginName(name); + } + KeyAuthPluginDataHandler.CACHED_HANDLE.get().removeHandle("governance-keyAuth_governance-keyAuth-rule"); + AgentGatewayPluginDataHandler.CACHED_HANDLE.get().removeHandle("governance-agentGateway_governance-agentGateway-rule"); + promptHandler.CACHED_HANDLE.get().removeHandle("governance-aiPrompt_governance-aiPrompt-rule"); + AiTokenLimiterPluginHandler.CACHED_HANDLE.get().removeHandle("governance-aiTokenLimiter_governance-aiTokenLimiter-rule"); + AiTokenLimiterPluginHandler.REDIS_CACHED_HANDLE.get().removeHandle("aiTokenLimiter"); + proxyHandler.getSelectorCachedHandle().removeHandle(CacheKeyUtils.INST.getKey("governance-aiProxy", Constants.DEFAULT_RULE)); + } + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracerTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracerTest.java index 99e15b981175..bcece8a975bd 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracerTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracerTest.java @@ -22,8 +22,11 @@ import io.opentelemetry.api.baggage.Baggage; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.StatusCode; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; import io.opentelemetry.sdk.OpenTelemetrySdk; @@ -33,6 +36,7 @@ import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import org.apache.shenyu.common.dto.AgentGatewayMcpConfig; import org.apache.shenyu.common.metrics.AgentMcpCallObserver.Outcome; +import org.apache.shenyu.common.tracing.AgentTraceContext; import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpCallTracer; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; @@ -63,6 +67,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.awaitility.Awaitility.await; import static org.mockito.ArgumentMatchers.any; @@ -116,14 +121,18 @@ void responseWritingMustTerminateBeforeSpanEnds(final String mode) { } } - @Test - void reactorParentAndChildStayPrivateAcrossThirtyTwoSameIdCalls() { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void reactorParentAndChildStayPrivateAcrossThirtyTwoSameIdCalls(final boolean gatewayKey) { try (Fixture fixture = new Fixture()) { List parents = new CopyOnWriteArrayList<>(); Map children = new ConcurrentHashMap<>(); Mono action = Mono.deferContextual(context -> { Context execution = context.get(Context.class); assertTrue(Baggage.fromContext(execution).isEmpty()); + Map headers = context.get(AgentTraceContext.HEADERS_KEY); + assertEquals(Span.fromContext(execution).getSpanContext().getSpanId(), headers.get("traceparent").split("-")[2]); + assertThrows(UnsupportedOperationException.class, () -> headers.put("baggage", "secret")); children.put(Span.fromContext(execution).getSpanContext().getSpanId(), context.get("expected-parent")); return Mono.just(new JsonObject()); }).subscribeOn(Schedulers.parallel()); @@ -133,7 +142,8 @@ void reactorParentAndChildStayPrivateAcrossThirtyTwoSameIdCalls() { parents.add(parent.getSpanContext().getSpanId()); Context context = Baggage.builder().put("private-subject", "secret").build().storeInContext(Context.root().with(parent)); return handler.handle(exchange("tools/call"), config("json", 30000), traffic(), index) - .contextWrite(value -> value.put(Context.class, context).put("expected-parent", parent.getSpanContext().getSpanId())) + .contextWrite(value -> value.put(gatewayKey ? AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY : Context.class, context) + .put("expected-parent", parent.getSpanContext().getSpanId())) .doFinally(signal -> parent.end()); }, 32)).verifyComplete(); await().atMost(Duration.ofSeconds(3)).until(() -> fixture.exporter.getFinishedSpanItems().size() == 64); @@ -147,6 +157,54 @@ void reactorParentAndChildStayPrivateAcrossThirtyTwoSameIdCalls() { } } + @Test + void gatewayServerParentWinsAndOnlyW3cHeadersAreAttached() { + try (Fixture fixture = new Fixture()) { + SpanContext gateway = SpanContext.create("11111111111111111111111111111111", "2222222222222222", + TraceFlags.getSampled(), TraceState.builder().put("vendor", "opaque").build()); + SpanContext other = SpanContext.create("33333333333333333333333333333333", "4444444444444444", + TraceFlags.getSampled(), TraceState.getDefault()); + Context parent = Baggage.builder().put("subject", "private").build().storeInContext(Context.root().with(Span.wrap(gateway))); + AgentMcpCallTracer.Trace trace = fixture.tracer.start(reactor.util.context.Context.of( + AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY, parent, Context.class, Context.root().with(Span.wrap(other)))); + reactor.util.context.Context attached = trace.attach(reactor.util.context.Context.of( + AgentTraceContext.HEADERS_KEY, Map.of("baggage", "must-be-replaced"), "application-key", "preserved")); + Map headers = attached.get(AgentTraceContext.HEADERS_KEY); + assertEquals(Set.of("traceparent", "tracestate"), headers.keySet()); + assertEquals("vendor=opaque", headers.get("tracestate")); + assertEquals("preserved", attached.get("application-key")); + assertTrue(Baggage.fromContext(attached.get(Context.class)).isEmpty()); + trace.finish(Outcome.SUCCESS); + SpanData child = fixture.single(Outcome.SUCCESS); + assertEquals(gateway.getTraceId(), child.getTraceId()); + assertEquals(gateway.getSpanId(), child.getParentSpanId()); + assertEquals("00-" + child.getTraceId() + "-" + child.getSpanId() + "-01", headers.get("traceparent")); + assertThrows(UnsupportedOperationException.class, () -> headers.put("Authorization", "private")); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void invalidGatewayContextFallsBackToExplicitApplicationParent(final boolean wrongType) { + try (Fixture fixture = new Fixture()) { + SpanContext parent = SpanContext.create("11111111111111111111111111111111", "2222222222222222", + TraceFlags.getSampled(), TraceState.getDefault()); + AgentMcpCallTracer.Trace trace = fixture.tracer.start(reactor.util.context.Context.of( + AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY, wrongType ? "not-an-otel-context" : Context.root(), + Context.class, Context.root().with(Span.wrap(parent)))); + trace.finish(Outcome.SUCCESS); + assertEquals(parent.getSpanId(), fixture.single(Outcome.SUCCESS).getParentSpanId()); + } + } + + @Test + void noopTelemetryDoesNotInventTraceHeaders() { + AgentMcpCallTracer.Trace trace = new OpenTelemetryAgentMcpCallTracer(io.opentelemetry.api.OpenTelemetry.noop()) + .start(reactor.util.context.Context.empty()); + assertEquals(Map.of(), trace.attach(reactor.util.context.Context.empty()).get(AgentTraceContext.HEADERS_KEY)); + trace.finish(Outcome.SUCCESS); + } + @Test void doesNotInheritThreadLocalParentOrEndIt() { try (Fixture fixture = new Fixture()) { diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpRemoteTracingTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpRemoteTracingTest.java new file mode 100644 index 000000000000..eb26acc1cc0e --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpRemoteTracingTest.java @@ -0,0 +1,358 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.sun.net.httpserver.HttpServer; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import org.apache.shenyu.common.dto.AgentGatewayMcpConfig; +import org.apache.shenyu.common.tracing.AgentTraceContext; +import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpHttpHandler; +import org.apache.shenyu.plugin.agent.gateway.remote.ManagedRemoteMcpCatalog; +import org.apache.shenyu.plugin.agent.gateway.remote.RemoteServerBinding; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpIdentity; +import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry; +import org.apache.shenyu.plugin.tracing.TracingConstants; +import org.apache.shenyu.plugin.tracing.TracingPlugin; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.netty.DisposableServer; +import reactor.test.StepVerifier; + +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Real catalog and outbound HTTP regression for request-local logical spans. */ +class OpenTelemetryAgentMcpRemoteTracingTest { + + private static final Duration WAIT = Duration.ofSeconds(30); + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void gatewayParentLogicalCallAndOutboundHeadersStayCorrelated(final boolean sse) throws Exception { + try (Fixture fixture = new Fixture(sse)) { + StepVerifier.create(Flux.range(0, 32).flatMap(index -> fixture.call("call-" + index), 32)).verifyComplete(); + fixture.assertCalls(32); + fixture.assertServiceIsolation(); + assertEquals(1, fixture.requests.stream().filter(request -> "initialize".equals(request.method())).count()); + assertEquals(1, fixture.requests.stream().filter(request -> "notifications/initialized".equals(request.method())).count()); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void cancellingOneLogicalCallDoesNotEndPeerOrReuseItsHeaders(final boolean sse) throws Exception { + try (Fixture fixture = new Fixture(sse)) { + fixture.holdPeer = true; + final CompletableFuture peer = fixture.cancelWhilePeerPending(); + await().atMost(WAIT).until(() -> fixture.exporter.getFinishedSpanItems().stream() + .filter(span -> "cancelled".equals(span.getAttributes().get(AttributeKey.stringKey("shenyu.mcp.outcome")))).count() == 1); + assertFalse(peer.isDone()); + assertTrue(fixture.exporter.getFinishedSpanItems().stream() + .noneMatch(span -> fixture.inboundTraces.get("peer").equals(span.getTraceId()))); + fixture.peerRelease.countDown(); + peer.get(30, TimeUnit.SECONDS); + fixture.call("later").block(WAIT); + fixture.assertCalls(3); + fixture.assertServiceIsolation(); + assertEquals(1, fixture.exporter.getFinishedSpanItems().stream() + .filter(span -> "cancelled".equals(span.getAttributes().get(AttributeKey.stringKey("shenyu.mcp.outcome")))).count()); + assertEquals(2, fixture.exporter.getFinishedSpanItems().stream() + .filter(span -> "success".equals(span.getAttributes().get(AttributeKey.stringKey("shenyu.mcp.outcome")))).count()); + assertFalse(fixture.requests.stream().anyMatch(request -> "DELETE".equals(request.method()))); + } + } + + private record Request(String method, String token, String traceparent, Map> headers) { } + + private static final class Fixture implements AutoCloseable { + + private final InMemorySpanExporter exporter = InMemorySpanExporter.create(); + + private final OpenTelemetrySdk sdk = OpenTelemetrySdk.builder().setTracerProvider(SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(exporter)).build()).build(); + + private final ExecutorService executor = Executors.newFixedThreadPool(8); + + private final CountDownLatch entered = new CountDownLatch(1); + + private final CountDownLatch release = new CountDownLatch(1); + + private final CountDownLatch peerEntered = new CountDownLatch(1); + + private final CountDownLatch peerRelease = new CountDownLatch(1); + + private final Map parents = new ConcurrentHashMap<>(); + + private final Map inboundTraces = new ConcurrentHashMap<>(); + + private final List requests = new CopyOnWriteArrayList<>(); + + private final HttpServer server; + + private final DisposableServer gateway; + + private final HttpClient client = HttpClient.newBuilder().connectTimeout(WAIT).build(); + + private volatile boolean holdPeer; + + private final ManagedRemoteMcpCatalog catalog; + + private final AgentMcpHttpHandler handler; + + private final TracingPlugin tracing = new TracingPlugin(sdk.getTracer("gateway-fixture")); + + private final AgentGatewayMcpConfig config; + + private Fixture(final boolean sse) throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.setExecutor(executor); + server.createContext("/ready", exchange -> { + exchange.sendResponseHeaders(204, -1); + exchange.close(); + }); + server.createContext("/mcp", exchange -> { + try { + if ("DELETE".equals(exchange.getRequestMethod())) { + requests.add(new Request("DELETE", "", Objects.toString(exchange.getRequestHeaders().getFirst("traceparent"), ""), + Map.copyOf(exchange.getRequestHeaders()))); + exchange.sendResponseHeaders(204, -1); + return; + } + ObjectMapper json = new ObjectMapper(); + var request = json.readTree(exchange.getRequestBody()); + String method = request.path("method").asText(); + String token = request.path("params").path("arguments").path("token").asText(); + requests.add(new Request(method, token, Objects.toString(exchange.getRequestHeaders().getFirst("traceparent"), ""), + Map.copyOf(exchange.getRequestHeaders()))); + if ("notifications/initialized".equals(method)) { + exchange.sendResponseHeaders(202, -1); + return; + } + var result = json.createObjectNode(); + if ("initialize".equals(method)) { + exchange.getResponseHeaders().set("MCP-Session-Id", "shared-service-session"); + result.put("protocolVersion", "2025-06-18"); + result.putObject("capabilities").putObject("tools"); + result.putObject("serverInfo").put("name", "fixture").put("version", "1"); + } else if ("tools/list".equals(method)) { + result.putArray("tools").addObject().put("name", "lookup").put("description", "Read") + .putObject("inputSchema").put("type", "object"); + } else { + if ("cancel".equals(token)) { + entered.countDown(); + release.await(60, TimeUnit.SECONDS); + } else if (holdPeer && "peer".equals(token)) { + peerEntered.countDown(); + peerRelease.await(60, TimeUnit.SECONDS); + } + result.putArray("content").addObject().put("type", "text").put("text", token); + result.putObject("structuredContent").put("token", token); + result.put("isError", false); + } + var envelope = json.createObjectNode().put("jsonrpc", "2.0"); + envelope.set("id", request.get("id")); + envelope.set("result", result); + boolean streaming = sse && "tools/call".equals(method); + byte[] bytes = (streaming ? "data: " + envelope + "\n\n" : envelope.toString()).getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", streaming ? "text/event-stream" : "application/json"); + exchange.sendResponseHeaders(200, bytes.length); + exchange.getResponseBody().write(bytes); + } catch (Exception expected) { + // Cancellation deliberately closes a real remote HTTP connection. + } finally { + exchange.close(); + } + }); + server.start(); + URI endpoint = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/mcp"); + assertEquals(204, HttpClient.newHttpClient().send(HttpRequest.newBuilder(endpoint.resolve("/ready")) + .timeout(WAIT).build(), HttpResponse.BodyHandlers.discarding()).statusCode()); + catalog = new ManagedRemoteMcpCatalog(Set.of(endpoint), Set.of(), target -> new RemoteServerBinding.Credential(target, "fixed-service-token")); + String source = "{\"aggregation\":{\"revision\":\"trace-v1\",\"servers\":[{\"name\":\"orders\",\"endpoint\":\"" + endpoint + + "\",\"credentialRef\":\"service/orders\",\"credentialVersion\":\"v1\"}]}}"; + catalog.reload(source).contextWrite(value -> value.put(AgentTraceContext.HEADERS_KEY, + Map.of("traceparent", "00-11111111111111111111111111111111-2222222222222222-01"))).block(WAIT); + handler = new AgentMcpHttpHandler(new AgentMcpDispatcher(new AgentToolRegistry(List.of()), "fixture", "1", catalog), + ignored -> Mono.just(new AgentMcpIdentity("private-subject", Set.of("orders.lookup"))), new OpenTelemetryAgentMcpCallTracer(sdk)); + config = AgentGatewayMcpConfig.parse(JsonParser.parseString("{\"allowedTools\":[\"orders.lookup\"],\"timeoutMs\":30000,\"responseMode\":\"" + + (sse ? "sse" : "json") + "\"}").getAsJsonObject(), true); + assertEquals(TracingConstants.REACTOR_CONTEXT_KEY, AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY); + ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(WebHttpHandlerBuilder.webHandler(exchange -> tracing.execute(exchange, + next -> Mono.deferContextual(view -> { + String token = next.getRequest().getPath().value().substring("/agent/".length()); + Context parent = view.get(TracingConstants.REACTOR_CONTEXT_KEY); + parents.put(token, Span.fromContext(parent).getSpanContext().getSpanId()); + return handler.handle(next, config, new AgentTrafficContext("private-id", "mcp", "selector", "rule"), 1); + }))).build()); + gateway = reactor.netty.http.server.HttpServer.create().host("127.0.0.1").port(0).handle(adapter).bindNow(WAIT); + } + + private Mono call(final String token) { + return Mono.defer(() -> { + HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + gateway.port() + "/agent/" + token)).timeout(WAIT) + .header("Content-Type", "application/json").header("Accept", "application/json, text/event-stream") + .header("MCP-Protocol-Version", "2026-07-28").header("Mcp-Method", "tools/call").header("Mcp-Name", "orders.lookup") + .header("Authorization", "Bearer private-agent-token").header("Cookie", "private-cookie").header("baggage", "subject=private") + .header("X-Agent-Private", "must-not-escape").header("X-Spike-Subject", "private-agent") + .header("traceparent", traceparent(token)).header("tracestate", "vendor=opaque") + .POST(HttpRequest.BodyPublishers.ofString(body(token), StandardCharsets.UTF_8)).build(); + return Mono.fromFuture(client.sendAsync(request, HttpResponse.BodyHandlers.ofString())).doOnNext(response -> { + assertEquals(200, response.statusCode(), response.body()); + assertTrue(response.body().contains("same-id")); + assertTrue(response.body().contains(token)); + assertFalse(response.body().contains("\"error\"")); + }).then(); + }); + } + + private String traceparent(final String token) { + String traceId = UUID.randomUUID().toString().replace("-", ""); + inboundTraces.put(token, traceId); + return "00-" + traceId + "-bbbbbbbbbbbbbbbb-01"; + } + + private String body(final String token) { + JsonObject body = JsonParser.parseString("{\"jsonrpc\":\"2.0\",\"id\":\"same-id\",\"method\":\"tools/call\",\"params\":{\"name\":\"orders.lookup\"," + + "\"arguments\":{},\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}}}").getAsJsonObject(); + body.getAsJsonObject("params").getAsJsonObject("arguments").addProperty("token", token); + return body.toString(); + } + + private CompletableFuture cancelWhilePeerPending() throws Exception { + try (Socket socket = openCancelledCall()) { + assertTrue(entered.await(10, TimeUnit.SECONDS)); + final CompletableFuture peer = call("peer").toFuture(); + assertTrue(peerEntered.await(10, TimeUnit.SECONDS)); + return peer; + } + } + + private Socket openCancelledCall() throws Exception { + Socket socket = new Socket(); + try { + socket.connect(new InetSocketAddress("127.0.0.1", gateway.port()), 3000); + socket.setSoLinger(true, 0); + byte[] body = body("cancel").getBytes(StandardCharsets.UTF_8); + String headers = "POST /agent/cancel HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\n" + + "Accept: application/json, text/event-stream\r\nMCP-Protocol-Version: 2026-07-28\r\n" + + "Mcp-Method: tools/call\r\nMcp-Name: orders.lookup\r\ntraceparent: " + traceparent("cancel") + + "\r\ntracestate: vendor=opaque\r\nbaggage: subject=private\r\nAuthorization: Bearer private-agent-token\r\n" + + "Cookie: private-cookie\r\nX-Agent-Private: must-not-escape\r\nContent-Length: " + body.length + "\r\n\r\n"; + socket.getOutputStream().write(headers.getBytes(StandardCharsets.UTF_8)); + socket.getOutputStream().write(body); + socket.getOutputStream().flush(); + return socket; + } catch (Exception error) { + socket.close(); + throw error; + } + } + + private void assertCalls(final int count) { + await().atMost(WAIT).until(() -> exporter.getFinishedSpanItems().size() == count * 2); + var spans = exporter.getFinishedSpanItems(); + List calls = requests.stream().filter(request -> "tools/call".equals(request.method())).toList(); + assertEquals(count, calls.size()); + assertEquals(count, calls.stream().map(Request::traceparent).distinct().count()); + for (Request request : calls) { + String[] trace = request.traceparent().split("-"); + assertEquals(4, trace.length); + var logical = spans.stream().filter(span -> trace[2].equals(span.getSpanId())).findFirst().orElseThrow(); + assertEquals("shenyu.agent_gateway.tools.call", logical.getName()); + assertEquals(SpanKind.INTERNAL, logical.getKind()); + assertEquals(trace[1], logical.getTraceId()); + assertEquals(inboundTraces.get(request.token()), logical.getTraceId()); + assertEquals(parents.get(request.token()), logical.getParentSpanId()); + var gateway = spans.stream().filter(span -> logical.getParentSpanId().equals(span.getSpanId())).findFirst().orElseThrow(); + assertEquals(SpanKind.SERVER, gateway.getKind()); + assertEquals(gateway.getTraceId(), logical.getTraceId()); + assertEquals("bbbbbbbbbbbbbbbb", gateway.getParentSpanId()); + assertTrue(request.headers().entrySet().stream().filter(entry -> "tracestate".equalsIgnoreCase(entry.getKey())) + .anyMatch(entry -> List.of("vendor=opaque").equals(entry.getValue()))); + assertEquals(1, request.headers().entrySet().stream().filter(entry -> "traceparent".equalsIgnoreCase(entry.getKey())) + .mapToInt(entry -> entry.getValue().size()).sum()); + } + } + + private void assertServiceIsolation() { + for (Request request : requests) { + if (!"tools/call".equals(request.method())) { + assertTrue(request.headers().keySet().stream().noneMatch(name -> "traceparent".equalsIgnoreCase(name) || "tracestate".equalsIgnoreCase(name))); + } + assertTrue(request.headers().keySet().stream().noneMatch(name -> "baggage".equalsIgnoreCase(name) + || "X-Spike-Subject".equalsIgnoreCase(name) || "Cookie".equalsIgnoreCase(name) || "X-Agent-Private".equalsIgnoreCase(name))); + assertTrue(request.headers().entrySet().stream().filter(entry -> "Authorization".equalsIgnoreCase(entry.getKey())) + .anyMatch(entry -> List.of("Bearer fixed-service-token").equals(entry.getValue()))); + } + } + + @Override + public void close() { + release.countDown(); + peerRelease.countDown(); + try { + gateway.disposeNow(WAIT); + catalog.closeAsync().block(WAIT); + assertServiceIsolation(); + } finally { + server.stop(0); + executor.shutdownNow(); + sdk.close(); + } + } + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java index 79170c723c45..e83f787028aa 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java @@ -18,6 +18,7 @@ package org.apache.shenyu.springboot.starter.plugin.ai.proxy; import io.netty.channel.ChannelOption; +import org.apache.shenyu.common.metrics.AiCallObserver; import org.apache.shenyu.plugin.ai.proxy.enhanced.AiProxyPlugin; import org.apache.shenyu.plugin.ai.proxy.enhanced.handler.AiProxyPluginHandler; import org.apache.shenyu.plugin.ai.proxy.enhanced.protocol.AiProxyProtocol; @@ -36,6 +37,7 @@ import org.apache.shenyu.plugin.ai.proxy.enhanced.transport.WebClientAiProxyTransport; import org.apache.shenyu.plugin.api.ShenyuPlugin; import org.apache.shenyu.sync.data.api.AiProxyApiKeyDataSubscriber; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -45,6 +47,7 @@ import org.springframework.web.reactive.function.client.WebClient; import reactor.netty.http.client.HttpClient; +import java.time.Duration; import java.util.List; /** @@ -63,17 +66,18 @@ public class AiProxyPluginConfiguration { * @param aiProxyConfigService the aiProxyConfigService * @param aiProxyEngine the aiProxyEngine * @param aiProxyPluginHandler the aiProxyPluginHandler + * @param observers optional application terminal sink * @return the shenyu plugin */ @Bean public ShenyuPlugin aiProxyPlugin( final AiProxyConfigService aiProxyConfigService, final AiProxyEngine aiProxyEngine, - final AiProxyPluginHandler aiProxyPluginHandler) { + final AiProxyPluginHandler aiProxyPluginHandler, final ObjectProvider observers) { return new AiProxyPlugin( aiProxyConfigService, aiProxyEngine, - aiProxyPluginHandler); + aiProxyPluginHandler, observer(observers)); } /** @@ -107,12 +111,21 @@ public AiProxyApiKeyDataSubscriber aiProxyApiKeyDataSubscriber() { * @param aiProxyProtocolFactory protocol factory * @param aiProxyProviderFactory provider factory * @param aiProxyTransport transport + * @param observers optional application terminal sink * @return the AI proxy engine */ @Bean public AiProxyEngine aiProxyEngine(final AiProxyProtocolFactory aiProxyProtocolFactory, - final AiProxyProviderFactory aiProxyProviderFactory, final AiProxyTransport aiProxyTransport) { - return new AiProxyEngine(aiProxyProtocolFactory, aiProxyProviderFactory, aiProxyTransport); + final AiProxyProviderFactory aiProxyProviderFactory, final AiProxyTransport aiProxyTransport, final ObjectProvider observers) { + return new AiProxyEngine(aiProxyProtocolFactory, aiProxyProviderFactory, aiProxyTransport, Duration.ofSeconds(1), observer(observers)); + } + + private AiCallObserver observer(final ObjectProvider provider) { + List candidates = provider.stream().toList(); + if (candidates.size() > 1) { + throw new IllegalStateException("AI terminal observation requires one unambiguous application sink"); + } + return candidates.isEmpty() ? null : candidates.get(0); } /** diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/test/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfigurationTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/test/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfigurationTest.java index 8ba08de9112f..0822bbecf39b 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/test/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfigurationTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/test/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfigurationTest.java @@ -17,6 +17,8 @@ package org.apache.shenyu.springboot.starter.plugin.ai.proxy; +import org.apache.shenyu.common.metrics.AiCallObserver; + import org.apache.shenyu.plugin.ai.common.spring.ai.registry.AiModelFactoryRegistry; import org.apache.shenyu.plugin.ai.common.config.AiCommonConfig; import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamRequest; @@ -52,6 +54,16 @@ class AiProxyPluginConfigurationTest { ConfigurationPropertiesAutoConfiguration.class, AiProxyPluginConfiguration.class)); + @Test + void acceptsOneApplicationObserverAndRejectsAmbiguousSinks() { + final AiCallObserver first = event -> { }; + final AiCallObserver second = event -> { }; + contextRunner.withBean("firstSink", AiCallObserver.class, () -> first) + .run(context -> org.assertj.core.api.Assertions.assertThat(context).hasNotFailed().hasSingleBean(AiProxyPlugin.class)); + contextRunner.withBean("firstSink", AiCallObserver.class, () -> first).withBean("secondSink", AiCallObserver.class, () -> second) + .run(context -> org.assertj.core.api.Assertions.assertThat(context).hasFailed()); + } + @Test void createsTheMigratedPluginAndAllExistingProviderIdentifiers() { new ApplicationContextRunner().withUserConfiguration(AiProxyPluginConfiguration.class).run(context -> { diff --git a/shenyu-web/src/test/java/org/apache/shenyu/web/handler/AgentGatewayPluginOrderingTest.java b/shenyu-web/src/test/java/org/apache/shenyu/web/handler/AgentGatewayPluginOrderingTest.java new file mode 100644 index 000000000000..07da86e2834f --- /dev/null +++ b/shenyu-web/src/test/java/org/apache/shenyu/web/handler/AgentGatewayPluginOrderingTest.java @@ -0,0 +1,190 @@ +/* + * 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.web.handler; + +import org.apache.shenyu.common.config.ShenyuConfig; +import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.enums.PluginEnum; +import org.apache.shenyu.common.enums.PluginHandlerEventEnum; +import org.apache.shenyu.plugin.api.ShenyuPlugin; +import org.apache.shenyu.plugin.api.ShenyuPluginChain; +import org.apache.shenyu.plugin.base.cache.BaseDataCache; +import org.apache.shenyu.plugin.base.cache.PluginHandlerEvent; +import org.apache.shenyu.web.loader.ShenyuLoaderService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; + +/** + * Real handler/cache ordering with lightweight plugins; not protocol integration tests. + */ +class AgentGatewayPluginOrderingTest { + + private static final List PLUGINS = Arrays.asList(PluginEnum.AI_PROXY, PluginEnum.AI_TOKEN_LIMITER, + PluginEnum.AI_PROMPT, PluginEnum.AGENT_GATEWAY, PluginEnum.KEY_AUTH); + + private final Map previous = new HashMap<>(); + + private final List executed = new ArrayList<>(); + + @BeforeEach + void isolatePluginCache() { + PLUGINS.forEach(plugin -> { + previous.put(plugin.getName(), BaseDataCache.getInstance().obtainPluginData(plugin.getName())); + BaseDataCache.getInstance().removePluginDataByPluginName(plugin.getName()); + }); + } + + @AfterEach + void restorePluginCache() { + PLUGINS.forEach(plugin -> { + BaseDataCache.getInstance().removePluginDataByPluginName(plugin.getName()); + BaseDataCache.getInstance().cachePluginData(previous.get(plugin.getName())); + }); + } + + @Test + void shouldUseEnumOrderWithoutCachedConfiguration() { + assertOrder(handler(false), "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"); + } + + @Test + void shouldUseCachedDefaultsWhenPluginsAreEnabled() { + PLUGINS.forEach(plugin -> cache(plugin, plugin.getCode())); + ShenyuWebHandler handler = handler(false); + handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.ENABLED, data(PluginEnum.AGENT_GATEWAY, PluginEnum.AGENT_GATEWAY.getCode()))); + assertOrder(handler, "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"); + } + + @Test + void shouldNotSilentlyRepairAnUnmigratedCachedGateway() { + cache(PluginEnum.AGENT_GATEWAY, 198); + assertOrder(handler(false), "keyAuth", "aiPrompt", "aiTokenLimiter", "agentGateway", "aiProxy"); + } + + @Test + void shouldRetainExplicitCustomOrdersEvenWhenUnsafe() { + cache(PluginEnum.AGENT_GATEWAY, 149); + cache(PluginEnum.AI_PROXY, 148); + assertOrder(handler(false), "aiProxy", "agentGateway", "keyAuth", "aiPrompt", "aiTokenLimiter"); + } + + @Test + void shouldApplyAnAdminSortEventAndFallBackAfterCacheRemoval() { + ShenyuWebHandler handler = handler(false); + cache(PluginEnum.AGENT_GATEWAY, 198); + handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.SORTED, data(PluginEnum.AGENT_GATEWAY, 198))); + assertOrder(handler, "keyAuth", "aiPrompt", "aiTokenLimiter", "agentGateway", "aiProxy"); + cache(PluginEnum.AGENT_GATEWAY, PluginEnum.AGENT_GATEWAY.getCode()); + handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.SORTED, data(PluginEnum.AGENT_GATEWAY, PluginEnum.AGENT_GATEWAY.getCode()))); + assertOrder(handler, "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"); + BaseDataCache.getInstance().removePluginDataByPluginName(PluginEnum.AGENT_GATEWAY.getName()); + handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.SORTED, data(PluginEnum.AGENT_GATEWAY, 198))); + assertOrder(handler, "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"); + } + + @Test + void shouldContinueFromGatewayThroughTheExistingAiChain() { + verifyChain(handler(false)); + assertEquals(Arrays.asList("keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"), executed); + } + + @Test + void shouldNotReachLlmPluginsWhenGatewayTerminates() { + verifyChain(handler(true)); + assertEquals(Arrays.asList("keyAuth", "agentGateway"), executed); + } + + @Test + void shouldLeaveTheOriginalAiChainWhenGatewayIsDisabled() { + ShenyuWebHandler handler = handler(false); + handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.DISABLED, data(PluginEnum.AGENT_GATEWAY, PluginEnum.AGENT_GATEWAY.getCode()))); + verifyChain(handler); + assertEquals(Arrays.asList("keyAuth", "aiPrompt", "aiTokenLimiter", "aiProxy"), executed); + } + + private ShenyuWebHandler handler(final boolean gatewayTerminates) { + List plugins = PLUGINS.stream().map(plugin -> new RecordingPlugin(plugin, gatewayTerminates)) + .collect(Collectors.toList()); + ShenyuWebHandler handler = new ShenyuWebHandler(plugins, mock(ShenyuLoaderService.class), new ShenyuConfig()); + handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.SORTED, data(PluginEnum.AGENT_GATEWAY, PluginEnum.AGENT_GATEWAY.getCode()))); + return handler; + } + + private void assertOrder(final ShenyuWebHandler handler, final String... names) { + assertEquals(Arrays.asList(names), handler.getPlugins().stream().map(ShenyuPlugin::named).collect(Collectors.toList())); + } + + private void verifyChain(final ShenyuWebHandler handler) { + StepVerifier.create(handler.handle(MockServerWebExchange.from(MockServerHttpRequest.post("/agent")))).verifyComplete(); + } + + private void cache(final PluginEnum plugin, final int sort) { + BaseDataCache.getInstance().cachePluginData(data(plugin, sort)); + } + + private PluginData data(final PluginEnum plugin, final int sort) { + return PluginData.builder().name(plugin.getName()).sort(sort).enabled(true).build(); + } + + private final class RecordingPlugin implements ShenyuPlugin { + + private final PluginEnum plugin; + + private final boolean gatewayTerminates; + + private RecordingPlugin(final PluginEnum plugin, final boolean gatewayTerminates) { + this.plugin = plugin; + this.gatewayTerminates = gatewayTerminates; + } + + @Override + public Mono execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) { + executed.add(named()); + if (gatewayTerminates && plugin == PluginEnum.AGENT_GATEWAY) { + return Mono.empty(); + } + return chain.execute(exchange); + } + + @Override + public int getOrder() { + return plugin.getCode(); + } + + @Override + public String named() { + return plugin.getName(); + } + } +} From f4392ce53df5e7588ea2fb184c8e8effdd192b95 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Wed, 21 Oct 2026 14:54:11 +0800 Subject: [PATCH 03/36] feat(agent-gateway): add runtime governance observability --- .../common/metrics/AgentCatalogMetrics.java | 75 +++++++++++++++ .../common/metrics/AgentRuntimeMetrics.java | 96 +++++++++++++++++++ .../common/metrics/AiRequestObservation.java | 26 +++++ .../metrics/AgentRuntimeMetricsTest.java | 69 +++++++++++++ .../agent/gateway/AgentGatewayPlugin.java | 5 +- .../gateway/protocol/AgentMcpHttpHandler.java | 8 +- .../protocol/AgentMcpTerminalObservation.java | 30 +++++- .../remote/ManagedRemoteMcpCatalog.java | 27 +++++- .../remote/RemoteCatalogLifecycle.java | 8 +- .../AgentMcpTerminalObservationTest.java | 59 ++++++++++++ .../remote/ManagedRemoteMcpCatalogTest.java | 26 +++++ .../remote/RemoteCatalogLifecycleTest.java | 3 +- .../ai/proxy/enhanced/AiProxyPlugin.java | 5 +- .../shenyu/plugin/metrics/MetricsPlugin.java | 2 + .../plugin/metrics/constant/LabelNames.java | 14 +++ .../AgentCatalogMetricsCollector.java | 57 +++++++++++ .../prometheus/PrometheusMetricsService.java | 1 + .../reporter/AgentRuntimeMetricsReporter.java | 90 +++++++++++++++++ .../metrics/reporter/MetricsReporter.java | 29 +++++- .../plugin/metrics/MetricsPluginTest.java | 55 +++++++++++ .../AgentCatalogMetricsCollectorTest.java | 67 +++++++++++++ .../shenyu/plugin/key/auth/KeyAuthPlugin.java | 10 ++ .../plugin/key/auth/KeyAuthPluginTest.java | 30 ++++++ .../pom.xml | 12 +++ .../AgentGatewayPluginConfiguration.java | 16 +++- .../OpenTelemetryAgentMcpCallTracer.java | 6 +- .../AgentGatewayPluginConfigurationTest.java | 25 +++++ .../gateway/AgentGovernanceHttpTest.java | 40 +++++++- .../OpenTelemetryAgentMcpOtlpTest.java | 50 ++++++++++ 29 files changed, 924 insertions(+), 17 deletions(-) create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentCatalogMetrics.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentRuntimeMetrics.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/metrics/AgentRuntimeMetricsTest.java create mode 100644 shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentCatalogMetricsCollector.java create mode 100644 shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java create mode 100644 shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentCatalogMetricsCollectorTest.java diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentCatalogMetrics.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentCatalogMetrics.java new file mode 100644 index 000000000000..282c59192a83 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentCatalogMetrics.java @@ -0,0 +1,75 @@ +/* + * 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.metrics; + +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** Live, payload-free catalog snapshots, aggregated without endpoint or generation labels. */ +public final class AgentCatalogMetrics implements AutoCloseable { + + private static final Set SOURCES = ConcurrentHashMap.newKeySet(); + + private final Supplier source; + + private AgentCatalogMetrics(final Supplier source) { + this.source = source; + } + + /** Register after the managed catalog starts; callers own the returned registration. + * @param source in-memory snapshot supplier, never network I/O + * @return registration removed only by its owner + */ + public static AgentCatalogMetrics register(final Supplier source) { + AgentCatalogMetrics registration = new AgentCatalogMetrics(java.util.Objects.requireNonNull(source)); + SOURCES.add(registration); + return registration; + } + + /** Capture active catalog states; a failed supplier is explicitly unavailable. + * @return immutable snapshots, with no identity labels + */ + public static List snapshots() { + return SOURCES.stream().map(registration -> { + try { + return java.util.Objects.requireNonNull(registration.source.get()); + } catch (RuntimeException ignored) { + return new Snapshot(false, false, 0, 0, 0, 0, true); + } + }).toList(); + } + + @Override + public void close() { + SOURCES.remove(this); + } + + /** Catalog state, not session or physical connection counts. + * @param available a current usable directory exists + * @param updating a generation is being built + * @param generations retained generations + * @param clients owned endpoint clients, not socket count + * @param references active generation leases, not sessions + * @param pending owned endpoint HTTP requests, not logical MCP calls + * @param failed configuration or cleanup diagnostics contain failure + */ + public record Snapshot(boolean available, boolean updating, int generations, int clients, int references, int pending, boolean failed) { + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentRuntimeMetrics.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentRuntimeMetrics.java new file mode 100644 index 000000000000..4fd85586e3c2 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentRuntimeMetrics.java @@ -0,0 +1,96 @@ +/* + * 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.metrics; + +/** + * Optional request-scoped metrics port. Only closed enums cross this boundary; + * identities, tool names, payloads and credentials are never metric labels. + */ +public interface AgentRuntimeMetrics { + + String KEY = AgentRuntimeMetrics.class.getName(); + + AgentRuntimeMetrics NOOP = new AgentRuntimeMetrics() { }; + + /** Count one subscription owned by the MCP or AI logical-request boundary. + * @param traffic bounded traffic type + */ + default void started(final Traffic traffic) { + } + + /** Release one subscription and report its terminal outcome. + * @param traffic bounded traffic type + * @param outcome terminal outcome + * @param reason bounded failure category + * @param millis monotonic duration + */ + default void finished(final Traffic traffic, final Outcome outcome, final Reason reason, final long millis) { + } + + /** Count an actually completed AI upstream attempt, separately from the logical request. + * @param kind primary, retry or fallback + * @param outcome attempt outcome + * @param millis attempt duration + */ + default void attempt(final AiAttemptEvent.Kind kind, final Outcome outcome, final long millis) { + } + + /** Record catalog availability at lease acquisition, not an always-current health gauge. + * @param available whether the request acquired a catalog snapshot + */ + default void catalog(final boolean available) { + } + + /** Observe an authentication plugin rejection before Agent routing is known. + * @param source fixed authentication adapter + * @param reason credential rejection or invalid server configuration + */ + default void authenticationRejected(final AuthenticationSource source, final AuthenticationReason reason) { + } + + /** Isolate metrics failures from forwarding, including cancellation cleanup. + * @param callback bounded metrics operation + */ + static void safely(final Runnable callback) { + try { + callback.run(); + } catch (RuntimeException ignored) { + // Never log callback messages: a custom reporter may include sensitive data. + } + } + + enum Traffic { + MCP, LLM + } + + enum Outcome { + SUCCESS, TOOL_ERROR, ERROR, TIMEOUT, CANCELLED, REJECTED, RATE_LIMITED + } + + enum Reason { + NONE, AUTHENTICATION, AUTHORIZATION, RESOURCE_LIMIT, CATALOG_UNAVAILABLE, PROTOCOL, OTHER + } + + enum AuthenticationSource { + KEY_AUTH + } + + enum AuthenticationReason { + CREDENTIAL_REJECTED, INVALID_CONFIGURATION + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java index f9954343969f..aad56c87255f 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java @@ -35,6 +35,8 @@ public final class AiRequestObservation { private final AiCallObserver observer; + private final AgentRuntimeMetrics metrics; + private final long started = System.nanoTime(); private AgentRequestContext context; @@ -50,8 +52,14 @@ public final class AiRequestObservation { private boolean completed; public AiRequestObservation(final AiCallObserver observer, final AgentRequestContext context) { + this(observer, context, AgentRuntimeMetrics.NOOP); + } + + public AiRequestObservation(final AiCallObserver observer, final AgentRequestContext context, final AgentRuntimeMetrics metrics) { this.observer = observer; this.context = Objects.requireNonNull(context, "context"); + this.metrics = Objects.requireNonNull(metrics, "metrics"); + AgentRuntimeMetrics.safely(() -> metrics.started(AgentRuntimeMetrics.Traffic.LLM)); } public synchronized AgentRequestContext getContext() { @@ -137,6 +145,8 @@ public void finish(final SignalType signal, final Integer httpStatus) { terminalEvent = new AiTerminalEvent(context, outcome, httpStatus, elapsed(started), attempts, usage); } recordAttempt(attemptEvent); + AgentRuntimeMetrics.safely(() -> metrics.finished(AgentRuntimeMetrics.Traffic.LLM, + AgentRuntimeMetrics.Outcome.valueOf(terminalEvent.outcome().name()), reason(terminalEvent.httpStatus()), terminalEvent.elapsedMillis())); if (Objects.nonNull(observer)) { try { observer.record(terminalEvent); @@ -147,6 +157,9 @@ public void finish(final SignalType signal, final Integer httpStatus) { } private void recordAttempt(final AiAttemptEvent event) { + if (Objects.nonNull(event)) { + AgentRuntimeMetrics.safely(() -> metrics.attempt(event.kind(), AgentRuntimeMetrics.Outcome.valueOf(event.outcome().name()), event.elapsedMillis())); + } if (Objects.nonNull(observer) && Objects.nonNull(event)) { try { observer.recordAttempt(event); @@ -156,6 +169,19 @@ private void recordAttempt(final AiAttemptEvent event) { } } + private static AgentRuntimeMetrics.Reason reason(final Integer status) { + if (Objects.equals(status, 401)) { + return AgentRuntimeMetrics.Reason.AUTHENTICATION; + } + if (Objects.equals(status, 403)) { + return AgentRuntimeMetrics.Reason.AUTHORIZATION; + } + if (Objects.equals(status, 413) || Objects.equals(status, 429)) { + return AgentRuntimeMetrics.Reason.RESOURCE_LIMIT; + } + return AgentRuntimeMetrics.Reason.NONE; + } + /** * Classify explicit HTTP status without treating a cancelled write as delivered. * @param status assigned status diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/metrics/AgentRuntimeMetricsTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/metrics/AgentRuntimeMetricsTest.java new file mode 100644 index 000000000000..5e2fe48afe4d --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/metrics/AgentRuntimeMetricsTest.java @@ -0,0 +1,69 @@ +/* + * 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.metrics; + +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.SignalType; + +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +class AgentRuntimeMetricsTest { + + @Test + void attemptsAreSeparateFromOneLogicalRequestAndTheApplicationObserver() { + AgentRuntimeMetrics metrics = mock(AgentRuntimeMetrics.class); + AiCallObserver observer = mock(AiCallObserver.class); + AgentRequestContext context = new AgentRequestContext("private-id", "llm", "selector", "rule"); + AiRequestObservation request = new AiRequestObservation(observer, context, metrics); + AiRequestObservation.Attempt first = request.startAttempt(context, AiAttemptEvent.Kind.PRIMARY, "private-provider", "private-protocol", false); + first.finish(SignalType.ON_ERROR, AiCallOutcome.TIMEOUT); + first.finish(SignalType.ON_ERROR, AiCallOutcome.TIMEOUT); + AiRequestObservation.Attempt second = request.startAttempt(context, AiAttemptEvent.Kind.RETRY, "private-provider", "private-protocol", true); + second.status(200); + second.finish(SignalType.ON_COMPLETE, null); + request.finish(SignalType.ON_COMPLETE, 200); + request.finish(SignalType.CANCEL, null); + verify(metrics).started(AgentRuntimeMetrics.Traffic.LLM); + verify(metrics).attempt(eq(AiAttemptEvent.Kind.PRIMARY), eq(AgentRuntimeMetrics.Outcome.TIMEOUT), anyLong()); + verify(metrics).attempt(eq(AiAttemptEvent.Kind.RETRY), eq(AgentRuntimeMetrics.Outcome.SUCCESS), anyLong()); + verify(metrics).finished(eq(AgentRuntimeMetrics.Traffic.LLM), eq(AgentRuntimeMetrics.Outcome.SUCCESS), eq(AgentRuntimeMetrics.Reason.NONE), anyLong()); + verifyNoMoreInteractions(metrics); + verify(observer, times(2)).recordAttempt(org.mockito.ArgumentMatchers.any()); + verify(observer).record(org.mockito.ArgumentMatchers.any()); + } + + @Test + void cancellationFreezesTheOutstandingAttemptAndReleasesLogicalInflightOnce() { + AgentRuntimeMetrics metrics = mock(AgentRuntimeMetrics.class); + AgentRequestContext context = new AgentRequestContext("id", "llm", "s", "r"); + AiRequestObservation request = new AiRequestObservation(null, context, metrics); + AiRequestObservation.Attempt attempt = request.startAttempt(context, AiAttemptEvent.Kind.FALLBACK, "p", "p", true); + request.finish(SignalType.CANCEL, null); + attempt.finish(SignalType.CANCEL, null); + verify(metrics).started(AgentRuntimeMetrics.Traffic.LLM); + verify(metrics).attempt(eq(AiAttemptEvent.Kind.FALLBACK), eq(AgentRuntimeMetrics.Outcome.CANCELLED), anyLong()); + verify(metrics).finished(eq(AgentRuntimeMetrics.Traffic.LLM), eq(AgentRuntimeMetrics.Outcome.CANCELLED), eq(AgentRuntimeMetrics.Reason.NONE), anyLong()); + verifyNoMoreInteractions(metrics); + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java index 98a7a50057e8..61908c9e6b57 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java @@ -21,6 +21,7 @@ import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.dto.AgentRequestContext; import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.common.metrics.AiCallOutcome; import org.apache.shenyu.common.metrics.AiRequestObservation; import org.apache.shenyu.common.enums.PluginEnum; @@ -104,7 +105,9 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu private Mono handleLlm(final ServerWebExchange exchange, final ShenyuPluginChain chain, final AgentRequestContext initial) { return Mono.defer(() -> { - AiRequestObservation observation = new AiRequestObservation(aiObserver, initial); + Object callback = exchange.getAttribute(AgentRuntimeMetrics.KEY); + AiRequestObservation observation = new AiRequestObservation(aiObserver, initial, + callback instanceof AgentRuntimeMetrics metrics ? metrics : AgentRuntimeMetrics.NOOP); Mono identity = Objects.isNull(llmSecurityResolver) ? Mono.just(initial) : Mono.defer(() -> llmSecurityResolver.resolve(exchange)) .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED))) diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java index 35cb0ceeb1b4..f93c4a5057bc 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java @@ -25,6 +25,7 @@ import org.apache.shenyu.common.dto.AgentRequestContext; import org.apache.shenyu.common.metrics.AgentMcpCallObserver; import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; import org.springframework.core.io.buffer.DataBuffer; @@ -97,8 +98,10 @@ public AgentMcpHttpHandler(final AgentMcpDispatcher dispatcher, final AgentMcpSe public Mono handle(final ServerWebExchange exchange, final AgentGatewayMcpConfig config, final AgentTrafficContext traffic, final long configurationVersion) { return Mono.deferContextual(parentContext -> { - final AgentMcpTerminalObservation terminal = Objects.isNull(terminalObserver) ? null - : new AgentMcpTerminalObservation(terminalObserver, traffic, configurationVersion); + Object runtimeCallback = exchange.getAttribute(AgentRuntimeMetrics.KEY); + final AgentRuntimeMetrics metrics = runtimeCallback instanceof AgentRuntimeMetrics value ? value : AgentRuntimeMetrics.NOOP; + final AgentMcpTerminalObservation terminal = Objects.isNull(terminalObserver) && metrics == AgentRuntimeMetrics.NOOP ? null + : new AgentMcpTerminalObservation(terminalObserver, traffic, configurationVersion, metrics); final Instant deadline = Instant.now().plusMillis(config.getTimeoutMs()); Object callback = exchange.getAttribute(Constants.METRICS_AGENT_MCP_CALL); final AgentMcpCallObservation observation = new AgentMcpCallObservation(callback instanceof AgentMcpCallObserver observer ? observer : null, @@ -123,6 +126,7 @@ public Mono handle(final ServerWebExchange exchange, final AgentGatewayMcp identity.getSubject(), traffic.getRuleId(), configurationVersion, config.getAllowedTools(), identity.getToolGrants(), deadline, config.getResultFilters(), identity.getTenant().orElse(null))) .contextWrite(observation::traceContext) + .contextWrite(context -> context.put(AgentRuntimeMetrics.KEY, metrics)) .contextWrite(context -> context.put(AgentRequestContext.REACTOR_KEY, traffic.toRequestContext(configurationVersion).withIdentity(identity.getTenant().orElse(null), identity.getSubject()) .withTarget("tools/call".equals(request.getMethod()) ? request.getParams().path("name").textValue() : null, diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java index 2d5c334a1d5e..3b5a46634974 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java @@ -20,6 +20,7 @@ import org.apache.shenyu.common.metrics.AgentMcpCallObserver.Outcome; import org.apache.shenyu.common.metrics.AgentMcpTerminalEvent; import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,6 +40,10 @@ final class AgentMcpTerminalObservation { private final AgentMcpTerminalObserver observer; + private final AgentRuntimeMetrics metrics; + + private AgentRuntimeMetrics.Reason reason = AgentRuntimeMetrics.Reason.NONE; + private final AgentTrafficContext traffic; private final long configurationVersion; @@ -60,9 +65,16 @@ final class AgentMcpTerminalObservation { private boolean completed; AgentMcpTerminalObservation(final AgentMcpTerminalObserver observer, final AgentTrafficContext traffic, final long configurationVersion) { + this(observer, traffic, configurationVersion, AgentRuntimeMetrics.NOOP); + } + + AgentMcpTerminalObservation(final AgentMcpTerminalObserver observer, final AgentTrafficContext traffic, final long configurationVersion, + final AgentRuntimeMetrics metrics) { this.observer = observer; this.traffic = traffic; this.configurationVersion = configurationVersion; + this.metrics = metrics; + AgentRuntimeMetrics.safely(() -> metrics.started(AgentRuntimeMetrics.Traffic.MCP)); } synchronized void identified(final String value) { @@ -100,6 +112,17 @@ synchronized void failure(final Throwable error, final Integer transportStatus) if (error instanceof AgentMcpProtocolException) { status = ((AgentMcpProtocolException) error).getHttpStatus(); } + if (Objects.equals(status, 401)) { + reason = AgentRuntimeMetrics.Reason.AUTHENTICATION; + } else if (Objects.equals(status, 403)) { + reason = Objects.isNull(method) ? AgentRuntimeMetrics.Reason.PROTOCOL : AgentRuntimeMetrics.Reason.AUTHORIZATION; + } else if (error instanceof DataBufferLimitException || Objects.equals(status, 413) || Objects.equals(status, 429)) { + reason = AgentRuntimeMetrics.Reason.RESOURCE_LIMIT; + } else if (error.getCause() instanceof AgentMcpRemoteCatalog.CatalogUnavailableException) { + reason = AgentRuntimeMetrics.Reason.CATALOG_UNAVAILABLE; + } else { + reason = Objects.nonNull(status) && status < 500 ? AgentRuntimeMetrics.Reason.PROTOCOL : AgentRuntimeMetrics.Reason.OTHER; + } if (error instanceof TimeoutException || Objects.equals(status, 504)) { outcome = Outcome.TIMEOUT; } else if (error instanceof DataBufferLimitException || Objects.nonNull(status) && status < 500) { @@ -120,8 +143,13 @@ void finish(final SignalType signal, final Integer status) { .withTarget(requestedTool, method, protocolVersion), signal == SignalType.CANCEL ? Outcome.CANCELLED : outcome, TimeUnit.NANOSECONDS.toMillis(Math.max(0, System.nanoTime() - started)), status); } + AgentRuntimeMetrics.safely(() -> metrics.finished(AgentRuntimeMetrics.Traffic.MCP, + event.getOutcome() == Outcome.SERVER_ERROR ? AgentRuntimeMetrics.Outcome.ERROR : AgentRuntimeMetrics.Outcome.valueOf(event.getOutcome().name()), + reason, event.getElapsedMillis())); try { - observer.record(event); + if (Objects.nonNull(observer)) { + observer.record(event); + } } catch (RuntimeException error) { // Callback messages may contain sensitive application data. LOG.debug("MCP terminal event callback failed"); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java index 0754c6e81b31..78688caa9cb6 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java @@ -24,6 +24,8 @@ import io.modelcontextprotocol.common.McpTransportContext; import org.apache.shenyu.common.dto.AgentGatewayAggregationConfig; import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.apache.shenyu.common.metrics.AgentCatalogMetrics; import org.apache.shenyu.common.tracing.AgentTraceContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpRemoteCatalog; @@ -72,6 +74,8 @@ public final class ManagedRemoteMcpCatalog implements AgentMcpRemoteCatalog, Aut private final Disposable worker; + private final AgentCatalogMetrics catalogMetrics; + private volatile String lastFailure = ""; private volatile boolean closed; @@ -90,6 +94,14 @@ public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set { + Diagnostics state = diagnosticsState(); + RemoteCatalogLifecycle.Diagnostics lifecycleState = state.lifecycle(); + return new AgentCatalogMetrics.Snapshot(!closed && !lifecycleState.closed() && lifecycleState.currentVersion() > 0, + lifecycleState.updating(), lifecycleState.generations(), lifecycleState.clients(), lifecycleState.references(), + lifecycleState.pending(), + !state.lastFailure().isEmpty() || !lifecycleState.cleanupFailures().isEmpty()); + }); } private Mono applyUpdate(final ControlUpdate update) { @@ -157,7 +169,19 @@ private Mono reload(final String source, final BooleanSupplier stillCurren @Override public Mono withSnapshot(final Function> operation) { - return lifecycle.withSnapshot(directory -> operation.apply(new CatalogSnapshot(directory))); + return Mono.deferContextual(context -> { + AgentRuntimeMetrics metrics = context.getOrDefault(AgentRuntimeMetrics.KEY, AgentRuntimeMetrics.NOOP); + java.util.concurrent.atomic.AtomicBoolean acquired = new java.util.concurrent.atomic.AtomicBoolean(); + return lifecycle.withSnapshot(directory -> { + acquired.set(true); + AgentRuntimeMetrics.safely(() -> metrics.catalog(true)); + return operation.apply(new CatalogSnapshot(directory)); + }).doOnError(CatalogUnavailableException.class, error -> { + if (!acquired.get()) { + AgentRuntimeMetrics.safely(() -> metrics.catalog(false)); + } + }); + }); } /** @@ -192,6 +216,7 @@ private synchronized void recordFailure(final long sequence, final String catego public Mono closeAsync() { return Mono.defer(() -> { closed = true; + catalogMetrics.close(); worker.dispose(); scheduler.dispose(); return lifecycle.closeGracefully(); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java index f976b5f72a0a..38cbd68ee169 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java @@ -387,7 +387,9 @@ public Map diagnostics() { public Diagnostics diagnosticsState() { synchronized (lock) { return new Diagnostics(closed, Objects.nonNull(updatingGeneration), generations.size(), owners.size(), - generations.stream().mapToInt(g -> g.references).sum(), Objects.isNull(current) ? 0L : current.version, cleanupFailures); + generations.stream().mapToInt(g -> g.references).sum(), + generations.stream().flatMap(g -> g.clients.stream()).mapToInt(RemoteMcpEndpoint::pending).sum(), + Objects.isNull(current) ? 0L : current.version, cleanupFailures); } } @@ -455,7 +457,7 @@ private void signalDrain() { } /** Immutable lifecycle diagnostics; map export is retained for existing management consumers. */ - public record Diagnostics(boolean closed, boolean updating, int generations, int clients, int references, + public record Diagnostics(boolean closed, boolean updating, int generations, int clients, int references, int pending, long currentVersion, List cleanupFailures) { public Diagnostics { cleanupFailures = List.copyOf(cleanupFailures); @@ -467,7 +469,7 @@ public record Diagnostics(boolean closed, boolean updating, int generations, int */ public Map toMap() { return Map.of("closed", closed, "updating", updating, "generations", generations, "clients", clients, - "references", references, "currentVersion", currentVersion, "cleanupFailures", cleanupFailures); + "references", references, "pending", pending, "currentVersion", currentVersion, "cleanupFailures", cleanupFailures); } } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java index ef3c93587876..1cb6a67a26e3 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java @@ -26,6 +26,7 @@ import org.apache.shenyu.common.metrics.AgentMcpCallObserver.Outcome; import org.apache.shenyu.common.metrics.AgentMcpTerminalEvent; import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpIdentity; import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; @@ -80,6 +81,64 @@ class AgentMcpTerminalObservationTest { private final AgentTrafficContext traffic = new AgentTrafficContext("gateway-id", "mcp", "selector", "rule"); + @Test + void runtimeMetricsWorkWithoutAnApplicationObserverBeforeParsing() { + AgentRuntimeMetrics metrics = mock(AgentRuntimeMetrics.class); + MockServerWebExchange exchange = exchange("tools/call"); + exchange.getAttributes().put(AgentRuntimeMetrics.KEY, metrics); + StepVerifier.create(handler(Mono.just(new JsonObject()), ignored -> Mono.empty(), null) + .handle(exchange, config("json", 30000), traffic, 1)).verifyComplete(); + verify(metrics).started(AgentRuntimeMetrics.Traffic.MCP); + verify(metrics).finished(org.mockito.ArgumentMatchers.eq(AgentRuntimeMetrics.Traffic.MCP), + org.mockito.ArgumentMatchers.eq(AgentRuntimeMetrics.Outcome.REJECTED), + org.mockito.ArgumentMatchers.eq(AgentRuntimeMetrics.Reason.AUTHENTICATION), org.mockito.ArgumentMatchers.anyLong()); + } + + @Test + void runtimeMetricsFinishOnceOnCancellationEvenIfApplicationObserverThrows() { + AgentRuntimeMetrics metrics = mock(AgentRuntimeMetrics.class); + AgentMcpTerminalObservation observation = new AgentMcpTerminalObservation(event -> { + throw new IllegalStateException("private"); + }, traffic, 1, metrics); + observation.finish(SignalType.CANCEL, null); + observation.finish(SignalType.ON_COMPLETE, 200); + verify(metrics).started(AgentRuntimeMetrics.Traffic.MCP); + verify(metrics).finished(org.mockito.ArgumentMatchers.eq(AgentRuntimeMetrics.Traffic.MCP), + org.mockito.ArgumentMatchers.eq(AgentRuntimeMetrics.Outcome.CANCELLED), + org.mockito.ArgumentMatchers.eq(AgentRuntimeMetrics.Reason.NONE), org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verifyNoMoreInteractions(metrics); + } + + @ParameterizedTest + @CsvSource({"401,AUTHENTICATION", "403,PROTOCOL", "413,RESOURCE_LIMIT", "429,RESOURCE_LIMIT", "400,PROTOCOL", "500,OTHER"}) + void runtimeMetricsUseBoundedFailureReasons(final int status, final AgentRuntimeMetrics.Reason reason) { + AgentRuntimeMetrics metrics = mock(AgentRuntimeMetrics.class); + AgentMcpTerminalObservation observation = new AgentMcpTerminalObservation(null, traffic, 1, metrics); + observation.failure(new IllegalStateException("private"), status); + observation.finish(SignalType.ON_COMPLETE, status); + verify(metrics).finished(org.mockito.ArgumentMatchers.eq(AgentRuntimeMetrics.Traffic.MCP), org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(reason), org.mockito.ArgumentMatchers.anyLong()); + } + + @Test + void metricsFailureCannotChangeTheMcpResult() { + AgentRuntimeMetrics metrics = new AgentRuntimeMetrics() { + @Override + public void started(final Traffic trafficType) { + throw new IllegalStateException("private"); + } + + @Override + public void finished(final Traffic trafficType, final AgentRuntimeMetrics.Outcome outcome, final Reason reason, final long millis) { + throw new IllegalStateException("private"); + } + }; + MockServerWebExchange exchange = exchange("tools/call"); + exchange.getAttributes().put(AgentRuntimeMetrics.KEY, metrics); + StepVerifier.create(handler(Mono.just(new JsonObject()), identity(), null).handle(exchange, config("json", 30000), traffic, 1)).verifyComplete(); + assertEquals(200, exchange.getResponse().getStatusCode().value()); + } + @Test void trustedTenantAndCommonContextReachProviderAndTerminalWithoutSessionFabrication() { Recording observer = new Recording(); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalogTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalogTest.java index d641a54c3c6a..d8db97a88908 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalogTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalogTest.java @@ -21,6 +21,10 @@ import com.sun.net.httpserver.HttpServer; import io.modelcontextprotocol.common.McpTransportContext; import org.apache.shenyu.common.dto.PluginData; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpRemoteCatalog; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -45,6 +49,28 @@ class ManagedRemoteMcpCatalogTest { + @Test + void catalogMetricsDescribeAcquisitionNotBusinessOutcome() { + AgentRuntimeMetrics metrics = org.mockito.Mockito.mock(AgentRuntimeMetrics.class); + ManagedRemoteMcpCatalog catalog = new ManagedRemoteMcpCatalog(Set.of(), Set.of(), reference -> { + throw new IllegalStateException("No credentials expected"); + }); + try { + StepVerifier.create(catalog.withSnapshot(snapshot -> Mono.error(new AgentMcpRemoteCatalog.CatalogUnavailableException())) + .contextWrite(context -> context.put(AgentRuntimeMetrics.KEY, metrics))) + .expectError(AgentMcpRemoteCatalog.CatalogUnavailableException.class).verify(); + org.mockito.Mockito.verify(metrics).catalog(true); + org.mockito.Mockito.verify(metrics, org.mockito.Mockito.never()).catalog(false); + catalog.close(); + StepVerifier.create(catalog.withSnapshot(snapshot -> Mono.just(new ObjectMapper().createObjectNode())) + .contextWrite(context -> context.put(AgentRuntimeMetrics.KEY, metrics))) + .expectError(AgentMcpRemoteCatalog.CatalogUnavailableException.class).verify(); + org.mockito.Mockito.verify(metrics).catalog(false); + } finally { + catalog.close(); + } + } + @Test void newerFencedEventClearsOnlyTheSupersededFailureDiagnostic() throws Exception { CountDownLatch entered = new CountDownLatch(1); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycleTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycleTest.java index 0face49f11a2..4e88352a164b 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycleTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycleTest.java @@ -65,7 +65,8 @@ void typedDiagnosticSnapshotIsImmutableAndKeepsLegacyExportShape() { var after = manager.diagnosticsState(); assertEquals(0L, before.currentVersion()); assertEquals(1L, after.currentVersion()); - assertEquals(Set.of("closed", "updating", "generations", "clients", "references", "currentVersion", "cleanupFailures"), after.toMap().keySet()); + assertEquals(Set.of("closed", "updating", "generations", "clients", "references", "pending", "currentVersion", "cleanupFailures"), after.toMap().keySet()); + assertEquals(0, after.pending()); assertEquals(after.toMap(), manager.diagnostics()); assertThrows(UnsupportedOperationException.class, () -> after.toMap().clear()); manager.closeGracefully().block(WAIT); diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java index ef4953fa51db..47b87efc2b5c 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java @@ -25,6 +25,7 @@ import org.apache.shenyu.common.enums.PluginEnum; import org.apache.shenyu.common.exception.ShenyuException; import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.common.metrics.AiRequestObservation; import org.apache.shenyu.plugin.ai.common.config.AiCommonConfig; import org.apache.shenyu.plugin.ai.proxy.enhanced.cache.AiProxyApiKeyCache; @@ -93,8 +94,10 @@ public AiProxyPlugin(final AiProxyConfigService aiProxyConfigService, final AiPr protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { return Mono.deferContextual(view -> { AiRequestObservation inherited = view.getOrDefault(AiRequestObservation.REACTOR_KEY, null); + Object callback = exchange.getAttribute(AgentRuntimeMetrics.KEY); AiRequestObservation observation = Objects.nonNull(inherited) ? inherited - : new AiRequestObservation(observer, AiObservationSupport.context(view, selector.getId(), rule.getId())); + : new AiRequestObservation(observer, AiObservationSupport.context(view, selector.getId(), rule.getId()), + callback instanceof AgentRuntimeMetrics metrics ? metrics : AgentRuntimeMetrics.NOOP); return executeRequest(exchange, selector) .doOnError(error -> observation.failure(AiObservationSupport.outcome(error))) .onErrorResume(error -> handleFailure(exchange.getResponse(), error)) diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/MetricsPlugin.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/MetricsPlugin.java index e20f28c9517e..5b185649cbd8 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/MetricsPlugin.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/MetricsPlugin.java @@ -20,6 +20,7 @@ import org.apache.shenyu.common.constant.Constants; import org.apache.shenyu.common.enums.PluginEnum; import org.apache.shenyu.common.metrics.AgentMcpCallObserver; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.common.utils.DateUtils; import org.apache.shenyu.plugin.api.ShenyuPlugin; import org.apache.shenyu.plugin.api.ShenyuPluginChain; @@ -58,6 +59,7 @@ public Mono execute(final ServerWebExchange exchange, final ShenyuPluginCh } private void setMetricsCallbacks(final ServerWebExchange exchange) { + exchange.getAttributes().put(AgentRuntimeMetrics.KEY, MetricsReporter.agentRuntimeMetrics()); // Metrics must run before Agent Gateway so its per-subscription observation can capture this callback. exchange.getAttributes().put(Constants.METRICS_AGENT_MCP_CALL, (AgentMcpCallObserver) (outcome, millis) -> { String[] labels = {outcome.name().toLowerCase(Locale.ROOT)}; diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/constant/LabelNames.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/constant/LabelNames.java index 1f2f16d4daf5..6b72d0767c89 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/constant/LabelNames.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/constant/LabelNames.java @@ -22,6 +22,20 @@ */ public final class LabelNames { + public static final String AGENT_REQUESTS_TOTAL = "shenyu_agent_requests_total"; + + public static final String AGENT_REQUEST_LATENCY = "shenyu_agent_request_latency_millis"; + + public static final String AGENT_REQUESTS_INFLIGHT = "shenyu_agent_requests_inflight"; + + public static final String AGENT_AI_ATTEMPTS_TOTAL = "shenyu_agent_ai_attempts_total"; + + public static final String AGENT_AI_ATTEMPT_LATENCY = "shenyu_agent_ai_attempt_latency_millis"; + + public static final String AGENT_CATALOG_OBSERVATIONS_TOTAL = "shenyu_agent_catalog_observations_total"; + + public static final String AUTHENTICATION_REJECTIONS_TOTAL = "shenyu_authentication_rejections_total"; + /** Records accepted at the logging queue admission boundary, not backend deliveries. */ public static final String LOGGING_QUEUE_ACCEPTED_TOTAL = "shenyu_logging_queue_accepted_total"; diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentCatalogMetricsCollector.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentCatalogMetricsCollector.java new file mode 100644 index 000000000000..fcca998dfafd --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentCatalogMetricsCollector.java @@ -0,0 +1,57 @@ +/* + * 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.plugin.metrics.prometheus; + +import io.prometheus.client.Collector; +import io.prometheus.client.GaugeMetricFamily; +import org.apache.shenyu.common.metrics.AgentCatalogMetrics; + +import java.util.List; + +/** On-scrape catalog state using the existing exporter, without polling or another SDK. */ +public final class AgentCatalogMetricsCollector extends Collector implements Collector.Describable { + + @Override + public List collect() { + return samples(AgentCatalogMetrics.snapshots()); + } + + @Override + public List describe() { + return samples(List.of()); + } + + private List samples(final List states) { + GaugeMetricFamily catalogs = new GaugeMetricFamily("shenyu_agent_catalog_instances", "Owned catalogs grouped by current availability", List.of("state")); + catalogs.addMetric(List.of("available"), states.stream().filter(AgentCatalogMetrics.Snapshot::available).count()); + catalogs.addMetric(List.of("unavailable"), states.stream().filter(state -> !state.available()).count()); + GaugeMetricFamily updating = new GaugeMetricFamily("shenyu_agent_catalog_updating", "Owned catalogs currently refreshing", + states.stream().filter(AgentCatalogMetrics.Snapshot::updating).count()); + GaugeMetricFamily failed = new GaugeMetricFamily("shenyu_agent_catalog_failed", "Owned catalogs with configuration or cleanup failure", + states.stream().filter(AgentCatalogMetrics.Snapshot::failed).count()); + GaugeMetricFamily clients = new GaugeMetricFamily("shenyu_agent_catalog_clients", "Owned endpoint clients, not physical connections", + states.stream().mapToLong(AgentCatalogMetrics.Snapshot::clients).sum()); + GaugeMetricFamily leases = new GaugeMetricFamily("shenyu_agent_catalog_leases", "Active generation leases, not MCP sessions", + states.stream().mapToLong(AgentCatalogMetrics.Snapshot::references).sum()); + GaugeMetricFamily pending = new GaugeMetricFamily("shenyu_agent_catalog_pending_requests", "Owned endpoint HTTP requests, not logical MCP calls", + states.stream().mapToLong(AgentCatalogMetrics.Snapshot::pending).sum()); + GaugeMetricFamily generations = new GaugeMetricFamily("shenyu_agent_catalog_generations", "Retained directory generations", + states.stream().mapToLong(AgentCatalogMetrics.Snapshot::generations).sum()); + return List.of(catalogs, updating, failed, clients, leases, pending, generations); + } +} diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java index 3a0dc2d328ad..fbe9bf7db1ba 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java @@ -102,6 +102,7 @@ private void register(final MetricsConfig config) { return; } new LoggingQueueMetricsCollector().register(); + new AgentCatalogMetricsCollector().register(); String jvmEnabled = String.valueOf(config.getProps().getProperty("jvm_enabled")); if (StringUtils.isNotEmpty(jvmEnabled)) { boolean enabled = Boolean.parseBoolean(jvmEnabled); diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java new file mode 100644 index 000000000000..7573b331ddec --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java @@ -0,0 +1,90 @@ +/* + * 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.plugin.metrics.reporter; + +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.apache.shenyu.common.metrics.AiAttemptEvent; +import org.apache.shenyu.plugin.metrics.constant.LabelNames; +import org.apache.shenyu.plugin.metrics.spi.MetricsRegister; + +import java.util.Locale; + +/** Binds each request to the registry it started with, not a later reloaded registry. */ +final class AgentRuntimeMetricsReporter implements AgentRuntimeMetrics { + + private final MetricsRegister register; + + private boolean active = true; + + AgentRuntimeMetricsReporter(final MetricsRegister register) { + this.register = register; + } + + @Override + public synchronized void started(final Traffic traffic) { + if (active) { + register.gaugeIncrement(LabelNames.AGENT_REQUESTS_INFLIGHT, new String[]{label(traffic)}); + } + } + + @Override + public synchronized void finished(final Traffic traffic, final Outcome outcome, final Reason reason, final long millis) { + if (!active) { + return; + } + String[] labels = {label(traffic), label(outcome), label(reason)}; + try { + register.counterIncrement(LabelNames.AGENT_REQUESTS_TOTAL, labels, 1); + register.recordTime(LabelNames.AGENT_REQUEST_LATENCY, new String[]{label(traffic), label(outcome)}, millis); + } finally { + register.gaugeDecrement(LabelNames.AGENT_REQUESTS_INFLIGHT, new String[]{label(traffic)}); + } + } + + @Override + public synchronized void attempt(final AiAttemptEvent.Kind kind, final Outcome outcome, final long millis) { + if (!active) { + return; + } + String[] labels = {label(kind), label(outcome)}; + register.counterIncrement(LabelNames.AGENT_AI_ATTEMPTS_TOTAL, labels, 1); + register.recordTime(LabelNames.AGENT_AI_ATTEMPT_LATENCY, labels, millis); + } + + @Override + public synchronized void catalog(final boolean available) { + if (active) { + register.counterIncrement(LabelNames.AGENT_CATALOG_OBSERVATIONS_TOTAL, new String[]{available ? "available" : "unavailable"}, 1); + } + } + + synchronized void deactivate() { + active = false; + } + + @Override + public synchronized void authenticationRejected(final AuthenticationSource source, final AuthenticationReason reason) { + if (active) { + register.counterIncrement(LabelNames.AUTHENTICATION_REJECTIONS_TOTAL, new String[]{label(source), label(reason)}, 1); + } + } + + private static String label(final Enum value) { + return value.name().toLowerCase(Locale.ROOT); + } +} diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java index 5e4b035340fa..56cd02bab672 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java @@ -18,6 +18,7 @@ package org.apache.shenyu.plugin.metrics.reporter; import org.apache.shenyu.plugin.metrics.config.Metric; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.metrics.constant.LabelNames; import org.apache.shenyu.plugin.metrics.spi.MetricsRegister; @@ -32,12 +33,24 @@ public final class MetricsReporter { private static MetricsRegister metricsRegister; + private static volatile AgentRuntimeMetrics agentRuntimeMetrics = AgentRuntimeMetrics.NOOP; + + /** Capture the current optional registry without making the Agent plugin depend on Metrics. + * @return a bounded metrics callback tied to this registry lifetime + */ + public static AgentRuntimeMetrics agentRuntimeMetrics() { + return agentRuntimeMetrics; + } + /** * Register. * * @param metricsRegister metrics register */ - public static void register(final MetricsRegister metricsRegister) { + public static synchronized void register(final MetricsRegister metricsRegister) { + if (agentRuntimeMetrics instanceof AgentRuntimeMetricsReporter previous) { + previous.deactivate(); + } MetricsReporter.metricsRegister = metricsRegister; MetricsReporter.registerCounter(LabelNames.REQUEST_TOTAL, "shenyu request total count"); MetricsReporter.registerCounter(LabelNames.REQUEST_TYPE_TOTAL, new String[]{"type"}, "shenyu http request type total count"); @@ -51,6 +64,14 @@ public static void register(final MetricsRegister metricsRegister) { MetricsReporter.registerCounter(LabelNames.RESILIENCE4J_REQUEST_CIRCUITBREAKER_TOTAL, "shenyu resilience4j circuitbreaker request total count"); MetricsReporter.registerCounter(LabelNames.HYSTRIX_REQUEST_CIRCUITBREAKER_TOTAL, "shenyu hystrix circuitbreaker request total count"); MetricsReporter.registerCounter(LabelNames.RATELIMITER_REQUEST_RESTRICT_TOTAL, "shenyu ratelimiter request restrict total count"); + MetricsReporter.registerCounter(LabelNames.AGENT_REQUESTS_TOTAL, new String[]{"traffic", "outcome", "reason"}, "Terminal Agent request subscriptions including pre-dispatch rejection"); + MetricsReporter.registerHistogram(LabelNames.AGENT_REQUEST_LATENCY, new String[]{"traffic", "outcome"}, "Agent request terminal latency millis"); + MetricsReporter.registerGauge(LabelNames.AGENT_REQUESTS_INFLIGHT, new String[]{"traffic"}, "Active Agent logical request subscriptions, not sessions"); + MetricsReporter.registerCounter(LabelNames.AGENT_AI_ATTEMPTS_TOTAL, new String[]{"kind", "outcome"}, "Actually completed AI upstream attempts"); + MetricsReporter.registerHistogram(LabelNames.AGENT_AI_ATTEMPT_LATENCY, new String[]{"kind", "outcome"}, "AI upstream attempt latency millis"); + MetricsReporter.registerCounter(LabelNames.AGENT_CATALOG_OBSERVATIONS_TOTAL, new String[]{"state"}, "Remote catalog availability observed at request lease acquisition"); + MetricsReporter.registerCounter(LabelNames.AUTHENTICATION_REJECTIONS_TOTAL, new String[]{"source", "reason"}, "Authentication plugin rejections before Agent routing is known"); + agentRuntimeMetrics = new AgentRuntimeMetricsReporter(metricsRegister); } /** @@ -231,7 +252,11 @@ public static void recordTime(final String name, final long duration) { /** * Clean. */ - public static void clean() { + public static synchronized void clean() { + if (agentRuntimeMetrics instanceof AgentRuntimeMetricsReporter previous) { + previous.deactivate(); + } + agentRuntimeMetrics = AgentRuntimeMetrics.NOOP; Optional.ofNullable(metricsRegister).ifPresent(MetricsRegister::clean); metricsRegister = null; } diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/MetricsPluginTest.java b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/MetricsPluginTest.java index 5465b9a1a8b9..ec25b6fe868c 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/MetricsPluginTest.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/MetricsPluginTest.java @@ -22,6 +22,8 @@ import org.apache.shenyu.common.enums.PluginEnum; import org.apache.shenyu.common.enums.RpcTypeEnum; import org.apache.shenyu.common.metrics.AgentMcpCallObserver; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.apache.shenyu.common.metrics.AiAttemptEvent; import org.apache.shenyu.plugin.api.RemoteAddressResolver; import org.apache.shenyu.plugin.api.ShenyuPluginChain; import org.apache.shenyu.plugin.api.context.ShenyuContext; @@ -165,4 +167,57 @@ private ServerWebExchange createExchange(final String path, final ShenyuContext result.getAttributes().put(Constants.CONTEXT, shenyuContext); return result; } + + @Test + void governanceMetricsUseTheExistingPrometheusRegistryWithoutIdentityLabels() { + MetricsReporter.clean(); + CollectorRegistry.defaultRegistry.clear(); + MetricsReporter.register(new PrometheusMetricsRegister()); + try { + AgentRuntimeMetrics metrics = MetricsReporter.agentRuntimeMetrics(); + metrics.started(AgentRuntimeMetrics.Traffic.MCP); + metrics.started(AgentRuntimeMetrics.Traffic.MCP); + Assertions.assertEquals(2.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_REQUESTS_INFLIGHT, + new String[]{"traffic"}, new String[]{"mcp"})); + metrics.finished(AgentRuntimeMetrics.Traffic.MCP, AgentRuntimeMetrics.Outcome.REJECTED, AgentRuntimeMetrics.Reason.AUTHENTICATION, 7); + metrics.finished(AgentRuntimeMetrics.Traffic.MCP, AgentRuntimeMetrics.Outcome.CANCELLED, AgentRuntimeMetrics.Reason.NONE, 9); + Assertions.assertEquals(0.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_REQUESTS_INFLIGHT, + new String[]{"traffic"}, new String[]{"mcp"})); + Assertions.assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_REQUESTS_TOTAL, + new String[]{"traffic", "outcome", "reason"}, new String[]{"mcp", "rejected", "authentication"})); + Assertions.assertEquals(7.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_REQUEST_LATENCY + "_sum", + new String[]{"traffic", "outcome"}, new String[]{"mcp", "rejected"})); + metrics.attempt(AiAttemptEvent.Kind.RETRY, AgentRuntimeMetrics.Outcome.TIMEOUT, 5); + Assertions.assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_AI_ATTEMPTS_TOTAL, + new String[]{"kind", "outcome"}, new String[]{"retry", "timeout"})); + metrics.catalog(false); + metrics.catalog(true); + Assertions.assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_CATALOG_OBSERVATIONS_TOTAL, + new String[]{"state"}, new String[]{"unavailable"})); + Assertions.assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_CATALOG_OBSERVATIONS_TOTAL, + new String[]{"state"}, new String[]{"available"})); + } finally { + MetricsReporter.clean(); + CollectorRegistry.defaultRegistry.clear(); + } + } + + @Test + void outstandingRequestDoesNotDecrementAReplacementRegistry() { + MetricsRegister first = Mockito.mock(MetricsRegister.class); + MetricsRegister replacement = Mockito.mock(MetricsRegister.class); + try { + MetricsReporter.register(first); + AgentRuntimeMetrics active = MetricsReporter.agentRuntimeMetrics(); + active.started(AgentRuntimeMetrics.Traffic.LLM); + MetricsReporter.clean(); + Assertions.assertSame(AgentRuntimeMetrics.NOOP, MetricsReporter.agentRuntimeMetrics()); + MetricsReporter.register(replacement); + active.finished(AgentRuntimeMetrics.Traffic.LLM, AgentRuntimeMetrics.Outcome.CANCELLED, AgentRuntimeMetrics.Reason.NONE, 0); + Mockito.verify(first, Mockito.never()).gaugeDecrement(ArgumentMatchers.any(), ArgumentMatchers.any()); + Mockito.verify(replacement, Mockito.never()).gaugeDecrement(ArgumentMatchers.any(), ArgumentMatchers.any()); + } finally { + MetricsReporter.clean(); + } + } } diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentCatalogMetricsCollectorTest.java b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentCatalogMetricsCollectorTest.java new file mode 100644 index 000000000000..85f4ea7df4ed --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentCatalogMetricsCollectorTest.java @@ -0,0 +1,67 @@ +/* + * 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.plugin.metrics.prometheus; + +import io.prometheus.client.CollectorRegistry; +import org.apache.shenyu.common.metrics.AgentCatalogMetrics; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AgentCatalogMetricsCollectorTest { + + @Test + void scrapeTracksUpdatesAndIndependentRegistrationLifetimes() { + CollectorRegistry registry = new CollectorRegistry(); + new AgentCatalogMetricsCollector().register(registry); + AtomicReference state = new AtomicReference<>(new AgentCatalogMetrics.Snapshot(true, false, 1, 2, 3, 5, false)); + try (AgentCatalogMetrics first = AgentCatalogMetrics.register(state::get); + AgentCatalogMetrics second = AgentCatalogMetrics.register(() -> new AgentCatalogMetrics.Snapshot(false, true, 2, 4, 1, 7, true))) { + assertEquals(6.0, registry.getSampleValue("shenyu_agent_catalog_clients")); + assertEquals(4.0, registry.getSampleValue("shenyu_agent_catalog_leases")); + assertEquals(12.0, registry.getSampleValue("shenyu_agent_catalog_pending_requests")); + assertEquals(1.0, registry.getSampleValue("shenyu_agent_catalog_failed")); + assertEquals(1.0, registry.getSampleValue("shenyu_agent_catalog_instances", new String[]{"state"}, new String[]{"available"})); + state.set(new AgentCatalogMetrics.Snapshot(false, false, 0, 0, 0, 0, false)); + assertEquals(0.0, registry.getSampleValue("shenyu_agent_catalog_instances", new String[]{"state"}, new String[]{"available"})); + first.close(); + first.close(); + assertEquals(4.0, registry.getSampleValue("shenyu_agent_catalog_clients")); + registry.metricFamilySamples().asIterator().forEachRemaining(family -> family.samples.forEach(sample -> + assertTrue(sample.labelNames.isEmpty() || sample.labelNames.equals(List.of("state"))))); + } + assertEquals(0.0, registry.getSampleValue("shenyu_agent_catalog_clients")); + assertEquals(0.0, registry.getSampleValue("shenyu_agent_catalog_leases")); + } + + @Test + void brokenDiagnosticSupplierReportsUnavailableWithoutFailingScrape() { + CollectorRegistry registry = new CollectorRegistry(); + new AgentCatalogMetricsCollector().register(registry); + try (AgentCatalogMetrics ignored = AgentCatalogMetrics.register(() -> { + throw new IllegalStateException("private credential"); + })) { + assertEquals(1.0, registry.getSampleValue("shenyu_agent_catalog_instances", new String[]{"state"}, new String[]{"unavailable"})); + assertEquals(1.0, registry.getSampleValue("shenyu_agent_catalog_failed")); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java index 6b89c4d4f7df..f812c47acfe8 100644 --- a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java +++ b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java @@ -22,6 +22,7 @@ import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.dto.convert.rule.impl.KeyAuthRuleHandle; import org.apache.shenyu.common.enums.PluginEnum; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.api.ShenyuPluginChain; import org.apache.shenyu.plugin.api.result.ShenyuResultEnum; import org.apache.shenyu.plugin.api.result.ShenyuResultWrap; @@ -61,6 +62,7 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu .obtainHandle(CacheKeyUtils.INST.getKey(rule)); if (Objects.isNull(keyAuthRuleHandle) || StringUtils.isBlank(keyAuthRuleHandle.getKeyName()) || StringUtils.isBlank(keyAuthRuleHandle.getKey())) { + recordRejection(exchange, AgentRuntimeMetrics.AuthenticationReason.INVALID_CONFIGURATION); Object error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.KEY_NAME_AND_KEY_MUST_BE_CONFIGURED); return WebFluxResultUtils.result(exchange, error); } @@ -68,9 +70,17 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu return KeyAuthAuthentication.execute(exchange, chain, rule); } Object error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.ERROR_KEY); + recordRejection(exchange, AgentRuntimeMetrics.AuthenticationReason.CREDENTIAL_REJECTED); return WebFluxResultUtils.result(exchange, error); } + private void recordRejection(final ServerWebExchange exchange, final AgentRuntimeMetrics.AuthenticationReason reason) { + Object callback = exchange.getAttribute(AgentRuntimeMetrics.KEY); + if (callback instanceof AgentRuntimeMetrics metrics) { + AgentRuntimeMetrics.safely(() -> metrics.authenticationRejected(AgentRuntimeMetrics.AuthenticationSource.KEY_AUTH, reason)); + } + } + /** * Check the key. * @param exchange exchange diff --git a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthPluginTest.java b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthPluginTest.java index 934bdba4d8e6..e4a420a7f25c 100644 --- a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthPluginTest.java +++ b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/test/java/org/apache/shenyu/plugin/key/auth/KeyAuthPluginTest.java @@ -20,6 +20,7 @@ import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.enums.PluginEnum; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.api.ShenyuPluginChain; import org.apache.shenyu.plugin.api.result.DefaultShenyuResult; import org.apache.shenyu.plugin.api.result.ShenyuResult; @@ -83,6 +84,35 @@ public void testNotConfigured() { StepVerifier.create(mono).expectSubscription().verifyComplete(); } + @Test + public void rejectionIsObservedWithoutInferringAgentTrafficOrLeakingKey() { + ruleData.setHandle("{\"keyName\":\"apiKey\",\"key\":\"private-key\"}"); + keyAuthPluginDataHandler.handlerRule(ruleData); + exchange = MockServerWebExchange.from(MockServerHttpRequest.get("localhost").header("apiKey", "wrong").build()); + AgentRuntimeMetrics metrics = mock(AgentRuntimeMetrics.class); + exchange.getAttributes().put(AgentRuntimeMetrics.KEY, metrics); + StepVerifier.create(keyAuthPlugin.doExecute(exchange, chain, selectorData, ruleData)).verifyComplete(); + org.mockito.Mockito.verify(metrics).authenticationRejected(AgentRuntimeMetrics.AuthenticationSource.KEY_AUTH, + AgentRuntimeMetrics.AuthenticationReason.CREDENTIAL_REJECTED); + org.mockito.Mockito.verifyNoMoreInteractions(metrics); + org.mockito.Mockito.verify(chain, org.mockito.Mockito.never()).execute(any()); + } + + @Test + public void reportingFailureCannotTurnAuthenticationRejectionIntoAdmission() { + ruleData.setHandle("{}"); + keyAuthPluginDataHandler.handlerRule(ruleData); + exchange = MockServerWebExchange.from(MockServerHttpRequest.get("localhost").build()); + AgentRuntimeMetrics metrics = mock(AgentRuntimeMetrics.class); + org.mockito.Mockito.doThrow(new IllegalStateException("private")).when(metrics) + .authenticationRejected(any(), any()); + exchange.getAttributes().put(AgentRuntimeMetrics.KEY, metrics); + StepVerifier.create(keyAuthPlugin.doExecute(exchange, chain, selectorData, ruleData)).verifyComplete(); + org.mockito.Mockito.verify(metrics).authenticationRejected(AgentRuntimeMetrics.AuthenticationSource.KEY_AUTH, + AgentRuntimeMetrics.AuthenticationReason.INVALID_CONFIGURATION); + org.mockito.Mockito.verify(chain, org.mockito.Mockito.never()).execute(any()); + } + @Test public void testKeyAuthWithHeaderCredentials() { ruleData.setHandle("{\"keyName\":\"apiKey\",\"key\":\"key\"," diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml index 2ff2ec3cface..fa9b82a31c44 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml @@ -26,6 +26,18 @@ shenyu-spring-boot-starter-plugin-agent-gateway + + org.apache.shenyu + shenyu-spring-boot-starter-plugin-tracing + ${project.version} + test + + + org.apache.shenyu + shenyu-plugin-metrics + ${project.version} + test + org.apache.shenyu shenyu-plugin-ai-proxy diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java index 1320e186c514..877285b76f57 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java @@ -245,13 +245,23 @@ static class TracingConfiguration { /** * Use the explicitly supplied application telemetry, never a second SDK or global singleton. - * @param telemetry application-owned telemetry + * @param telemetry optional application-owned telemetry (takes precedence) + * @param gatewayTracer optional tracer owned by the ShenYu tracing starter * @return request-local tracing bridge */ @Bean @ConditionalOnMissingBean(AgentMcpCallTracer.class) - AgentMcpCallTracer agentGatewayCallTracer(final OpenTelemetry telemetry) { - return new OpenTelemetryAgentMcpCallTracer(telemetry); + AgentMcpCallTracer agentGatewayCallTracer(final ObjectProvider telemetry, + @org.springframework.beans.factory.annotation.Qualifier("tracingTracer") final ObjectProvider gatewayTracer) { + OpenTelemetry application = telemetry.getIfAvailable(); + if (java.util.Objects.nonNull(application)) { + return new OpenTelemetryAgentMcpCallTracer(application); + } + io.opentelemetry.api.trace.Tracer shared = gatewayTracer.getIfAvailable(); + if (java.util.Objects.isNull(shared)) { + throw new IllegalStateException("Enabled MCP tracing requires application OpenTelemetry, tracingTracer, or a custom AgentMcpCallTracer"); + } + return new OpenTelemetryAgentMcpCallTracer(shared); } } } diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracer.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracer.java index 19e14d8ce6cd..b789152864ad 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracer.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpCallTracer.java @@ -42,7 +42,11 @@ final class OpenTelemetryAgentMcpCallTracer implements AgentMcpCallTracer { private final Tracer tracer; OpenTelemetryAgentMcpCallTracer(final OpenTelemetry telemetry) { - tracer = telemetry.getTracer("org.apache.shenyu.agent.gateway"); + this(telemetry.getTracer("org.apache.shenyu.agent.gateway")); + } + + OpenTelemetryAgentMcpCallTracer(final Tracer tracer) { + this.tracer = java.util.Objects.requireNonNull(tracer, "tracer"); } @Override diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java index 0349c155e7b4..4d83e80d96fc 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java @@ -99,6 +99,31 @@ void enabledTracingRequiresApplicationTelemetry() { .run(context -> assertNotNull(context.getStartupFailure())); } + @Test + void tracingReusesOnlyTheExplicitlyNamedGatewayTracer() { + io.opentelemetry.api.trace.Tracer shared = OpenTelemetry.noop().getTracer("gateway"); + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.gateway.tracing.enabled=true") + .withBean("tracingTracer", io.opentelemetry.api.trace.Tracer.class, () -> shared) + .run(context -> { + assertEquals(shared, ReflectionTestUtils.getField(context.getBean(AgentMcpCallTracer.class), "tracer")); + assertTrue(context.getBeansOfType(OpenTelemetry.class).isEmpty()); + }); + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.gateway.tracing.enabled=true") + .withBean("unrelatedTracer", io.opentelemetry.api.trace.Tracer.class, () -> shared) + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void explicitApplicationTelemetryWinsOverGatewayTracer() { + OpenTelemetry telemetry = mock(OpenTelemetry.class); + io.opentelemetry.api.trace.Tracer application = mock(io.opentelemetry.api.trace.Tracer.class); + when(telemetry.getTracer("org.apache.shenyu.agent.gateway")).thenReturn(application); + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.gateway.tracing.enabled=true") + .withBean(OpenTelemetry.class, () -> telemetry) + .withBean("tracingTracer", io.opentelemetry.api.trace.Tracer.class, () -> OpenTelemetry.noop().getTracer("gateway")) + .run(context -> assertEquals(application, ReflectionTestUtils.getField(context.getBean(AgentMcpCallTracer.class), "tracer"))); + } + @Test void optionalTelemetryApiIsNotRequiredWhenDisabled() { contextRunner.withClassLoader(new FilteredClassLoader("io.opentelemetry")) diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java index 55bf6b12dc0f..5984b0370bce 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java @@ -35,6 +35,11 @@ import org.apache.shenyu.common.metrics.AiCallOutcome; import org.apache.shenyu.common.metrics.AiTerminalEvent; import org.apache.shenyu.common.metrics.AiUsage; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.apache.shenyu.plugin.metrics.reporter.MetricsReporter; +import org.apache.shenyu.plugin.metrics.prometheus.PrometheusMetricsRegister; +import org.apache.shenyu.plugin.metrics.constant.LabelNames; +import io.prometheus.client.CollectorRegistry; import org.apache.shenyu.plugin.agent.gateway.AgentGatewayPlugin; import org.apache.shenyu.plugin.agent.gateway.handler.AgentGatewayPluginDataHandler; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; @@ -106,6 +111,19 @@ */ class AgentGovernanceHttpTest { + @Test + void invalidKeyIsCountedBeforeAgentRoutingWithoutCreatingALogicalAiCall() { + try (Fixture fixture = new Fixture(false, false)) { + fixture.request("wrong").expectBody().consumeWith(ignored -> { }); + assertEquals(0, fixture.upstreamCalls.get()); + assertEquals(0, fixture.terminals.size()); + assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AUTHENTICATION_REJECTIONS_TOTAL, + new String[]{"source", "reason"}, new String[]{"key_auth", "credential_rejected"})); + assertNull(CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_REQUESTS_TOTAL, + new String[]{"traffic", "outcome", "reason"}, new String[]{"llm", "rejected", "authentication"})); + } + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void keyAuthToLimiterToProxyHasOneTerminalAndOneBodySubscription(final boolean stream) { @@ -135,6 +153,12 @@ void keyAuthToLimiterToProxyHasOneTerminalAndOneBodySubscription(final boolean s assertEquals("12345678901234567890123456789012", span.getTraceId()); assertEquals("1234567890123456", span.getParentSpanId()); assertEquals("00-" + span.getTraceId() + "-" + span.getSpanId() + "-01", fixture.outboundParent.get()); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals(0.0, CollectorRegistry.defaultRegistry.getSampleValue( + LabelNames.AGENT_REQUESTS_INFLIGHT, new String[]{"traffic"}, new String[]{"llm"}))); + assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_REQUESTS_TOTAL, + new String[]{"traffic", "outcome", "reason"}, new String[]{"llm", "success", "none"})); + assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_AI_ATTEMPTS_TOTAL, + new String[]{"kind", "outcome"}, new String[]{"primary", "success"})); } } @@ -148,6 +172,10 @@ void tokenDenialHasTrustedContextWithoutCallingModel() { assertEquals("tenant", event.context().getTenant()); assertEquals(0, event.attemptCount()); assertEquals(AiUsage.UNKNOWN, event.usage()); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue( + LabelNames.AGENT_REQUESTS_TOTAL, new String[]{"traffic", "outcome", "reason"}, new String[]{"llm", "rate_limited", "resource_limit"}))); + assertNull(CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_AI_ATTEMPTS_TOTAL, + new String[]{"kind", "outcome"}, new String[]{"primary", "success"})); assertEquals(1, fixture.bodySubscriptions.get()); assertEquals(0, fixture.upstreamCalls.get()); assertTrue(fixture.attempts.isEmpty()); @@ -273,8 +301,12 @@ public void recordAttempt(final AiAttemptEvent event) { TracingPlugin tracing = new TracingPlugin(telemetry.getTracer("governance-fixture")); handler = new ShenyuWebHandler(List.of(proxy, limiter, prompt, agent, key, tracing), mock(ShenyuLoaderService.class), config); handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.SORTED, BaseDataCache.getInstance().obtainPluginData(agent.named()))); + MetricsReporter.clean(); + CollectorRegistry.defaultRegistry.clear(); + MetricsReporter.register(new PrometheusMetricsRegister()); gateway = HttpServer.create().host("127.0.0.1").port(0).runOn(loops).handle(new ReactorHttpHandlerAdapter( WebHttpHandlerBuilder.webHandler(exchange -> { + exchange.getAttributes().put(AgentRuntimeMetrics.KEY, MetricsReporter.agentRuntimeMetrics()); org.springframework.http.server.reactive.ServerHttpRequestDecorator request = new org.springframework.http.server.reactive.ServerHttpRequestDecorator(exchange.getRequest()) { @Override public Flux getBody() { @@ -305,8 +337,12 @@ private RuleData register(final ShenyuPlugin plugin, final String handle) { } private WebTestClient.ResponseSpec request() { + return request("fixture-key"); + } + + private WebTestClient.ResponseSpec request(final String key) { return WebTestClient.bindToServer().baseUrl("http://127.0.0.1:" + gateway.port()).responseTimeout(Duration.ofSeconds(20)).build() - .post().uri("/chat").header("X-Api-Key", "fixture-key").header("X-Tenant-Id", "forged").header("X-Subject", "forged") + .post().uri("/chat").header("X-Api-Key", key).header("X-Tenant-Id", "forged").header("X-Subject", "forged") .header("traceparent", "00-12345678901234567890123456789012-1234567890123456-01").header("baggage", "private=never-forward") .header("Content-Type", "application/json").bodyValue("{\"messages\":[{\"role\":\"user\",\"content\":\"private\"}],\"stream\":" + stream + "}").exchange(); } @@ -317,6 +353,8 @@ public void close() { upstream.disposeNow(Duration.ofSeconds(10)); loops.disposeLater().block(Duration.ofSeconds(10)); telemetry.close(); + MetricsReporter.clean(); + CollectorRegistry.defaultRegistry.clear(); BaseDataCache cache = BaseDataCache.getInstance(); for (String name : List.of("keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy")) { cache.removeRuleDataBySelectorId("governance-" + name); diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpOtlpTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpOtlpTest.java index 0dfca132ccd2..3daec193c775 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpOtlpTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/OpenTelemetryAgentMcpOtlpTest.java @@ -25,6 +25,13 @@ import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import org.apache.shenyu.common.metrics.AgentMcpCallObserver.Outcome; +import org.apache.shenyu.common.config.ShenyuConfig; +import org.apache.shenyu.springboot.starter.plugin.tracing.TracingPluginConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.apache.shenyu.plugin.tracing.TracingPlugin; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import reactor.core.publisher.Mono; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpCallTracer; import org.junit.jupiter.api.Test; import reactor.util.context.Context; @@ -42,6 +49,49 @@ class OpenTelemetryAgentMcpOtlpTest { + @Test + void tracingStarterOwnsTheOnlyProviderAndExportsGatewayAndLogicalCallTogether() throws Exception { + java.util.concurrent.CopyOnWriteArrayList payloads = new java.util.concurrent.CopyOnWriteArrayList<>(); + HttpServer receiver = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + receiver.createContext("/v1/traces", exchange -> { + payloads.add(exchange.getRequestBody().readAllBytes()); + exchange.getResponseHeaders().set("Content-Type", "application/x-protobuf"); + exchange.sendResponseHeaders(200, -1); + exchange.close(); + }); + receiver.start(); + try { + ShenyuConfig config = new ShenyuConfig(); + config.getTracing().getOtlp().setEndpoint("http://127.0.0.1:" + receiver.getAddress().getPort()); + new ApplicationContextRunner().withUserConfiguration(TracingPluginConfiguration.class, AgentGatewayPluginConfiguration.class) + .withBean(ShenyuConfig.class, () -> config) + .withPropertyValues("shenyu.tracing.enabled=true", "shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.gateway.tracing.enabled=true") + .run(context -> { + assertTrue(java.util.Objects.isNull(context.getStartupFailure())); + assertEquals(1, context.getBeansOfType(SdkTracerProvider.class).size()); + assertTrue(context.getBeansOfType(OpenTelemetry.class).isEmpty()); + SdkTracerProvider provider = context.getBean(SdkTracerProvider.class); + AgentMcpCallTracer bridge = context.getBean(AgentMcpCallTracer.class); + TracingPlugin gateway = (TracingPlugin) context.getBean("tracingPlugin"); + gateway.execute(MockServerWebExchange.from(MockServerHttpRequest.post("/mcp").build()), exchange -> Mono.deferContextual(view -> { + AgentMcpCallTracer.Trace trace = bridge.start(view); + io.opentelemetry.context.Context serverContext = view.get(org.apache.shenyu.common.tracing.AgentTraceContext.GATEWAY_REACTOR_CONTEXT_KEY); + io.opentelemetry.context.Context logicalContext = trace.attach(Context.empty()).get(io.opentelemetry.context.Context.class); + assertEquals(io.opentelemetry.api.trace.Span.fromContext(serverContext).getSpanContext().getTraceId(), + io.opentelemetry.api.trace.Span.fromContext(logicalContext).getSpanContext().getTraceId()); + trace.finish(Outcome.SUCCESS); + trace.finish(Outcome.SUCCESS); + return Mono.empty(); + })).block(Duration.ofSeconds(10)); + assertTrue(provider.forceFlush().join(10, TimeUnit.SECONDS).isSuccess()); + assertEquals(1, payloads.size()); + assertTrue(new String(payloads.get(0), StandardCharsets.UTF_8).contains("shenyu.agent_gateway.tools.call")); + }); + } finally { + receiver.stop(0); + } + } + @Test void applicationOwnedSdkExportsOnceOverRealOtlpHttp() throws Exception { AtomicReference payload = new AtomicReference<>(); From 8aba05cac4208e3da3e69306ad73713042fe25ec Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Fri, 23 Oct 2026 09:08:33 +0800 Subject: [PATCH 04/36] feat(agent-gateway): add unified invocation auditing --- docs/agent-invocation-audit.md | 40 +++ .../impl/AiProxyApiKeyServiceImpl.java | 1 + .../impl/AiProxyApiKeyServiceImplTest.java | 2 + .../audit/AgentInvocationAuditBridge.java | 115 ++++++ .../audit/AgentInvocationAuditEvent.java | 328 ++++++++++++++++++ .../audit/AgentInvocationAuditObserver.java | 27 ++ .../common/dto/AgentRequestContext.java | 24 +- .../shenyu/common/dto/ProxyApiKeyData.java | 22 +- .../metrics/AgentMcpTerminalObserver.java | 7 + .../audit/AgentInvocationAuditBridgeTest.java | 101 ++++++ .../audit/AgentInvocationAuditEventTest.java | 64 ++++ .../agent/gateway/AgentGatewayPlugin.java | 21 +- .../gateway/protocol/AgentMcpDispatcher.java | 13 +- .../protocol/AgentMcpExecutionContext.java | 20 ++ .../gateway/protocol/AgentMcpHttpHandler.java | 6 +- .../protocol/AgentMcpTerminalObservation.java | 15 + .../agent/gateway/tool/AgentToolRegistry.java | 14 + .../agent/gateway/AgentGatewayPluginTest.java | 6 + .../AgentMcpTerminalObservationTest.java | 50 ++- .../ai/proxy/enhanced/AiProxyPlugin.java | 10 +- .../enhanced/cache/AiProxyApiKeyCache.java | 13 +- .../AiProxyEngineOrchestrationTest.java | 7 +- .../shenyu/plugin/key/auth/KeyAuthPlugin.java | 29 +- shenyu-spring-boot-starter/pom.xml | 1 + .../pom.xml | 33 ++ .../audit/AgentInvocationAuditCollector.java | 119 +++++++ .../AgentInvocationAuditConfiguration.java | 64 ++++ .../audit/AgentInvocationAuditConsumer.java | 46 +++ ...ot.autoconfigure.AutoConfiguration.imports | 16 + .../AgentInvocationAuditCollectorTest.java | 141 ++++++++ .../pom.xml | 5 + .../AgentGatewayPluginConfiguration.java | 10 +- .../AgentGatewayPluginConfigurationTest.java | 13 + .../gateway/AgentGovernanceHttpTest.java | 19 +- .../pom.xml | 5 + .../proxy/AiProxyPluginConfigurationTest.java | 11 + 36 files changed, 1392 insertions(+), 26 deletions(-) create mode 100644 docs/agent-invocation-audit.md create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridge.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditEvent.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditObserver.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditEventTest.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/pom.xml create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollector.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditConfiguration.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditConsumer.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/test/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollectorTest.java diff --git a/docs/agent-invocation-audit.md b/docs/agent-invocation-audit.md new file mode 100644 index 000000000000..af36502272b5 --- /dev/null +++ b/docs/agent-invocation-audit.md @@ -0,0 +1,40 @@ +# 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. + +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 + +This candidate integrates the request/terminal contracts from PR #7860 and runtime governance from PR #7921. It is not an independent publishable patch until those dependencies are merged and the audit delta is rebuilt on the resulting master. The earlier independent prototype's identity interface, completion logic and custom queue are not used. diff --git a/shenyu-admin/src/main/java/org/apache/shenyu/admin/service/impl/AiProxyApiKeyServiceImpl.java b/shenyu-admin/src/main/java/org/apache/shenyu/admin/service/impl/AiProxyApiKeyServiceImpl.java index d9636bf79dc3..cf7917336dea 100644 --- a/shenyu-admin/src/main/java/org/apache/shenyu/admin/service/impl/AiProxyApiKeyServiceImpl.java +++ b/shenyu-admin/src/main/java/org/apache/shenyu/admin/service/impl/AiProxyApiKeyServiceImpl.java @@ -343,6 +343,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()) diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/impl/AiProxyApiKeyServiceImplTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/impl/AiProxyApiKeyServiceImplTest.java index 11038dc81c96..25c6ee9e394a 100644 --- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/impl/AiProxyApiKeyServiceImplTest.java +++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/impl/AiProxyApiKeyServiceImplTest.java @@ -103,6 +103,8 @@ void testEnabledPublishesEvent() { ArgumentCaptor 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 diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridge.java b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridge.java new file mode 100644 index 000000000000..9d61d4819e1a --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridge.java @@ -0,0 +1,115 @@ +/* + * 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(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 void safely(final Runnable action) { + try { + action.run(); + } catch (RuntimeException ignored) { + // Sink failures must not alter traffic or suppress another observer. + } + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditEvent.java b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditEvent.java new file mode 100644 index 000000000000..639b32abd677 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditEvent.java @@ -0,0 +1,328 @@ +/* + * 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 java.time.Instant; +import java.util.Objects; +import java.util.Optional; + +/** + * Immutable, credential-free invocation audit metadata. Prompts, arguments and response bodies are intentionally absent. + */ +public final class AgentInvocationAuditEvent { + + /** + * Stable metadata contract version. Bump it only when fields or semantics change. + */ + public static final int SCHEMA_VERSION = 1; + + private final RecordType recordType; + + private final String requestId; + + private final String tenant; + + private final String subject; + + private final String apiKeyId; + + private final String selectorId; + + private final String ruleId; + + private final String configurationVersion; + + private final String policyVersion; + + private final Decision decision; + + private final String target; + + private final String outcome; + + private final String reason; + + private final Integer httpStatus; + + private final Integer attempt; + + private final long elapsedMillis; + + private final Instant timestamp; + + private AgentInvocationAuditEvent(final Builder builder) { + recordType = Objects.requireNonNull(builder.recordType, "recordType"); + requestId = text(builder.requestId, "requestId"); + tenant = nullableText(builder.tenant, "tenant"); + subject = nullableText(builder.subject, "subject"); + apiKeyId = nullableText(builder.apiKeyId, "apiKeyId"); + selectorId = nullableText(builder.selectorId, "selectorId"); + ruleId = nullableText(builder.ruleId, "ruleId"); + configurationVersion = text(builder.configurationVersion, "configurationVersion"); + policyVersion = text(builder.policyVersion, "policyVersion"); + decision = Objects.requireNonNull(builder.decision, "decision"); + target = nullableText(builder.target, "target"); + outcome = text(builder.outcome, "outcome"); + reason = text(builder.reason, "reason"); + httpStatus = Objects.isNull(builder.httpStatus) ? null : builder.httpStatus; + attempt = Objects.isNull(builder.attempt) ? null : builder.attempt; + if (Objects.nonNull(attempt) && attempt < 1) { + throw new IllegalArgumentException("attempt must be positive"); + } + elapsedMillis = builder.elapsedMillis; + if (elapsedMillis < 0) { + throw new IllegalArgumentException("elapsedMillis must not be negative"); + } + timestamp = Objects.requireNonNullElseGet(builder.timestamp, Instant::now); + } + + public static Builder logical() { + return new Builder(RecordType.LOGICAL); + } + + public static Builder attempt(final int attempt) { + return new Builder(RecordType.ATTEMPT).attempt(attempt); + } + + public RecordType getRecordType() { + return recordType; + } + + public String getRequestId() { + return requestId; + } + + public Optional getTenant() { + return Optional.ofNullable(tenant); + } + + public Optional getSubject() { + return Optional.ofNullable(subject); + } + + public Optional getApiKeyId() { + return Optional.ofNullable(apiKeyId); + } + + public int getSchemaVersion() { + return SCHEMA_VERSION; + } + + public Optional getSelectorId() { + return Optional.ofNullable(selectorId); + } + + public Optional getRuleId() { + return Optional.ofNullable(ruleId); + } + + public String getConfigurationVersion() { + return configurationVersion; + } + + public String getPolicyVersion() { + return policyVersion; + } + + public Decision getDecision() { + return decision; + } + + public Optional getTarget() { + return Optional.ofNullable(target); + } + + public String getOutcome() { + return outcome; + } + + public String getReason() { + return reason; + } + + public Optional getHttpStatus() { + return Optional.ofNullable(httpStatus); + } + + public Optional getAttempt() { + return Optional.ofNullable(attempt); + } + + public long getElapsedMillis() { + return elapsedMillis; + } + + public Instant getTimestamp() { + return timestamp; + } + + private static String text(final String value, final String name) { + String result = nullableText(value, name); + return Objects.requireNonNull(result, name); + } + + private static String nullableText(final String value, final String name) { + if (Objects.isNull(value)) { + return null; + } + if (value.isBlank() || value.length() > 256 || !value.equals(value.strip()) || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(name + " must be bounded nonblank text"); + } + return value; + } + + public enum RecordType { + LOGICAL, + ATTEMPT + } + + public enum Decision { + ALLOWED, + REJECTED + } + + public static final class Builder { + + private final RecordType recordType; + + private String requestId; + + private String tenant; + + private String subject; + + private String apiKeyId; + + private String selectorId; + + private String ruleId; + + private String configurationVersion = "unknown"; + + private String policyVersion = "unknown"; + + private Decision decision = Decision.ALLOWED; + + private String target; + + private String outcome; + + private String reason = "UNKNOWN"; + + private Integer httpStatus; + + private Integer attempt; + + private long elapsedMillis; + + private Instant timestamp; + + private Builder(final RecordType recordType) { + this.recordType = recordType; + } + + public Builder requestId(final String value) { + requestId = value; + return this; + } + + public Builder tenant(final String value) { + tenant = value; + return this; + } + + public Builder subject(final String value) { + subject = value; + return this; + } + + public Builder apiKeyId(final String value) { + apiKeyId = value; + return this; + } + + public Builder selectorId(final String value) { + selectorId = value; + return this; + } + + public Builder ruleId(final String value) { + ruleId = value; + return this; + } + + public Builder configurationVersion(final long value) { + configurationVersion = Long.toString(value); + return this; + } + + public Builder configurationVersion(final String value) { + configurationVersion = value; + return this; + } + + public Builder policyVersion(final String value) { + policyVersion = value; + return this; + } + + public Builder decision(final Decision value) { + decision = value; + return this; + } + + public Builder target(final String value) { + target = value; + return this; + } + + public Builder outcome(final String value) { + outcome = value; + return this; + } + + public Builder reason(final String value) { + reason = value; + return this; + } + + public Builder httpStatus(final Integer value) { + httpStatus = value; + return this; + } + + private Builder attempt(final Integer value) { + attempt = value; + return this; + } + + public Builder elapsedMillis(final long value) { + elapsedMillis = value; + return this; + } + + public Builder timestamp(final Instant value) { + timestamp = value; + return this; + } + + public AgentInvocationAuditEvent build() { + return new AgentInvocationAuditEvent(this); + } + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditObserver.java b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditObserver.java new file mode 100644 index 000000000000..aca63247b47d --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditObserver.java @@ -0,0 +1,27 @@ +/* + * 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; + +/** Nonblocking application-owned metadata sink. */ +@FunctionalInterface +public interface AgentInvocationAuditObserver { + + String EXCHANGE_ATTRIBUTE = AgentInvocationAuditObserver.class.getName(); + + void record(AgentInvocationAuditEvent event); +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentRequestContext.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentRequestContext.java index fbf3b8d85c0f..77600ca30031 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentRequestContext.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentRequestContext.java @@ -53,6 +53,8 @@ public final class AgentRequestContext { private final String sessionId; + private final String apiKeyId; + public AgentRequestContext(final String requestId, final String trafficType, final String selectorId, final String ruleId) { this(requestId, trafficType, selectorId, ruleId, null, null, null, null, null, null, null); } @@ -60,6 +62,12 @@ public AgentRequestContext(final String requestId, final String trafficType, fin public AgentRequestContext(final String requestId, final String trafficType, final String selectorId, final String ruleId, final Long configurationVersion, final String tenant, final String subject, final String target, final String operation, final String protocolVersion, final String sessionId) { + this(requestId, trafficType, selectorId, ruleId, configurationVersion, tenant, subject, target, operation, protocolVersion, sessionId, null); + } + + private AgentRequestContext(final String requestId, final String trafficType, final String selectorId, final String ruleId, + final Long configurationVersion, final String tenant, final String subject, final String target, + final String operation, final String protocolVersion, final String sessionId, final String apiKeyId) { this.requestId = Objects.requireNonNull(requestId, "requestId"); this.trafficType = Objects.requireNonNull(trafficType, "trafficType"); this.selectorId = selectorId; @@ -71,20 +79,30 @@ public AgentRequestContext(final String requestId, final String trafficType, fin this.operation = operation; this.protocolVersion = protocolVersion; this.sessionId = sessionId; + this.apiKeyId = apiKeyId; } public AgentRequestContext withIdentity(final String trustedTenant, final String trustedSubject) { return new AgentRequestContext(requestId, trafficType, selectorId, ruleId, configurationVersion, trustedTenant, trustedSubject, - target, operation, protocolVersion, sessionId); + target, operation, protocolVersion, sessionId, apiKeyId); } public AgentRequestContext withTarget(final String resolvedTarget, final String resolvedOperation, final String resolvedProtocolVersion) { return new AgentRequestContext(requestId, trafficType, selectorId, ruleId, configurationVersion, tenant, subject, - resolvedTarget, resolvedOperation, resolvedProtocolVersion, sessionId); + resolvedTarget, resolvedOperation, resolvedProtocolVersion, sessionId, apiKeyId); } public AgentRequestContext withConfigurationVersion(final long version) { - return new AgentRequestContext(requestId, trafficType, selectorId, ruleId, version, tenant, subject, target, operation, protocolVersion, sessionId); + return new AgentRequestContext(requestId, trafficType, selectorId, ruleId, version, tenant, subject, target, operation, protocolVersion, sessionId, apiKeyId); + } + + public AgentRequestContext withApiKeyId(final String internalId) { + return new AgentRequestContext(requestId, trafficType, selectorId, ruleId, configurationVersion, tenant, subject, + target, operation, protocolVersion, sessionId, internalId); + } + + public String getApiKeyId() { + return apiKeyId; } public String getRequestId() { diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/ProxyApiKeyData.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/ProxyApiKeyData.java index 041b3225300b..07ce887483c9 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/ProxyApiKeyData.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/ProxyApiKeyData.java @@ -22,6 +22,8 @@ /** ProxyApiKeyData for syncing proxy->real API key mappings to gateway. */ public class ProxyApiKeyData { + private String id; + private String realApiKey; private String proxyApiKey; @@ -41,6 +43,7 @@ public ProxyApiKeyData() { } private ProxyApiKeyData(final Builder builder) { + this.id = builder.id; this.realApiKey = builder.realApiKey; this.proxyApiKey = builder.proxyApiKey; this.description = builder.description; @@ -53,6 +56,14 @@ public static Builder builder() { return new Builder(); } + public String getId() { + return id; + } + + public void setId(final String id) { + this.id = id; + } + public String getRealApiKey() { return realApiKey; } @@ -110,7 +121,7 @@ public boolean equals(final Object o) { return false; } ProxyApiKeyData that = (ProxyApiKeyData) o; - return Objects.equals(realApiKey, that.realApiKey) + return Objects.equals(id, that.id) && Objects.equals(realApiKey, that.realApiKey) && Objects.equals(proxyApiKey, that.proxyApiKey) && Objects.equals(description, that.description) && Objects.equals(enabled, that.enabled) @@ -120,10 +131,12 @@ public boolean equals(final Object o) { @Override public int hashCode() { - return Objects.hash(realApiKey, proxyApiKey, description, enabled, namespaceId, selectorId); + return Objects.hash(id, realApiKey, proxyApiKey, description, enabled, namespaceId, selectorId); } public static final class Builder { + private String id; + private String realApiKey; private String proxyApiKey; @@ -139,6 +152,11 @@ public static final class Builder { private Builder() { } + public Builder id(final String id) { + this.id = id; + return this; + } + public Builder realApiKey(final String realApiKey) { this.realApiKey = realApiKey; return this; diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalObserver.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalObserver.java index 80cafe67cd9e..439dcc2e775c 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalObserver.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentMcpTerminalObserver.java @@ -31,4 +31,11 @@ public interface AgentMcpTerminalObserver { * @param event immutable, body-free per-subscription snapshot */ void record(AgentMcpTerminalEvent event); + + /** + * Record an actual tool execution separately from the logical completion. + * @param event trusted terminal snapshot + */ + default void recordAttempt(final AgentMcpTerminalEvent event) { + } } diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java new file mode 100644 index 000000000000..87d1a9d83eec --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java @@ -0,0 +1,101 @@ +/* + * 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.AiAttemptEvent; +import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.common.metrics.AiCallOutcome; +import org.apache.shenyu.common.metrics.AiRequestObservation; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; +import reactor.core.scheduler.Schedulers; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AgentInvocationAuditBridgeTest { + + @Test + void reusesTerminalIdempotenceAndKeepsAttemptIdentity() { + List records = new CopyOnWriteArrayList<>(); + AiRequestObservation observation = new AiRequestObservation(AgentInvocationAuditBridge.ai(null, records::add), context("one")); + AiRequestObservation.Attempt primary = observation.startAttempt(observation.getContext().withTarget("primary", "chat", null), + AiAttemptEvent.Kind.PRIMARY, "openai", "chat", false); + primary.status(503); + primary.finish(SignalType.ON_ERROR, AiCallOutcome.ERROR); + primary.finish(SignalType.ON_ERROR, AiCallOutcome.ERROR); + AiRequestObservation.Attempt fallback = observation.startAttempt(observation.getContext().withTarget("fallback", "chat", null), + AiAttemptEvent.Kind.FALLBACK, "openai", "chat", false); + fallback.status(200); + fallback.finish(SignalType.ON_COMPLETE, null); + observation.finish(SignalType.ON_COMPLETE, 200); + observation.finish(SignalType.CANCEL, null); + assertEquals(3, records.size()); + assertEquals(List.of(1, 2), records.stream().filter(event -> event.getAttempt().isPresent()).map(event -> event.getAttempt().orElseThrow()).toList()); + assertEquals(1, records.stream().filter(event -> event.getRecordType() == AgentInvocationAuditEvent.RecordType.LOGICAL).count()); + assertTrue(records.stream().allMatch(event -> event.getApiKeyId().orElseThrow().equals("key-id-one"))); + assertEquals("fallback", records.get(2).getTarget().orElseThrow()); + } + + @Test + void independentReactorSubscriptionsDoNotShareIdentity() { + List records = new CopyOnWriteArrayList<>(); + AiCallObserver bridge = AgentInvocationAuditBridge.ai(null, records::add); + List completed = Flux.range(0, 64).flatMap(index -> Mono.deferContextual(view -> { + AiRequestObservation observation = new AiRequestObservation(bridge, view.get(AgentRequestContext.REACTOR_KEY)); + observation.finish(SignalType.ON_COMPLETE, index % 2 == 0 ? 200 : 429); + return Mono.just(index); + }).subscribeOn(Schedulers.parallel()).contextWrite(view -> view.put(AgentRequestContext.REACTOR_KEY, context(Integer.toString(index))))) + .collectList().block(java.time.Duration.ofSeconds(10)); + assertEquals(64, completed.size()); + assertEquals(64, records.size()); + for (AgentInvocationAuditEvent event : records) { + assertEquals("tenant-" + event.getRequestId(), event.getTenant().orElseThrow()); + assertEquals("subject-" + event.getRequestId(), event.getSubject().orElseThrow()); + assertEquals("key-id-" + event.getRequestId(), event.getApiKeyId().orElseThrow()); + if (event.getHttpStatus().orElseThrow() == 429) { + assertEquals(AgentInvocationAuditEvent.Decision.REJECTED, event.getDecision()); + } + } + } + + @Test + void auditFailureDoesNotSuppressExistingObserverAndDisabledPathIsUnchanged() { + AtomicInteger delivered = new AtomicInteger(); + AiCallObserver existing = event -> delivered.incrementAndGet(); + assertSame(existing, AgentInvocationAuditBridge.ai(existing, null)); + AiRequestObservation observation = new AiRequestObservation(AgentInvocationAuditBridge.ai(existing, event -> { + throw new IllegalStateException("private backend data"); + }), context("one")); + observation.finish(SignalType.ON_COMPLETE, 200); + assertEquals(1, delivered.get()); + } + + private AgentRequestContext context(final String id) { + return new AgentRequestContext(id, "llm", "selector", "rule").withIdentity("tenant-" + id, "subject-" + id) + .withApiKeyId("key-id-" + id).withConfigurationVersion(7); + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditEventTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditEventTest.java new file mode 100644 index 000000000000..dc029d7f7180 --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditEventTest.java @@ -0,0 +1,64 @@ +/* + * 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.junit.jupiter.api.Test; + +import java.time.Instant; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class AgentInvocationAuditEventTest { + + @Test + void buildsVersionedLogicalRecordWithoutCredentialCarryingFields() { + AgentInvocationAuditEvent event = AgentInvocationAuditEvent.logical() + .requestId("request-1") + .tenant("tenant-1") + .subject("subject-1") + .apiKeyId("internal-key-id") + .selectorId("selector-1") + .ruleId("rule-1") + .configurationVersion("configuration-1") + .policyVersion("policy-1") + .target("tool-1") + .outcome("SUCCESS") + .reason("COMPLETED") + .httpStatus(200) + .elapsedMillis(1) + .timestamp(Instant.EPOCH) + .build(); + + assertEquals(AgentInvocationAuditEvent.SCHEMA_VERSION, event.getSchemaVersion()); + assertEquals(AgentInvocationAuditEvent.RecordType.LOGICAL, event.getRecordType()); + assertEquals(AgentInvocationAuditEvent.Decision.ALLOWED, event.getDecision()); + assertEquals("internal-key-id", event.getApiKeyId().orElseThrow()); + assertEquals(Instant.EPOCH, event.getTimestamp()); + } + + @Test + void rejectsUnboundedOrMalformedAuditTextAndInvalidAttempts() { + assertThrows(IllegalArgumentException.class, () -> AgentInvocationAuditEvent.logical() + .requestId(" request ").outcome("SUCCESS").build()); + assertThrows(IllegalArgumentException.class, () -> AgentInvocationAuditEvent.logical() + .requestId("x".repeat(257)).outcome("SUCCESS").build()); + assertThrows(IllegalArgumentException.class, () -> AgentInvocationAuditEvent.attempt(0) + .requestId("request").outcome("FAILED").build()); + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java index 790f6572ca31..dc65e11edd4c 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java @@ -86,7 +86,7 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu return Mono.defer(() -> { final AgentGatewayRuleHandle handle = resolveHandle(rule); if (!handle.isValid()) { - return reject(exchange, handle.getErrorMessage()); + return reject(exchange, handle.getErrorMessage(), selector, rule); } final AgentTrafficContext context = new AgentTrafficContext( UUID.randomUUID().toString(), handle.getTrafficType(), selector.getId(), rule.getId()); @@ -165,11 +165,26 @@ private void registerResponseRequestId(final ServerWebExchange exchange, final S }); } - private Mono reject(final ServerWebExchange exchange, final String reason) { + private Mono reject(final ServerWebExchange exchange, final String reason, final SelectorData selector, final RuleData rule) { exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); final Object error = ShenyuResultWrap.error(exchange, HttpStatus.INTERNAL_SERVER_ERROR.value(), AgentGatewayConstants.CONFIG_INVALID_CODE + ": " + reason, null); - return WebFluxResultUtils.result(exchange, error); + long started = System.nanoTime(); + String requestId = UUID.randomUUID().toString(); + return WebFluxResultUtils.result(exchange, error).doFinally(signal -> { + Object callback = exchange.getAttribute(org.apache.shenyu.common.audit.AgentInvocationAuditObserver.EXCHANGE_ATTRIBUTE); + if (callback instanceof org.apache.shenyu.common.audit.AgentInvocationAuditObserver audit) { + try { + audit.record(org.apache.shenyu.common.audit.AgentInvocationAuditEvent.logical().requestId(requestId) + .selectorId(selector.getId()).ruleId(rule.getId()).configurationVersion("unknown").policyVersion("agent-rule-admission-v1") + .decision(org.apache.shenyu.common.audit.AgentInvocationAuditEvent.Decision.REJECTED) + .outcome(signal == reactor.core.publisher.SignalType.CANCEL ? "CANCELLED" : "SERVER_ERROR").reason("INVALID_CONFIGURATION") + .httpStatus(500).elapsedMillis(java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(Math.max(0, System.nanoTime() - started))).build()); + } catch (RuntimeException ignored) { + // Do not expose the rejected configuration or alter its response. + } + } + }); } @Override diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java index 8c22aa4c5378..04c68209e342 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import org.apache.shenyu.common.dto.AgentGatewayHttpToolConfig; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolArgumentException; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolCapabilityException; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolDefinition; @@ -87,7 +88,7 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier (AgentToolProvider) new AgentHttpToolProvider(tool, context.getHttpInvoker())).toList()); AgentMcpExecutionContext bound = new AgentMcpExecutionContext(context.getRequestId(), context.getSubject(), context.getRuleId(), context.getConfigurationVersion(), context.getRuleTools(), context.getAllowedTools(), context.getDeadline(), context.getResultFilters(), - context.getTenant().orElse(null)); + AgentGatewayHttpToolConfig.empty(), null, context.getTenant().orElse(null), context::notifyAttempt); return new AgentMcpDispatcher(captured, serverName, serverVersion, remoteCatalog).dispatch(request, () -> bound); } if (Objects.nonNull(remoteCatalog)) { @@ -165,7 +166,10 @@ private Mono routeWithRemote(final AgentMcpRequest request, final Ag final AgentMcpResultFilter filter = prepareResultFilter(request, context, name, definitions.get(name).get("outputSchema")); ObjectNode params = request.getParams(); JsonObject arguments = params.has("arguments") ? JsonParser.parseString(params.get("arguments").toString()).getAsJsonObject() : new JsonObject(); - return snapshot.invoke(name, arguments, context) + return Mono.defer(() -> { + context.notifyAttempt(); + return snapshot.invoke(name, arguments, context); + }) .switchIfEmpty(Mono.error(new IllegalStateException("Remote tool completed without a result"))) .map(value -> { ObjectNode result = value.deepCopy(); @@ -219,8 +223,9 @@ private Mono call(final AgentMcpRequest request, final AgentMcpExecu final AgentMcpResultFilter filter = prepareResultFilter(request, context, name, null); JsonObject arguments = params.has("arguments") ? JsonParser.parseString(params.get("arguments").toString()).getAsJsonObject() : new JsonObject(); JsonObject capabilities = request.getClientCapabilities(); - return registry.invoke(name, context.getAllowedTools(), () -> new AgentToolInvocation(context.getRequestId(), context.getSubject(), arguments, - context.getRuleId(), context.getConfigurationVersion(), context.getDeadline(), capabilities)) + return registry.invoke(name, context.getAllowedTools(), + () -> new AgentToolInvocation(context.getRequestId(), context.getSubject(), arguments, + context.getRuleId(), context.getConfigurationVersion(), context.getDeadline(), capabilities), context::notifyAttempt) .map(value -> { // Active field policies must not introduce an opaque metadata channel. ObjectNode result = filter.isActive() ? mapper.createObjectNode().put("resultType", "complete") : complete(); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java index a189dcf22d7c..515604130a3b 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java @@ -26,6 +26,7 @@ import java.util.Optional; import java.util.Set; import java.time.Instant; +import java.util.concurrent.atomic.AtomicBoolean; /** * Immutable authorization input supplied exclusively by a trusted server-side adapter. @@ -55,6 +56,10 @@ public final class AgentMcpExecutionContext { private final AgentHttpToolInvoker httpInvoker; + private final Runnable attemptListener; + + private final AtomicBoolean attemptRecorded = new AtomicBoolean(); + public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion, final Set ruleTools, final Set securityGrants) { this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, Instant.MAX); @@ -90,10 +95,19 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi final Set ruleTools, final Set securityGrants, final Instant deadline, final AgentGatewayResultFilterConfig resultFilters, final AgentGatewayHttpToolConfig httpTools, final AgentHttpToolInvoker httpInvoker, final String tenant) { + this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters, + httpTools, httpInvoker, tenant, null); + } + + AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion, + final Set ruleTools, final Set securityGrants, final Instant deadline, + final AgentGatewayResultFilterConfig resultFilters, final AgentGatewayHttpToolConfig httpTools, + final AgentHttpToolInvoker httpInvoker, final String tenant, final Runnable attemptListener) { this.tenant = Objects.isNull(tenant) ? null : requireText(tenant, "tenant"); this.deadline = Objects.requireNonNull(deadline, "deadline"); this.httpTools = Objects.requireNonNull(httpTools, "httpTools"); this.httpInvoker = httpInvoker; + this.attemptListener = attemptListener; this.resultFilters = Objects.requireNonNull(resultFilters, "resultFilters"); this.requestId = requireText(requestId, "requestId"); this.subject = requireText(subject, "subject"); @@ -152,6 +166,12 @@ public AgentHttpToolInvoker getHttpInvoker() { return httpInvoker; } + void notifyAttempt() { + if (Objects.nonNull(attemptListener) && attemptRecorded.compareAndSet(false, true)) { + attemptListener.run(); + } + } + private String requireText(final String value, final String name) { if (Objects.requireNonNull(value, name).isBlank()) { throw new IllegalArgumentException(name + " must not be blank"); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java index 2be4ccf8f56a..595542dec17c 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java @@ -140,7 +140,11 @@ public Mono handle(final ServerWebExchange exchange, final AgentGatewayMcp return dispatcher.dispatch(request, () -> new AgentMcpExecutionContext(traffic.getRequestId(), identity.getSubject(), traffic.getRuleId(), configurationVersion, config.getAllowedTools(), identity.getToolGrants(), deadline, config.getResultFilters(), config.getHttpTools(), httpInvoker, - identity.getTenant().orElse(null))) + identity.getTenant().orElse(null), () -> { + if (Objects.nonNull(terminal)) { + terminal.attempted(); + } + })) .contextWrite(observation::traceContext) .contextWrite(context -> context.put(AgentRuntimeMetrics.KEY, metrics)) .contextWrite(context -> context.put(AgentRequestContext.REACTOR_KEY, diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java index 3b5a46634974..a1e2cc71b050 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java @@ -64,6 +64,8 @@ final class AgentMcpTerminalObservation { private boolean completed; + private boolean attempted; + AgentMcpTerminalObservation(final AgentMcpTerminalObserver observer, final AgentTrafficContext traffic, final long configurationVersion) { this(observer, traffic, configurationVersion, AgentRuntimeMetrics.NOOP); } @@ -77,6 +79,12 @@ final class AgentMcpTerminalObservation { AgentRuntimeMetrics.safely(() -> metrics.started(AgentRuntimeMetrics.Traffic.MCP)); } + synchronized void attempted() { + if (!completed) { + attempted = true; + } + } + synchronized void identified(final String value) { if (!completed) { subject = value; @@ -148,6 +156,13 @@ void finish(final SignalType signal, final Integer status) { reason, event.getElapsedMillis())); try { if (Objects.nonNull(observer)) { + if (attempted) { + try { + observer.recordAttempt(event); + } catch (RuntimeException error) { + LOG.debug("MCP attempt event callback failed"); + } + } observer.record(event); } } catch (RuntimeException error) { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java index 61acff527f0d..4a1efa63388b 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java @@ -137,6 +137,19 @@ public static void validateDefinition(final String name, final String descriptio */ public Mono invoke(final String name, final Set allowedTools, final Supplier input) { + return invoke(name, allowedTools, input, () -> { }); + } + + /** + * Invoke a tool, notifying the request observer only after pre-execution validation. + * @param name tool name + * @param allowedTools effective permissions + * @param input request-local invocation factory + * @param onAttempt nonblocking callback before provider execution + * @return request-local result + */ + public Mono invoke(final String name, final Set allowedTools, + final Supplier input, final Runnable onAttempt) { Set permissions = Set.copyOf(allowedTools); Objects.requireNonNull(input, "input"); return Mono.defer(() -> { @@ -154,6 +167,7 @@ public Mono invoke(final String name, final Set allowedTools } catch (IllegalArgumentException error) { throw new AgentToolArgumentException(error); } + onAttempt.run(); return provider.invoke(invocation) .switchIfEmpty(Mono.error(new IllegalStateException("Tool completed without a result"))) .map(JsonObject::deepCopy); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPluginTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPluginTest.java index 3298cb51e67e..7da3a5faf016 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPluginTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPluginTest.java @@ -288,6 +288,9 @@ void shouldUseCurrentRuleWhenCachedSnapshotIsStale() { @Test void shouldRejectInvalidHandleBeforeCallingDownstream() { ServerWebExchange exchange = newExchange(); + java.util.List audits = new java.util.concurrent.CopyOnWriteArrayList<>(); + exchange.getAttributes().put(org.apache.shenyu.common.audit.AgentInvocationAuditObserver.EXCHANGE_ATTRIBUTE, + (org.apache.shenyu.common.audit.AgentInvocationAuditObserver) audits::add); AtomicReference calls = new AtomicReference<>(0); RuleData invalidRule = RuleData.builder() .id("rule-1") @@ -301,6 +304,9 @@ void shouldRejectInvalidHandleBeforeCallingDownstream() { }, selector(), invalidRule)).verifyComplete(); assertEquals(0, calls.get()); + assertEquals(1, audits.size()); + assertEquals("INVALID_CONFIGURATION", audits.get(0).getReason()); + assertTrue(audits.get(0).getSubject().isEmpty()); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, exchange.getResponse().getStatusCode()); assertNotNull(AgentGatewayPluginDataHandler.CACHED_HANDLE.get().obtainHandle("selector-1_rule-1")); assertTrue(!AgentGatewayPluginDataHandler.CACHED_HANDLE.get() diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java index 1cb6a67a26e3..49bcc2a10997 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java @@ -19,6 +19,8 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import org.apache.shenyu.common.audit.AgentInvocationAuditBridge; +import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; import org.apache.shenyu.common.constant.Constants; import org.apache.shenyu.common.dto.AgentGatewayMcpConfig; import org.apache.shenyu.common.dto.AgentRequestContext; @@ -81,6 +83,24 @@ class AgentMcpTerminalObservationTest { private final AgentTrafficContext traffic = new AgentTrafficContext("gateway-id", "mcp", "selector", "rule"); + @Test + void auditUsesActualAttemptAndTerminalOwner() { + List events = new java.util.concurrent.CopyOnWriteArrayList<>(); + AgentMcpTerminalObserver observer = AgentInvocationAuditBridge.mcp(null, events::add); + StepVerifier.create(handler(Mono.just(new JsonObject()), ignored -> Mono.just(new AgentMcpIdentity("tenant", "subject", Set.of("read"), Set.of())), observer) + .handle(exchange("tools/call"), config("json", 30000), traffic, 7)).verifyComplete(); + assertEquals(2, events.size()); + assertEquals(AgentInvocationAuditEvent.RecordType.ATTEMPT, events.get(0).getRecordType()); + assertEquals(AgentInvocationAuditEvent.RecordType.LOGICAL, events.get(1).getRecordType()); + assertEquals("tenant", events.get(1).getTenant().orElseThrow()); + events.clear(); + StepVerifier.create(handler(Mono.just(new JsonObject()), ignored -> Mono.empty(), observer) + .handle(exchange("tools/call"), config("json", 30000), traffic, 7)).verifyComplete(); + assertEquals(1, events.size()); + assertEquals("REJECTED", events.get(0).getOutcome()); + assertTrue(events.get(0).getSubject().isEmpty()); + } + @Test void runtimeMetricsWorkWithoutAnApplicationObserverBeforeParsing() { AgentRuntimeMetrics metrics = mock(AgentRuntimeMetrics.class); @@ -94,6 +114,25 @@ void runtimeMetricsWorkWithoutAnApplicationObserverBeforeParsing() { org.mockito.ArgumentMatchers.eq(AgentRuntimeMetrics.Reason.AUTHENTICATION), org.mockito.ArgumentMatchers.anyLong()); } + @ParameterizedTest + @CsvSource({"success,SUCCESS,2", "tool-error,TOOL_ERROR,2", "timeout,TIMEOUT,2", "rejected,REJECTED,1"}) + void realHttpAuditPreservesResponseAndCorrelatesExecution(final String scenario, final String outcome, final int count) throws Exception { + List audits = new java.util.concurrent.CopyOnWriteArrayList<>(); + Mono action = "timeout".equals(scenario) ? Mono.never() + : "tool-error".equals(scenario) ? Mono.error(new AgentToolExecutionException("secret")) + : Mono.just(new JsonObject()); + AgentMcpSecurityResolver resolver = "rejected".equals(scenario) ? ignored -> Mono.empty() : identity(); + try (TerminalHttpFixture fixture = new TerminalHttpFixture( + handler(action, resolver, AgentInvocationAuditBridge.mcp(null, audits::add)), config("json", 500), traffic, 7)) { + HttpResponse response = send(fixture); + assertEquals("timeout".equals(scenario) ? 504 : "rejected".equals(scenario) ? 401 : 200, response.statusCode()); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals(count, audits.size())); + assertTrue(audits.stream().allMatch(event -> outcome.equals(event.getOutcome()) && "gateway-id".equals(event.getRequestId()))); + assertEquals(1, audits.stream().filter(event -> event.getRecordType() == AgentInvocationAuditEvent.RecordType.LOGICAL).count()); + assertFalse(response.body().contains("secret")); + } + } + @Test void runtimeMetricsFinishOnceOnCancellationEvenIfApplicationObserverThrows() { AgentRuntimeMetrics metrics = mock(AgentRuntimeMetrics.class); @@ -467,7 +506,8 @@ void lateSignalsCannotAlterOrRepeatAnEvent() { } private AgentMcpHttpHandler handler(final Mono action, final AgentMcpSecurityResolver resolver, final AgentMcpTerminalObserver observer) { - return new AgentMcpHttpHandler(dispatcher(action), resolver, null, observer); + return new AgentMcpHttpHandler(dispatcher(action), resolver, null, + observer instanceof Recording recording ? AgentInvocationAuditBridge.mcp(observer, recording.audits::add) : observer); } private AgentMcpDispatcher dispatcher(final Mono action) { @@ -547,6 +587,8 @@ private static final class Recording implements AgentMcpTerminalObserver { private final ConcurrentLinkedQueue events = new ConcurrentLinkedQueue<>(); + private final ConcurrentLinkedQueue audits = new ConcurrentLinkedQueue<>(); + @Override public void record(final AgentMcpTerminalEvent event) { events.add(event); @@ -557,6 +599,12 @@ private AgentMcpTerminalEvent only(final Outcome outcome) { assertEquals(1, events.size()); AgentMcpTerminalEvent event = events.element(); assertEquals(outcome, event.getOutcome()); + if (!audits.isEmpty()) { + List logical = audits.stream().filter(audit -> audit.getRecordType() == AgentInvocationAuditEvent.RecordType.LOGICAL).toList(); + assertEquals(1, logical.size()); + assertEquals(event.getOutcome().name(), logical.get(0).getOutcome()); + assertEquals(event.getRequestId(), logical.get(0).getRequestId()); + } return event; } } diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java index 47b87efc2b5c..213e2b4af2a0 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java @@ -98,7 +98,7 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu AiRequestObservation observation = Objects.nonNull(inherited) ? inherited : new AiRequestObservation(observer, AiObservationSupport.context(view, selector.getId(), rule.getId()), callback instanceof AgentRuntimeMetrics metrics ? metrics : AgentRuntimeMetrics.NOOP); - return executeRequest(exchange, selector) + return executeRequest(exchange, selector, observation) .doOnError(error -> observation.failure(AiObservationSupport.outcome(error))) .onErrorResume(error -> handleFailure(exchange.getResponse(), error)) .doOnError(observation::error) @@ -112,7 +112,7 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu }); } - private Mono executeRequest(final ServerWebExchange exchange, final SelectorData selector) { + private Mono executeRequest(final ServerWebExchange exchange, final SelectorData selector, final AiRequestObservation observation) { return Mono.defer(() -> { AiProxyHandle handle = aiProxyPluginHandler.getSelectorCachedHandle() .obtainHandle(CacheKeyUtils.INST.getKey(selector.getId(), Constants.DEFAULT_RULE)); @@ -128,13 +128,15 @@ private Mono executeRequest(final ServerWebExchange exchange, final Select AiCommonConfig config = aiProxyConfigService.resolvePrimaryConfig(handle); if (Objects.nonNull(handle) && "true".equalsIgnoreCase(handle.getProxyEnabled())) { String proxyKey = exchange.getRequest().getHeaders().getFirst(Constants.X_API_KEY); - String realKey = Objects.isNull(proxyKey) || proxyKey.isEmpty() ? null - : AiProxyApiKeyCache.getInstance().getRealApiKey(selector.getId(), proxyKey); + org.apache.shenyu.common.dto.ProxyApiKeyData mapping = Objects.isNull(proxyKey) || proxyKey.isEmpty() ? null + : AiProxyApiKeyCache.getInstance().getValidatedMapping(selector.getId(), proxyKey); + String realKey = Objects.isNull(mapping) ? null : mapping.getRealApiKey(); if (Objects.isNull(realKey)) { exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); return exchange.getResponse().setComplete(); } config.setApiKey(realKey); + observation.updateContext(observation.getContext().withApiKeyId(mapping.getId())); } Optional fallback = aiProxyConfigService.resolveDynamicFallbackConfig(config, body) .or(() -> aiProxyConfigService.resolveAdminFallbackConfig(config, handle)); diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/cache/AiProxyApiKeyCache.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/cache/AiProxyApiKeyCache.java index b82bd12a7114..6c798716e96b 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/cache/AiProxyApiKeyCache.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/cache/AiProxyApiKeyCache.java @@ -92,12 +92,23 @@ public void remove(final ProxyApiKeyData data) { * @return real key or null if missing/disabled */ public String getRealApiKey(final String selectorId, final String proxyApiKey) { - final ProxyApiKeyData data = dataMap.get(key(selectorId, proxyApiKey)); + final ProxyApiKeyData data = getValidatedMapping(selectorId, proxyApiKey); return (Objects.nonNull(data) && Boolean.TRUE.equals(data.getEnabled())) ? data.getRealApiKey() : null; } + /** + * Capture an enabled mapping so admission and audit use the same synchronized identity. + * @param selectorId matched selector + * @param proxyApiKey presented credential + * @return enabled mapping, or null + */ + public ProxyApiKeyData getValidatedMapping(final String selectorId, final String proxyApiKey) { + ProxyApiKeyData data = dataMap.get(key(selectorId, proxyApiKey)); + return Objects.nonNull(data) && Boolean.TRUE.equals(data.getEnabled()) ? data : null; + } + /** Clear cache. */ public void refresh() { dataMap.clear(); diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java index 86314b67b1c6..2282ce200dcf 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java @@ -485,15 +485,18 @@ public AiUpstreamResponse encodeResponse(final AiUpstreamResponse response, fina void cancellationDuringFallbackReachesOnlyTheActiveBody() { AtomicInteger calls = new AtomicInteger(); AtomicBoolean cancelled = new AtomicBoolean(); + AtomicBoolean bodySubscribed = new AtomicBoolean(); AiProxyEngine engine = engine(request -> { if (calls.incrementAndGet() <= 2) { return Mono.error(networkFailure()); } return Mono.just(response(200, Flux.just(bytes("data: {\"fallback\":true}\n\n")) - .concatWith(Flux.never()).doOnCancel(() -> cancelled.set(true)))); + .concatWith(Flux.never()).doOnSubscribe(subscription -> bodySubscribed.set(true)) + .doOnCancel(() -> cancelled.set(true)))); }); StepVerifier.create(engine.execute(BODY, config(true, "main"), Optional.of(config(true, "fallback")), response -> response.getBody().then())) - .thenAwait(Duration.ofMillis(30)).thenCancel().verify(Duration.ofSeconds(3)); + .then(() -> await().atMost(Duration.ofSeconds(5)).untilTrue(bodySubscribed)) + .thenCancel().verify(Duration.ofSeconds(10)); assertEquals(3, calls.get()); await().atMost(Duration.ofSeconds(5)).untilTrue(cancelled); } diff --git a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java index f812c47acfe8..131727c8b432 100644 --- a/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java +++ b/shenyu-plugin/shenyu-plugin-security/shenyu-plugin-key-auth/src/main/java/org/apache/shenyu/plugin/key/auth/KeyAuthPlugin.java @@ -18,6 +18,8 @@ package org.apache.shenyu.plugin.key.auth; import org.apache.commons.lang3.StringUtils; +import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; +import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.dto.convert.rule.impl.KeyAuthRuleHandle; @@ -64,14 +66,37 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu || StringUtils.isBlank(keyAuthRuleHandle.getKey())) { recordRejection(exchange, AgentRuntimeMetrics.AuthenticationReason.INVALID_CONFIGURATION); Object error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.KEY_NAME_AND_KEY_MUST_BE_CONFIGURED); - return WebFluxResultUtils.result(exchange, error); + return rejected(exchange, error, selector, rule, "INVALID_CONFIGURATION"); } if (checkKey(exchange, keyAuthRuleHandle.getKeyName(), keyAuthRuleHandle.getKey())) { return KeyAuthAuthentication.execute(exchange, chain, rule); } Object error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.ERROR_KEY); recordRejection(exchange, AgentRuntimeMetrics.AuthenticationReason.CREDENTIAL_REJECTED); - return WebFluxResultUtils.result(exchange, error); + return rejected(exchange, error, selector, rule, "CREDENTIAL_REJECTED"); + } + + private Mono rejected(final ServerWebExchange exchange, final Object error, final SelectorData selector, + final RuleData rule, final String reason) { + return Mono.defer(() -> { + long started = System.nanoTime(); + String requestId = java.util.UUID.randomUUID().toString(); + return WebFluxResultUtils.result(exchange, error).doFinally(signal -> { + Object sink = exchange.getAttribute(AgentInvocationAuditObserver.EXCHANGE_ATTRIBUTE); + if (sink instanceof AgentInvocationAuditObserver audit) { + try { + audit.record(AgentInvocationAuditEvent.logical().requestId(requestId).selectorId(selector.getId()).ruleId(rule.getId()) + .configurationVersion("unknown").policyVersion("key-auth-admission-v1") + .decision(AgentInvocationAuditEvent.Decision.REJECTED) + .outcome(signal == reactor.core.publisher.SignalType.CANCEL ? "CANCELLED" : "REJECTED").reason(reason) + .httpStatus(Objects.isNull(exchange.getResponse().getStatusCode()) ? null : exchange.getResponse().getStatusCode().value()) + .elapsedMillis(java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(Math.max(0, System.nanoTime() - started))).build()); + } catch (RuntimeException ignored) { + // Rejection and its response must not depend on diagnostic delivery. + } + } + }); + }); } private void recordRejection(final ServerWebExchange exchange, final AgentRuntimeMetrics.AuthenticationReason reason) { diff --git a/shenyu-spring-boot-starter/pom.xml b/shenyu-spring-boot-starter/pom.xml index 6af82827846c..161a58f276c0 100644 --- a/shenyu-spring-boot-starter/pom.xml +++ b/shenyu-spring-boot-starter/pom.xml @@ -27,6 +27,7 @@ pom + shenyu-spring-boot-starter-agent-audit shenyu-spring-boot-starter-gateway shenyu-spring-boot-starter-plugin shenyu-spring-boot-starter-sync-data-center diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/pom.xml b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/pom.xml new file mode 100644 index 000000000000..7115703bfd5a --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/pom.xml @@ -0,0 +1,33 @@ + + + + 4.0.0 + + org.apache.shenyu + shenyu-spring-boot-starter + 2.7.2-SNAPSHOT + + shenyu-spring-boot-starter-agent-audit + + + org.apache.shenyu + shenyu-plugin-logging-common + ${project.version} + + + diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollector.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollector.java new file mode 100644 index 000000000000..b0c5a256428f --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollector.java @@ -0,0 +1,119 @@ +/* + * 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.springboot.starter.agent.audit; + +import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; +import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; +import org.apache.shenyu.plugin.logging.common.client.AbstractLogConsumeClient; +import org.apache.shenyu.plugin.logging.common.collector.AbstractLogCollector; +import org.apache.shenyu.plugin.logging.common.config.GenericGlobalConfig; +import org.apache.shenyu.plugin.logging.common.entity.ShenyuRequestLog; +import org.apache.shenyu.plugin.logging.desensitize.api.matcher.KeyWordMatch; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.LongAdder; + +/** + * Metadata adapter using ShenYu's existing bounded logging collector and queue instrumentation. + */ +public final class AgentInvocationAuditCollector extends AbstractLogCollector implements AgentInvocationAuditObserver { + + private final GenericGlobalConfig config = new GenericGlobalConfig(); + + private final Client client; + + public AgentInvocationAuditCollector(final int capacity, final AgentInvocationAuditConsumer consumer) { + if (capacity < 1 || capacity > 65536) { + throw new IllegalArgumentException("Audit queue capacity must be between 1 and 65536"); + } + config.setBufferQueueSize(capacity); + client = new Client(Objects.requireNonNull(consumer, "consumer")); + client.initClient(config); + } + + @Override + public void record(final AgentInvocationAuditEvent event) { + if (Objects.nonNull(event)) { + collect(new AuditLog(event)); + } + } + + public long getFailedRecords() { + return client.failedRecords.sum(); + } + + @Override + protected Client getLogConsumeClient() { + return client; + } + + @Override + protected GenericGlobalConfig getLogCollectConfig() { + return config; + } + + @Override + protected void desensitizeLog(final AuditLog log, final KeyWordMatch match, final String algorithm) { + // Only the immutable, credential-free audit contract is populated; never copy an exchange. + } + + public static final class AuditLog extends ShenyuRequestLog { + + private final AgentInvocationAuditEvent event; + + private AuditLog(final AgentInvocationAuditEvent event) { + this.event = event; + setSelectorId(event.getSelectorId().orElse(null)); + } + } + + public static final class Client extends AbstractLogConsumeClient { + + private final AgentInvocationAuditConsumer consumer; + + private final LongAdder failedRecords = new LongAdder(); + + private Client(final AgentInvocationAuditConsumer consumer) { + this.consumer = consumer; + } + + @Override + public boolean initClient0(final GenericGlobalConfig config) { + return true; + } + + @Override + public void consume0(final List logs) { + try { + consumer.accept(logs.stream().map(log -> log.event).toList()); + } catch (RuntimeException error) { + failedRecords.add(logs.size()); + // Do not log sink exception messages: they may contain backend credentials or payloads. + LoggerFactory.getLogger(AgentInvocationAuditCollector.class).warn("Agent invocation audit sink failed"); + } + } + + @Override + public void close0() { + // The application owns the sink lifecycle. + } + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditConfiguration.java new file mode 100644 index 000000000000..edcf86a65b6d --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditConfiguration.java @@ -0,0 +1,64 @@ +/* + * 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.springboot.starter.agent.audit; + +import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + + +/** + * Opt-in, metadata-only audit delivery shared by agent traffic boundaries. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty(value = "shenyu.plugins.agent.audit.enabled", havingValue = "true") +public class AgentInvocationAuditConfiguration { + + /** + * Expose the trusted sink to authentication plugins that run before Agent Gateway. + * @param observer application or managed observer + * @return metadata-only filter, without a second logical terminal owner + */ + @Bean + public org.springframework.web.server.WebFilter agentInvocationAuditFilter(final AgentInvocationAuditObserver observer) { + return (exchange, chain) -> { + exchange.getAttributes().put(AgentInvocationAuditObserver.EXCHANGE_ATTRIBUTE, observer); + return chain.filter(exchange); + }; + } + + /** + * Create a bounded collector unless the application supplies its own nonblocking sink. + * + * @param environment deployment-owned queue settings + * @param consumers optional application-provided delivery consumer + * @return shared audit observer + */ + @Bean(initMethod = "start", destroyMethod = "close") + @ConditionalOnMissingBean(AgentInvocationAuditObserver.class) + public AgentInvocationAuditCollector agentInvocationAuditCollector(final Environment environment, + final ObjectProvider consumers) { + int capacity = environment.getProperty("shenyu.plugins.agent.audit.queue-capacity", Integer.class, 8192); + AgentInvocationAuditConsumer consumer = consumers.getIfAvailable(() -> AgentInvocationAuditConsumer.LOGGING); + return new AgentInvocationAuditCollector(capacity, consumer); + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditConsumer.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditConsumer.java new file mode 100644 index 000000000000..101b0d2c7733 --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditConsumer.java @@ -0,0 +1,46 @@ +/* + * 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.springboot.starter.agent.audit; + +import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +/** + * Default diagnostic sink. A deployment can replace it without changing agent traffic boundaries. + */ +@FunctionalInterface +public interface AgentInvocationAuditConsumer { + + AgentInvocationAuditConsumer LOGGING = AgentInvocationAuditConsumer::log; + + void accept(List events); + + private static void log(final List events) { + Logger logger = LoggerFactory.getLogger("org.apache.shenyu.agent.invocation.audit"); + events.forEach(event -> logger.info("schema={} type={} request={} tenant={} subject={} apiKeyId={} selector={} rule={} " + + "configuration={} policy={} target={} decision={} outcome={} reason={} status={} attempt={} elapsedMs={} timestamp={}", + event.getSchemaVersion(), event.getRecordType(), event.getRequestId(), event.getTenant().orElse(null), + event.getSubject().orElse(null), event.getApiKeyId().orElse(null), event.getSelectorId().orElse(null), + event.getRuleId().orElse(null), event.getConfigurationVersion(), event.getPolicyVersion(), event.getTarget().orElse(null), + event.getDecision(), event.getOutcome(), event.getReason(), event.getHttpStatus().orElse(null), event.getAttempt().orElse(null), + event.getElapsedMillis(), event.getTimestamp())); + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 000000000000..e6e35687edbb --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1,16 @@ +# 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. + +org.apache.shenyu.springboot.starter.agent.audit.AgentInvocationAuditConfiguration diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/test/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollectorTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/test/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollectorTest.java new file mode 100644 index 000000000000..4f4d2c1e185c --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/test/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollectorTest.java @@ -0,0 +1,141 @@ +/* + * 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.springboot.starter.agent.audit; + +import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; +import org.apache.shenyu.common.metrics.LoggingQueueMetrics; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AgentInvocationAuditCollectorTest { + + @Test + void defaultLoggingSinkWritesMetadataOnly() throws Exception { + ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger("org.apache.shenyu.agent.invocation.audit"); + List messages = new CopyOnWriteArrayList<>(); + ch.qos.logback.core.AppenderBase appender = new ch.qos.logback.core.AppenderBase<>() { + @Override + protected void append(final ch.qos.logback.classic.spi.ILoggingEvent event) { + messages.add(event.getFormattedMessage()); + } + }; + appender.start(); + logger.addAppender(appender); + try (AgentInvocationAuditCollector collector = new AgentInvocationAuditCollector(8, AgentInvocationAuditConsumer.LOGGING)) { + collector.start(); + collector.record(AgentInvocationAuditEvent.logical().requestId("audit-request").apiKeyId("internal-id").outcome("SUCCESS").build()); + await().atMost(Duration.ofSeconds(5)).until(() -> !messages.isEmpty()); + assertTrue(messages.get(0).contains("request=audit-request")); + assertTrue(messages.get(0).contains("apiKeyId=internal-id")); + assertTrue(messages.get(0).contains("schema=1")); + assertTrue(messages.stream().noneMatch(message -> message.contains("Authorization") || message.contains("requestBody"))); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + } + + @Test + void deliversOffRequestThreadThroughExistingCollector() throws Exception { + List delivered = new CopyOnWriteArrayList<>(); + AtomicReference worker = new AtomicReference<>(); + try (AgentInvocationAuditCollector collector = new AgentInvocationAuditCollector(8, batch -> { + worker.set(Thread.currentThread()); + delivered.addAll(batch); + })) { + collector.start(); + collector.record(event("one")); + await().atMost(Duration.ofSeconds(5)).until(() -> delivered.size() == 1); + assertNotEquals(Thread.currentThread(), worker.get()); + assertEquals(1, metrics().getAccepted()); + assertEquals(8, metrics().getCapacity()); + assertEquals(0, metrics().getDropped()); + } + assertTrue(LoggingQueueMetrics.registered().stream().noneMatch(metric -> metric.getCollector().equals(AgentInvocationAuditCollector.class.getName()))); + } + + @Test + void slowSinkDoesNotBlockAdmissionAndOverflowUsesExistingMetrics() throws Exception { + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + try (AgentInvocationAuditCollector collector = new AgentInvocationAuditCollector(2, batch -> { + entered.countDown(); + try { + release.await(5, TimeUnit.SECONDS); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + } + })) { + collector.start(); + collector.record(event("in-flight")); + assertTrue(entered.await(5, TimeUnit.SECONDS)); + try { + collector.record(event("queued-one")); + collector.record(event("queued-two")); + collector.record(event("overflow")); + assertEquals(3, metrics().getAccepted()); + assertEquals(1, metrics().getDropped()); + assertEquals(2, metrics().getQueuedRecords()); + } finally { + release.countDown(); + } + } + } + + @Test + void countsSinkFailuresAndCloseStopsAdmission() throws Exception { + AgentInvocationAuditCollector collector = new AgentInvocationAuditCollector(4, batch -> { + throw new IllegalStateException("secret must not be logged"); + }); + try (collector) { + collector.start(); + collector.record(event("failed")); + await().atMost(Duration.ofSeconds(5)).until(() -> collector.getFailedRecords() == 1); + } + collector.record(event("after-close")); + assertEquals(1, collector.getFailedRecords()); + } + + @Test + void rejectsUnboundedCapacity() { + assertThrows(IllegalArgumentException.class, () -> new AgentInvocationAuditCollector(0, batch -> { })); + assertThrows(IllegalArgumentException.class, () -> new AgentInvocationAuditCollector(65537, batch -> { })); + } + + private LoggingQueueMetrics metrics() { + return LoggingQueueMetrics.registered().stream() + .filter(metric -> metric.getCollector().equals(AgentInvocationAuditCollector.class.getName()) + && metric.getMode() == LoggingQueueMetrics.Mode.SINGLE).findFirst().orElseThrow(); + } + + private AgentInvocationAuditEvent event(final String id) { + return AgentInvocationAuditEvent.logical().requestId(id).outcome("SUCCESS").build(); + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml index fa9b82a31c44..72845af7ea0c 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/pom.xml @@ -26,6 +26,11 @@ shenyu-spring-boot-starter-plugin-agent-gateway + + org.apache.shenyu + shenyu-spring-boot-starter-agent-audit + ${project.version} + org.apache.shenyu shenyu-spring-boot-starter-plugin-tracing diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java index 500858660757..b03a44e4aa1a 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java @@ -18,6 +18,8 @@ package org.apache.shenyu.springboot.starter.plugin.agent.gateway; import io.opentelemetry.api.OpenTelemetry; +import org.apache.shenyu.common.audit.AgentInvocationAuditBridge; +import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver; import org.apache.shenyu.common.metrics.AiCallObserver; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpCallTracer; @@ -69,6 +71,7 @@ public class AgentGatewayPluginConfiguration { * @param tracers optional tracing bridge * @param terminalObservers optional application-owned terminal event sink * @param aiObservers optional application-owned AI attempt and terminal sink + * @param auditors optional unified audit sink * @param environment deployment-controlled tracing opt-in * @param beanFactory application bean factory used to verify the conditional JWT resolver * @return the plugin @@ -78,6 +81,7 @@ public ShenyuPlugin agentGatewayPlugin(final ObjectProvider p final ObjectProvider catalogs, final ObjectProvider tracers, final ObjectProvider terminalObservers, final ObjectProvider aiObservers, + final ObjectProvider auditors, final Environment environment, final BeanFactory beanFactory) { AgentMcpCallTracer tracer = tracers.getIfAvailable(); if (environment.getProperty("shenyu.plugins.agent.gateway.tracing.enabled", Boolean.class, false) && java.util.Objects.isNull(tracer)) { @@ -99,8 +103,10 @@ public ShenyuPlugin agentGatewayPlugin(final ObjectProvider p && !beanFactory.containsBean(JWT_SECURITY_RESOLVER_BEAN_NAME)) { throw new IllegalStateException("Enabled MCP JWT identity requires the optional JWT adapter dependencies"); } - return createPlugin(providers, authorities, catalogs.getIfAvailable(), tracer, terminalObservers.getIfAvailable(), - aiObservers.getIfAvailable(), environment.getProperty("shenyu.plugins.agent.gateway.security.llm.enabled", Boolean.class, false)); + return createPlugin(providers, authorities, catalogs.getIfAvailable(), tracer, + AgentInvocationAuditBridge.mcp(terminalObservers.getIfAvailable(), auditors.getIfAvailable()), + AgentInvocationAuditBridge.ai(aiObservers.getIfAvailable(), auditors.getIfAvailable()), + environment.getProperty("shenyu.plugins.agent.gateway.security.llm.enabled", Boolean.class, false)); } private ShenyuPlugin createPlugin(final ObjectProvider providers, final List resolvers, diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java index 7d9c5ce38922..87db4aae92f4 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java @@ -77,6 +77,19 @@ void shouldKeepPluginUnassembledByDefault() { }); } + @Test + void managedAuditPreservesExistingTerminalObservers() { + contextRunner.withUserConfiguration(org.apache.shenyu.springboot.starter.agent.audit.AgentInvocationAuditConfiguration.class) + .withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.audit.enabled=true") + .withBean(org.apache.shenyu.common.metrics.AiCallObserver.class, () -> event -> { }) + .withBean(org.apache.shenyu.common.metrics.AgentMcpTerminalObserver.class, () -> event -> { }) + .run(context -> { + assertNull(context.getStartupFailure()); + assertEquals(1, context.getBeansOfType(org.apache.shenyu.common.audit.AgentInvocationAuditObserver.class).size()); + assertTrue(context.containsBean("agentGatewayPlugin")); + }); + } + @Test void tracingIsOffByDefaultEvenWithApplicationTelemetry() { contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true") diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java index 5984b0370bce..fd94b8e849d2 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGovernanceHttpTest.java @@ -18,6 +18,9 @@ package org.apache.shenyu.springboot.starter.plugin.agent.gateway; import io.opentelemetry.api.trace.SpanKind; +import org.apache.shenyu.common.audit.AgentInvocationAuditBridge; +import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; +import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; import io.opentelemetry.sdk.trace.SdkTracerProvider; @@ -117,6 +120,10 @@ void invalidKeyIsCountedBeforeAgentRoutingWithoutCreatingALogicalAiCall() { fixture.request("wrong").expectBody().consumeWith(ignored -> { }); assertEquals(0, fixture.upstreamCalls.get()); assertEquals(0, fixture.terminals.size()); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> assertEquals(1, fixture.audits.size())); + assertEquals("CREDENTIAL_REJECTED", fixture.audits.element().getReason()); + assertTrue(fixture.audits.element().getSubject().isEmpty()); + assertEquals(AgentInvocationAuditEvent.RecordType.LOGICAL, fixture.audits.element().getRecordType()); assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AUTHENTICATION_REJECTIONS_TOTAL, new String[]{"source", "reason"}, new String[]{"key_auth", "credential_rejected"})); assertNull(CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_REQUESTS_TOTAL, @@ -132,6 +139,9 @@ void keyAuthToLimiterToProxyHasOneTerminalAndOneBodySubscription(final boolean s assertEquals(fixture.response, response); await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> assertEquals(1, fixture.terminals.size())); assertEquals(1, fixture.attempts.size()); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> assertEquals(2, fixture.audits.size())); + assertTrue(fixture.audits.stream().allMatch(audit -> audit.getTenant().orElseThrow().equals("tenant") + && audit.getSubject().orElseThrow().equals("service") && audit.getOutcome().equals("SUCCESS"))); assertEquals(1, fixture.upstreamCalls.get()); assertEquals(1, fixture.bodySubscriptions.get()); AiTerminalEvent event = fixture.terminals.element(); @@ -169,6 +179,9 @@ void tokenDenialHasTrustedContextWithoutCallingModel() { await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> assertEquals(1, fixture.terminals.size())); AiTerminalEvent event = fixture.terminals.element(); assertEquals(AiCallOutcome.RATE_LIMITED, event.outcome()); + assertEquals(1, fixture.audits.size()); + assertEquals("RATE_LIMITED", fixture.audits.element().getOutcome()); + assertEquals(AgentInvocationAuditEvent.Decision.REJECTED, fixture.audits.element().getDecision()); assertEquals("tenant", event.context().getTenant()); assertEquals(0, event.attemptCount()); assertEquals(AiUsage.UNKNOWN, event.usage()); @@ -190,6 +203,8 @@ private static final class Fixture implements AutoCloseable { private final ConcurrentLinkedQueue attempts = new ConcurrentLinkedQueue<>(); + private final ConcurrentLinkedQueue audits = new ConcurrentLinkedQueue<>(); + private final AtomicInteger upstreamCalls = new AtomicInteger(); private final AtomicInteger bodySubscriptions = new AtomicInteger(); @@ -271,7 +286,8 @@ public void recordAttempt(final AiAttemptEvent event) { } }; AgentGatewayPlugin agent = new AgentGatewayPlugin(new AgentMcpHttpHandler( - new AgentMcpDispatcher(new AgentToolRegistry(List.of()), "fixture", "1"), resolver), resolver, observer); + new AgentMcpDispatcher(new AgentToolRegistry(List.of()), "fixture", "1"), resolver), resolver, + AgentInvocationAuditBridge.ai(observer, audits::add)); agentHandler.handlerRule(register(agent, "{\"trafficType\":\"LLM\"}")); AiPromptPlugin prompt = new AiPromptPlugin(ServerCodecConfigurer.create().getReaders()); RuleData promptRule = register(prompt, "{\"prepend\":\"governed\",\"preRole\":\"system\"}"); @@ -307,6 +323,7 @@ public void recordAttempt(final AiAttemptEvent event) { gateway = HttpServer.create().host("127.0.0.1").port(0).runOn(loops).handle(new ReactorHttpHandlerAdapter( WebHttpHandlerBuilder.webHandler(exchange -> { exchange.getAttributes().put(AgentRuntimeMetrics.KEY, MetricsReporter.agentRuntimeMetrics()); + exchange.getAttributes().put(AgentInvocationAuditObserver.EXCHANGE_ATTRIBUTE, (AgentInvocationAuditObserver) audits::add); org.springframework.http.server.reactive.ServerHttpRequestDecorator request = new org.springframework.http.server.reactive.ServerHttpRequestDecorator(exchange.getRequest()) { @Override public Flux getBody() { diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/pom.xml b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/pom.xml index 41a03ba8f5b6..279b1c112938 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/pom.xml +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/pom.xml @@ -26,6 +26,11 @@ shenyu-spring-boot-starter-plugin-ai-proxy + + org.apache.shenyu + shenyu-spring-boot-starter-agent-audit + ${project.version} + org.apache.shenyu shenyu-plugin-ai-proxy diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/test/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfigurationTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/test/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfigurationTest.java index 6420a9ea016f..610dae60527b 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/test/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfigurationTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/test/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfigurationTest.java @@ -72,6 +72,17 @@ void acceptsOneApplicationObserverAndRejectsAmbiguousSinks() { .run(context -> org.assertj.core.api.Assertions.assertThat(context).hasFailed()); } + @Test + void managedAuditCanCoexistWithExistingObserverInAiOnlyDeployment() { + contextRunner.withConfiguration(AutoConfigurations.of( + org.apache.shenyu.springboot.starter.agent.audit.AgentInvocationAuditConfiguration.class)) + .withPropertyValues("shenyu.plugins.agent.audit.enabled=true") + .withBean(AiCallObserver.class, () -> event -> { }) + .run(context -> org.assertj.core.api.Assertions.assertThat(context).hasNotFailed() + .hasSingleBean(org.apache.shenyu.common.audit.AgentInvocationAuditObserver.class) + .hasSingleBean(AiProxyPlugin.class)); + } + @Test void createsTheMigratedPluginAndAllExistingProviderIdentifiers() { new ApplicationContextRunner().withUserConfiguration(AiProxyPluginConfiguration.class).run(context -> { From 19d83df77477437f88c40ce9a1f2c73f71f7b975 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Sat, 24 Oct 2026 22:12:21 +0800 Subject: [PATCH 05/36] feat(agent-gateway): add bounded mcp resource admission --- docs/agent-gateway-resource-admission.md | 40 ++ .../dto/AgentGatewayAdmissionConfig.java | 77 ++++ .../dto/AgentGatewayAggregationConfig.java | 17 +- .../common/metrics/AgentAdmissionMetrics.java | 73 ++++ .../AgentGatewayAggregationConfigTest.java | 20 + .../gateway/protocol/AgentMcpDispatcher.java | 30 +- .../protocol/AgentMcpRemoteCatalog.java | 8 + .../protocol/AgentMcpResourceAdmission.java | 112 ++++++ .../protocol/AgentResourceAdmission.java | 356 ++++++++++++++++++ .../remote/ManagedRemoteMcpCatalog.java | 47 ++- .../agent/gateway/tool/AgentToolRegistry.java | 19 +- .../protocol/AgentMcpDispatcherTest.java | 24 ++ .../protocol/AgentResourceAdmissionTest.java | 195 ++++++++++ .../remote/ManagedRemoteMcpCatalogTest.java | 22 ++ .../RequestScopedMcpClientAdmissionTest.java | 193 ++++++++++ .../proxy/enhanced/service/AiProxyEngine.java | 6 + .../AgentAdmissionMetricsCollector.java | 72 ++++ .../prometheus/PrometheusMetricsService.java | 1 + .../AgentAdmissionMetricsCollectorTest.java | 38 ++ .../AgentGatewayPluginConfiguration.java | 10 +- 20 files changed, 1345 insertions(+), 15 deletions(-) create mode 100644 docs/agent-gateway-resource-admission.md create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientAdmissionTest.java create mode 100644 shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollector.java create mode 100644 shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollectorTest.java diff --git a/docs/agent-gateway-resource-admission.md b/docs/agent-gateway-resource-admission.md new file mode 100644 index 000000000000..692b05006974 --- /dev/null +++ b/docs/agent-gateway-resource-admission.md @@ -0,0 +1,40 @@ +# Agent Gateway resource admission + +Agent Gateway applies deterministic admission around every `tools/call` execution. Admission is deliberately not a retry or circuit-breaking layer: a call still executes at most once. + +## Configuration + +The trusted plugin configuration may contain one `admission` object: + +```json +{ + "admission": { + "globalInFlight": 128, + "globalQueued": 64, + "localInFlight": 32, + "localQueued": 16, + "remoteInFlight": 8, + "remoteQueued": 16 + } +} +``` + +Omitting the object or supplying an empty object selects these defaults. Admin and gateway reject unknown fields and values outside the hard maxima (`128`, `256`, `64`, `128`, `32`, and `128` respectively). + +## Semantics + +- `global*` bounds all concurrent local and remote tool executions and their waiting work. +- `local*` bounds startup and request-local HTTP tool providers together. +- `remote*` is applied independently for each configured remote MCP server name. +- Queued work uses the request's absolute deadline. Time spent waiting counts against execution time. +- Queue overflow returns HTTP `429` and JSON-RPC `-32026`; an expired queued request returns HTTP `504` and `-32026`. +- Every success, business error, gateway error, cancellation, timeout, configuration withdrawal and shutdown releases each acquired permit once. +- Existing byte limits, transport concurrency, catalog generation leases and no-retry behavior remain in force. + +## Metrics + +The Prometheus exporter publishes payload-free aggregates by fixed scope (`global`, `local`, `remote`): `shenyu_agent_admission_inflight`, `shenyu_agent_admission_queued`, `shenyu_agent_admission_inflight_limit`, `shenyu_agent_admission_queue_limit` and `shenyu_agent_admission_rejections_total`. Tool names, subjects, tenants and endpoints are never labels. + +## Sizing guidance + +Keep the global budget at or below the gateway process's sustainable CPU and response-memory budget. Reserve a separate remote in-flight budget for each latency-critical MCP server, and keep remote queues small: queued remote calls consume a shared global slot while waiting. Increase queue sizes only when clients can tolerate waiting until the existing request deadline; admission does not extend deadlines. diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java new file mode 100644 index 000000000000..2f25a72fec28 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAdmissionConfig.java @@ -0,0 +1,77 @@ +/* + * 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.dto; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.Objects; + +/** + * Strict fixed resource-admission limits shared by Admin and the gateway. + */ +public record AgentGatewayAdmissionConfig(int globalInFlight, int globalQueued, + int localInFlight, int localQueued, + int remoteInFlight, int remoteQueued) { + + private static final AgentGatewayAdmissionConfig DEFAULT = new AgentGatewayAdmissionConfig(128, 64, 32, 16, 8, 16); + + public AgentGatewayAdmissionConfig { + range("globalInFlight", globalInFlight, 1, 128); + range("globalQueued", globalQueued, 0, 256); + range("localInFlight", localInFlight, 1, 64); + range("localQueued", localQueued, 0, 128); + range("remoteInFlight", remoteInFlight, 1, 32); + range("remoteQueued", remoteQueued, 0, 128); + } + + /** + * Parse the optional trusted plugin field. Null selects safe operational defaults. + * @param node admission object from plugin configuration + * @return immutable admission limits + */ + public static AgentGatewayAdmissionConfig parse(final JsonNode node) { + if (Objects.isNull(node)) { + return DEFAULT; + } + if (!node.isObject() || node.isEmpty()) { + return DEFAULT; + } + java.util.Set fields = new java.util.HashSet<>(); + node.fieldNames().forEachRemaining(fields::add); + if (!fields.equals(java.util.Set.of("globalInFlight", "globalQueued", "localInFlight", + "localQueued", "remoteInFlight", "remoteQueued"))) { + throw new IllegalArgumentException("Unknown or missing admission field"); + } + return new AgentGatewayAdmissionConfig(number(node, "globalInFlight"), number(node, "globalQueued"), + number(node, "localInFlight"), number(node, "localQueued"), + number(node, "remoteInFlight"), number(node, "remoteQueued")); + } + + private static int number(final JsonNode node, final String field) { + if (!node.path(field).isInt()) { + throw new IllegalArgumentException("Admission field must be an integer"); + } + return node.get(field).asInt(); + } + + private static void range(final String field, final int value, final int minimum, final int maximum) { + if (value < minimum || value > maximum) { + throw new IllegalArgumentException("Admission field is outside its hard maximum: " + field); + } + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfig.java b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfig.java index b36353785f1f..965416948844 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfig.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfig.java @@ -31,11 +31,13 @@ import java.util.Set; /** Strict, secret-free configuration shared by Admin and gateway. */ -public record AgentGatewayAggregationConfig(String revision, List servers) { +public record AgentGatewayAggregationConfig(String revision, List servers, AgentGatewayAdmissionConfig admission) { private static final ObjectMapper JSON = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION) .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final AgentGatewayAdmissionConfig DEFAULT_ADMISSION = AgentGatewayAdmissionConfig.parse(null); + public AgentGatewayAggregationConfig { if (Objects.isNull(revision) || !revision.matches("[A-Za-z0-9_-]{1,48}")) { throw new IllegalArgumentException("Invalid aggregation revision"); @@ -53,7 +55,7 @@ public record AgentGatewayAggregationConfig(String revision, List server */ public static AgentGatewayAggregationConfig parsePluginConfig(final String source) { if (Objects.isNull(source) || source.isBlank()) { - return new AgentGatewayAggregationConfig("empty", List.of()); + return new AgentGatewayAggregationConfig("empty", List.of(), DEFAULT_ADMISSION); } if (source.getBytes(StandardCharsets.UTF_8).length > 16384) { throw new IllegalArgumentException("Aggregation configuration byte limit"); @@ -64,9 +66,13 @@ public static AgentGatewayAggregationConfig parsePluginConfig(final String sourc throw new IllegalArgumentException("Expected plugin configuration object"); } if (root.isEmpty()) { - return new AgentGatewayAggregationConfig("empty", List.of()); + return new AgentGatewayAggregationConfig("empty", List.of(), DEFAULT_ADMISSION); + } + Set pluginFields = new HashSet<>(Set.of("aggregation")); + if (root.has("admission")) { + pluginFields.add("admission"); } - fields(root, Set.of("aggregation")); + fields(root, pluginFields); JsonNode aggregation = root.get("aggregation"); fields(aggregation, Set.of("revision", "servers")); if (!aggregation.path("servers").isArray()) { @@ -78,7 +84,8 @@ public static AgentGatewayAggregationConfig parsePluginConfig(final String sourc servers.add(new Server(text(server, "name"), URI.create(text(server, "endpoint")), text(server, "credentialRef"), text(server, "credentialVersion"))); } - return new AgentGatewayAggregationConfig(text(aggregation, "revision"), servers); + return new AgentGatewayAggregationConfig(text(aggregation, "revision"), servers, + AgentGatewayAdmissionConfig.parse(root.get("admission"))); } catch (Exception error) { // Do not include raw config or a parse exception which could contain a supplied secret. throw new IllegalArgumentException("Invalid Agent Gateway aggregation configuration"); diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java new file mode 100644 index 000000000000..4c87eccb4bf7 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java @@ -0,0 +1,73 @@ +/* + * 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.metrics; + +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** Live payload-free admission snapshots, without tool, subject, tenant, or endpoint labels. */ +public final class AgentAdmissionMetrics implements AutoCloseable { + + private static final Set SOURCES = ConcurrentHashMap.newKeySet(); + + private final Supplier> source; + + private AgentAdmissionMetrics(final Supplier> source) { + this.source = source; + } + + /** + * Register one controller after startup; the controller owns this registration. + * @param source in-memory snapshot supplier + * @return registration removed by close + */ + public static AgentAdmissionMetrics register(final Supplier> source) { + AgentAdmissionMetrics value = new AgentAdmissionMetrics(source); + SOURCES.add(value); + return value; + } + + /** Aggregate all live controller states. + * @return immutable snapshots + */ + public static List snapshots() { + return SOURCES.stream().flatMap(registration -> { + try { + return registration.source.get().stream(); + } catch (RuntimeException ignored) { + return java.util.stream.Stream.empty(); + } + }).toList(); + } + + @Override + public void close() { + SOURCES.remove(this); + } + + /** One bounded scope; names never carry request or target identity. */ + public record Snapshot(Scope scope, int inFlight, int queued, int inFlightLimit, int queueLimit, long rejected) { + } + + /** Fixed admission scopes, safe as metric labels. */ + public enum Scope { + GLOBAL, LOCAL, REMOTE + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfigTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfigTest.java index f614f8a56328..6b42ac4eb0bf 100644 --- a/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfigTest.java +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/dto/AgentGatewayAggregationConfigTest.java @@ -54,6 +54,26 @@ void freezesServerReferencesAndAcceptsHttpsSyntax() { assertThrows(IllegalArgumentException.class, () -> AgentGatewayAggregationConfig.parsePluginConfig(wrap(server + "," + server))); } + @Test + void parsesOptionalStrictAdmissionConfiguration() { + String source = "{\"aggregation\":{\"revision\":\"v1\",\"servers\":[]}," + + "\"admission\":{\"globalInFlight\":1,\"globalQueued\":2,\"localInFlight\":3," + + "\"localQueued\":4,\"remoteInFlight\":5,\"remoteQueued\":6}}"; + AgentGatewayAdmissionConfig admission = AgentGatewayAggregationConfig.parsePluginConfig(source).admission(); + assertEquals(1, admission.globalInFlight()); + assertEquals(2, admission.globalQueued()); + assertEquals(3, admission.localInFlight()); + assertEquals(4, admission.localQueued()); + assertEquals(5, admission.remoteInFlight()); + assertEquals(6, admission.remoteQueued()); + } + + @Test + void rejectsUnknownOrExcessiveAdmissionFields() { + assertThrows(IllegalArgumentException.class, () -> new AgentGatewayAdmissionConfig(0, 0, 1, 0, 1, 0)); + assertThrows(IllegalArgumentException.class, () -> new AgentGatewayAdmissionConfig(129, 0, 1, 0, 1, 0)); + } + @ParameterizedTest @ValueSource(strings = {"http://user:pass@127.0.0.1:8080/mcp", "http://127.0.0.1/mcp", "http://127.0.0.1:8080/a/../mcp", "http://127.0.0.1:8080/mcp?key=SECRET", "http://127.0.0.1:8080/mcp#SECRET", "http://127.0.0.1:8080/%2e/mcp", diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java index 04c68209e342..3cb6c5ccb9df 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java @@ -50,6 +50,8 @@ public final class AgentMcpDispatcher { private final AgentMcpRemoteCatalog remoteCatalog; + private final AgentMcpResourceAdmission admission; + private final String serverName; private final String serverVersion; @@ -61,8 +63,14 @@ public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverN } public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion, final AgentMcpRemoteCatalog remoteCatalog) { + this(registry, serverName, serverVersion, remoteCatalog, AgentMcpResourceAdmission.NOOP); + } + + public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion, + final AgentMcpRemoteCatalog remoteCatalog, final AgentMcpResourceAdmission admission) { this.registry = Objects.requireNonNull(registry, "registry"); this.remoteCatalog = remoteCatalog; + this.admission = Objects.requireNonNull(admission, "admission"); if (Objects.requireNonNull(serverName, "serverName").isBlank() || Objects.requireNonNull(serverVersion, "serverVersion").isBlank()) { throw new IllegalArgumentException("Server identity must not be blank"); } @@ -89,7 +97,8 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier bound); + return new AgentMcpDispatcher(captured, serverName, serverVersion, remoteCatalog, + Objects.isNull(remoteCatalog) ? admission : remoteCatalog.admission()).dispatch(request, () -> bound); } if (Objects.nonNull(remoteCatalog)) { return remoteCatalog.withSnapshot(snapshot -> routeWithRemote(request, context, snapshot)) @@ -120,6 +129,13 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier routeWithRemote(final AgentMcpRequest request, final Ag ObjectNode params = request.getParams(); JsonObject arguments = params.has("arguments") ? JsonParser.parseString(params.get("arguments").toString()).getAsJsonObject() : new JsonObject(); return Mono.defer(() -> { - context.notifyAttempt(); - return snapshot.invoke(name, arguments, context); + return admission.withRemote(remoteServer(name), context.getDeadline(), + Mono.fromRunnable(context::notifyAttempt).then(snapshot.invoke(name, arguments, context))); }) .switchIfEmpty(Mono.error(new IllegalStateException("Remote tool completed without a result"))) .map(value -> { @@ -225,7 +241,8 @@ private Mono call(final AgentMcpRequest request, final AgentMcpExecu JsonObject capabilities = request.getClientCapabilities(); return registry.invoke(name, context.getAllowedTools(), () -> new AgentToolInvocation(context.getRequestId(), context.getSubject(), arguments, - context.getRuleId(), context.getConfigurationVersion(), context.getDeadline(), capabilities), context::notifyAttempt) + context.getRuleId(), context.getConfigurationVersion(), context.getDeadline(), capabilities), context::notifyAttempt, + execution -> admission.withLocal(context.getDeadline(), execution)) .map(value -> { // Active field policies must not introduce an opaque metadata channel. ObjectNode result = filter.isActive() ? mapper.createObjectNode().put("resultType", "complete") : complete(); @@ -256,6 +273,11 @@ private ObjectNode toolFailure(final AgentMcpRequest request, final String messa return response(request, filterResult(request, filter, result)); } + private String remoteServer(final String exposedName) { + int separator = exposedName.indexOf('.'); + return separator > 0 ? exposedName.substring(0, separator) : exposedName; + } + private AgentMcpResultFilter prepareResultFilter(final AgentMcpRequest request, final AgentMcpExecutionContext context, final String name, final JsonNode schema) { try { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java index 14c555012131..efc2cd3607a1 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java @@ -36,6 +36,14 @@ public interface AgentMcpRemoteCatalog { */ Mono withSnapshot(Function> operation); + /** Return the closeable request-admission controller owned by this catalog. + * @return controller implementation + */ + default AgentMcpResourceAdmission admission() { + return AgentMcpResourceAdmission.NOOP; + } + + /** Distinguishes an unavailable catalog from unexpected gateway failures. */ final class CatalogUnavailableException extends IllegalStateException { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java new file mode 100644 index 000000000000..3698a1c2fd20 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java @@ -0,0 +1,112 @@ +/* + * 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.plugin.agent.gateway.protocol; + +import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; +import reactor.core.publisher.Mono; + +import java.time.Instant; +import java.util.Objects; + +/** Optional resource-admission port; the no-op implementation preserves existing behavior. */ +public interface AgentMcpResourceAdmission { + + AgentMcpResourceAdmission NOOP = new AgentMcpResourceAdmission() { + @Override + public Mono withLocal(final Instant deadline, final Mono action) { + return action; + } + + @Override + public Mono withRemote(final String server, final Instant deadline, final Mono action) { + return action; + } + }; + + /** Bound one local-provider execution. + * @param deadline absolute request deadline + * @param action controlled execution +* @param result type + * @return controlled result + */ + Mono withLocal(Instant deadline, Mono action); + + /** Bound one configured remote-server execution. + * @param server stable target name, never Agent input + * @param deadline absolute request deadline + * @param action controlled execution +* @param result type + * @return controlled result + */ + Mono withRemote(String server, Instant deadline, Mono action); + + /** Wrap the concrete deterministic controller while retaining the small port. + * @param config trusted hard-bounded configuration + * @return closeable port implementation + */ + static ResourceAdmissionController create(final AgentGatewayAdmissionConfig config) { + return new ResourceAdmissionController(new AgentResourceAdmission(config)); + } + + /** Closeable wrapper used by the Spring lifecycle. */ + final class ResourceAdmissionController implements AgentMcpResourceAdmission, AutoCloseable { + + private final AgentResourceAdmission delegate; + + private volatile AgentResourceAdmission current; + + private ResourceAdmissionController(final AgentResourceAdmission delegate) { + this.delegate = delegate; + this.current = delegate; + } + + @Override + public Mono withLocal(final Instant deadline, final Mono action) { + return current.withLocal(deadline, action); + } + + @Override + public Mono withRemote(final String server, final Instant deadline, final Mono action) { + return current.withRemote(server, deadline, action); + } + + /** + * Atomically install new limits and close only the retired controller. + * @param replacement validated replacement controller + */ + public void replace(final ResourceAdmissionController replacement) { + Objects.requireNonNull(replacement, "replacement"); + synchronized (this) { + if (current != delegate) { + return; + } + current = replacement.delegate; + } + delegate.close(); + } + + @Override + public void close() { + AgentResourceAdmission active; + synchronized (this) { + active = current; + } + active.close(); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java new file mode 100644 index 000000000000..8b34532f5fca --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java @@ -0,0 +1,356 @@ +/* + * 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.plugin.agent.gateway.protocol; + +import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; +import org.apache.shenyu.common.metrics.AgentAdmissionMetrics; +import reactor.core.publisher.Mono; + +import java.time.Instant; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicLong; +import java.util.ArrayDeque; +import java.util.Deque; + +/** Deterministic gateway resource admission with bounded deadline-aware queues. */ +public final class AgentResourceAdmission implements AutoCloseable { + + private final AgentGatewayAdmissionConfig config; + + private final Scope global; + + private final Scope local; + + private final Deque remotes = new ArrayDeque<>(); + + private final AgentAdmissionMetrics registration; + + private volatile boolean closed; + + public AgentResourceAdmission(final AgentGatewayAdmissionConfig config) { + this.config = Objects.requireNonNull(config, "config"); + global = new Scope("global", config.globalInFlight(), config.globalQueued()); + local = new Scope("local", config.localInFlight(), config.localQueued()); + registration = AgentAdmissionMetrics.register(this::snapshot); + } + + /** + * Acquire global and LOCAL admission around the single local provider execution. + * @param deadline absolute request deadline, including queue wait + * @param action execution after all permits are acquired + * @param response type + * @return one execution result with terminal permit release + */ + public Mono withLocal(final Instant deadline, final Mono action) { + return with(global, deadline, with(local, deadline, action)); + } + + /** + * Acquire global and one stable remote-server scope around a single tool call. + * @param server configured remote target name + * @param deadline absolute request deadline, including queue wait + * @param action execution after all permits are acquired +* @param response type + * @return one execution result with terminal permit release + */ + public Mono withRemote(final String server, final Instant deadline, final Mono action) { + return with(global, deadline, with(remote(server), deadline, action)); + } + + private Mono with(final Scope scope, final Instant deadline, final Mono action) { + return Mono.defer(() -> { + if (closed) { + scope.rejected.incrementAndGet(); + return Mono.error(AgentAdmissionException.closed()); + } + AcquireResult acquired = scope.acquire(deadline); + if (Objects.nonNull(acquired.error)) { + return Mono.error(acquired.error); + } + return acquired.wait.admission() + .timeout(Duration.between(Instant.now(), deadline)) + .onErrorMap(java.util.concurrent.TimeoutException.class, + error -> AgentAdmissionException.deadline()) + .then(action) + .doFinally(signal -> scope.release(acquired.wait)); + }); + } + + private Scope remote(final String name) { + if (Objects.isNull(name) || !name.matches("[A-Za-z0-9_-]{1,48}")) { + throw new IllegalArgumentException("Invalid remote admission scope"); + } + for (Scope scope : remotes) { + if (scope.name.equals(name)) { + return scope; + } + } + synchronized (remotes) { + for (Scope scope : remotes) { + if (scope.name.equals(name)) { + return scope; + } + } + Scope scope = new Scope(name, config.remoteInFlight(), config.remoteQueued()); + remotes.add(scope); + return scope; + } + } + + /** + * Secret-free live states for bounded runtime metrics. + * @return immutable controller snapshot + */ + public List snapshot() { + List result = new ArrayList<>(); + result.add(global.snapshot(AgentAdmissionMetrics.Scope.GLOBAL)); + result.add(local.snapshot(AgentAdmissionMetrics.Scope.LOCAL)); + remotes.forEach(scope -> result.add(scope.snapshot(AgentAdmissionMetrics.Scope.REMOTE))); + return result; + } + + /** Stop new work and cancel queued waiters; terminal executions still release once. */ + public void close() { + closed = true; + registration.close(); + global.close(); + local.close(); + remotes.forEach(Scope::close); + } + + /** Explicit resource-limit rejection, distinguishable from provider failures. */ + public static final class AgentAdmissionException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private final boolean timeout; + + private final boolean closed; + + private AgentAdmissionException(final boolean timeout, final boolean closed) { + super(timeout ? "Admission deadline exceeded" : closed ? "Gateway admission closed" : "Gateway resource limit exceeded"); + this.timeout = timeout; + this.closed = closed; + } + + static AgentAdmissionException overloaded() { + return new AgentAdmissionException(false, false); + } + + static AgentAdmissionException deadline() { + return new AgentAdmissionException(true, false); + } + + private static AgentAdmissionException closed() { + return new AgentAdmissionException(false, true); + } + + /** Whether the request already exhausted its absolute deadline. + * @return deadline category + */ + public boolean isTimeout() { + return timeout; + } + } + + private static final class Wait { + + private final Scope scope; + + private final Waiter waiter; + + private final boolean queued; + + private Wait(final Scope scope, final Waiter waiter) { + this.scope = scope; + this.waiter = waiter; + this.queued = Objects.nonNull(waiter); + } + + private Mono admission() { + return Objects.isNull(waiter) ? Mono.empty() : waiter.ready.asMono(); + } + } + + private static final class Scope { + + private final String name; + + private final int inFlightLimit; + + private final int queueLimit; + + private final AtomicLong rejected = new AtomicLong(); + + private final Object lock = new Object(); + + private final Deque waiting = new ArrayDeque<>(); + + private int inFlight; + + private int queued; + + private boolean closed; + + private Scope(final String name, final int inFlightLimit, final int queueLimit) { + this.name = name; + this.inFlightLimit = inFlightLimit; + this.queueLimit = queueLimit; + } + + AcquireResult acquire(final Instant deadline) { + synchronized (lock) { + if (closed) { + rejected.incrementAndGet(); + return AcquireResult.reject(AgentAdmissionException.closed()); + } + if (inFlight < inFlightLimit) { + inFlight++; + return AcquireResult.admitted(new Wait(this, null)); + } + if (queued >= queueLimit) { + rejected.incrementAndGet(); + return AcquireResult.reject(AgentAdmissionException.overloaded()); + } + if (!Instant.now().isBefore(deadline)) { + rejected.incrementAndGet(); + return AcquireResult.reject(AgentAdmissionException.deadline()); + } + Waiter waiter = new Waiter(deadline); + waiting.addLast(waiter); + queued++; + return AcquireResult.admitted(new Wait(this, waiter)); + } + } + + void release(final Wait wait) { + if (Objects.isNull(wait.waiter)) { + completeActive(wait); + return; + } + boolean promoted; + synchronized (lock) { + promoted = wait.waiter.state == State.PROMOTED; + if (wait.waiter.state == State.WAITING && waiting.remove(wait.waiter)) { + queued--; + rejected.incrementAndGet(); + } + wait.waiter.completeExceptionally(AgentAdmissionException.deadline()); + if (promoted) { + completeActive(wait); + } + } + } + + private void completeActive(final Wait wait) { + synchronized (lock) { + inFlight--; + promote(); + } + } + + private void promote() { + while (inFlight < inFlightLimit) { + Waiter next = waiting.pollFirst(); + if (Objects.isNull(next)) { + return; + } + queued--; + if (!Instant.now().isBefore(next.deadline) || closed) { + rejected.incrementAndGet(); + next.completeExceptionally(AgentAdmissionException.deadline()); + continue; + } + inFlight++; + next.complete(); + return; + } + } + + + void close() { + synchronized (lock) { + closed = true; + Waiter wait; + while (Objects.nonNull(wait = waiting.pollFirst())) { + queued--; + rejected.incrementAndGet(); + wait.completeExceptionally(AgentAdmissionException.closed()); + } + } + } + + AgentAdmissionMetrics.Snapshot snapshot(final AgentAdmissionMetrics.Scope scope) { + synchronized (lock) { + return new AgentAdmissionMetrics.Snapshot(scope, inFlight, queued, inFlightLimit, queueLimit, rejected.get()); + } + } + } + + private static final class Waiter { + + private final reactor.core.publisher.Sinks.One ready = reactor.core.publisher.Sinks.one(); + + private final Instant deadline; + + private State state = State.WAITING; + + private Waiter(final Instant deadline) { + this.deadline = deadline; + } + + void complete() { + state = State.PROMOTED; + ready.tryEmitValue(null); + } + + void completeExceptionally(final AgentAdmissionException error) { + state = State.TERMINATED; + ready.tryEmitError(error); + } + } + + private enum State { + WAITING, + PROMOTED, + TERMINATED + } + + private static final class AcquireResult { + + private final Wait wait; + + private final Throwable error; + + private AcquireResult(final Wait wait, final Throwable error) { + this.wait = wait; + this.error = error; + } + + static AcquireResult admitted(final Wait wait) { + return new AcquireResult(wait, null); + } + + static AcquireResult reject(final Throwable error) { + return new AcquireResult(null, error); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java index 78688caa9cb6..707ca2c7c10f 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java @@ -23,12 +23,14 @@ import com.google.gson.JsonObject; import io.modelcontextprotocol.common.McpTransportContext; import org.apache.shenyu.common.dto.AgentGatewayAggregationConfig; +import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; import org.apache.shenyu.common.dto.PluginData; import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.common.metrics.AgentCatalogMetrics; import org.apache.shenyu.common.tracing.AgentTraceContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpRemoteCatalog; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; @@ -66,6 +68,10 @@ public final class ManagedRemoteMcpCatalog implements AgentMcpRemoteCatalog, Aut private final RemoteServiceCredentialResolver credentials; + private final AgentMcpResourceAdmission.ResourceAdmissionController admission; + + private volatile AgentGatewayAdmissionConfig admissionConfig; + private final Scheduler scheduler = Schedulers.newBoundedElastic(1, 16, "agent-mcp-config"); private final Sinks.Many updates = Sinks.many().unicast().onBackpressureBuffer(new ArrayBlockingQueue<>(16)); @@ -87,9 +93,25 @@ public final class ManagedRemoteMcpCatalog implements AgentMcpRemoteCatalog, Aut * @param credentials trusted credentials value */ public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames, final RemoteServiceCredentialResolver credentials) { + this(allowedEndpoints, localNames, credentials, null); + } + + /** + * Managed Remote Mcp Catalog with admission configuration. + * @param allowedEndpoints trusted allowedEndpoints value + * @param localNames trusted localNames value + * @param credentials trusted credentials value + * @param source complete trusted plugin configuration + */ + public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames, + final RemoteServiceCredentialResolver credentials, final String source) { this.allowedEndpoints = Set.copyOf(allowedEndpoints); this.localNames = Set.copyOf(localNames); this.credentials = Objects.requireNonNull(credentials, "credentials"); + this.admissionConfig = Objects.isNull(source) + ? AgentGatewayAdmissionConfig.parse(null) + : AgentGatewayAggregationConfig.parsePluginConfig(source).admission(); + this.admission = AgentMcpResourceAdmission.create(this.admissionConfig); this.allowedEndpoints.forEach(RemoteTransportPolicy::endpoint); // The single owned subscription belongs to the control-plane lifecycle, never a request. lifecycle.refresh(List.of()).block(Duration.ofSeconds(6)); @@ -163,7 +185,13 @@ private Mono reload(final String source, final BooleanSupplier stillCurren RemoteServerBinding.Config reference = new RemoteServerBinding.Config(server.name(), server.endpoint(), server.credentialRef(), server.credentialVersion()); targets.add(RemoteServerBinding.resolve(reference, allowedEndpoints, credentials::resolve).lifecycleConfig()); } - return lifecycle.refresh(targets, List.of(), localNames, stillCurrent); + return lifecycle.refresh(targets, List.of(), localNames, stillCurrent) + .doOnSuccess(ignored -> { + if (stillCurrent.getAsBoolean()) { + admission.replace(AgentMcpResourceAdmission.create(config.admission())); + admissionConfig = config.admission(); + } + }); }); } @@ -184,6 +212,19 @@ public Mono withSnapshot(final Function> }); } + @Override + public AgentMcpResourceAdmission admission() { + return admission; + } + + /** + * Current validated admission limits. + * @return immutable trusted configuration + */ + public AgentGatewayAdmissionConfig admissionConfig() { + return admissionConfig; + } + /** * Secret-free lifecycle diagnostics for management and verification. * @return immutable diagnostic values @@ -192,6 +233,9 @@ public Map diagnostics() { Diagnostics state = diagnosticsState(); Map result = new LinkedHashMap<>(state.lifecycle().toMap()); result.put("lastFailure", state.lastFailure()); + result.put("admission", Map.of("globalInFlight", admissionConfig.globalInFlight(), "globalQueued", admissionConfig.globalQueued(), + "localInFlight", admissionConfig.localInFlight(), "localQueued", admissionConfig.localQueued(), + "remoteInFlight", admissionConfig.remoteInFlight(), "remoteQueued", admissionConfig.remoteQueued())); return Map.copyOf(result); } @@ -217,6 +261,7 @@ public Mono closeAsync() { return Mono.defer(() -> { closed = true; catalogMetrics.close(); + admission.close(); worker.dispose(); scheduler.dispose(); return lifecycle.closeGracefully(); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java index 4a1efa63388b..32d334ea413e 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java @@ -26,6 +26,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.function.Function; import java.util.function.Supplier; /** @@ -150,8 +151,24 @@ public Mono invoke(final String name, final Set allowedTools */ public Mono invoke(final String name, final Set allowedTools, final Supplier input, final Runnable onAttempt) { + return invoke(name, allowedTools, input, onAttempt, execution -> execution); + } + + /** + * Invoke a validated tool through an execution wrapper supplied by the trusted caller. + * @param name tool name + * @param allowedTools effective permissions + * @param input request-local invocation factory + * @param onAttempt nonblocking callback before provider execution + * @param executionWrapper admission or lifecycle boundary around one execution + * @return request-local result + */ + public Mono invoke(final String name, final Set allowedTools, + final Supplier input, final Runnable onAttempt, + final Function, Mono> executionWrapper) { Set permissions = Set.copyOf(allowedTools); Objects.requireNonNull(input, "input"); + Objects.requireNonNull(executionWrapper, "executionWrapper"); return Mono.defer(() -> { AgentToolProvider provider = providers.get(name); if (!permissions.contains(name) || Objects.isNull(provider)) { @@ -168,7 +185,7 @@ public Mono invoke(final String name, final Set allowedTools throw new AgentToolArgumentException(error); } onAttempt.run(); - return provider.invoke(invocation) + return executionWrapper.apply(provider.invoke(invocation)) .switchIfEmpty(Mono.error(new IllegalStateException("Tool completed without a result"))) .map(JsonObject::deepCopy); }); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java index 96835df22a18..c7371ba00f03 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.JsonObject; +import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; import com.google.gson.JsonParser; import org.apache.shenyu.plugin.agent.gateway.AgentGatewayConstants; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolExecutionException; @@ -429,6 +430,29 @@ void shouldKeepDeclaredCapabilitiesRequestLocalAndSeparateFromAuthorization() { assertEquals(1, calls.get()); } + @Test + void shouldAdmitLocalToolOnlyAfterPreExecutionValidation() { + AtomicInteger admitted = new AtomicInteger(); + AgentMcpResourceAdmission.ResourceAdmissionController admission = AgentMcpResourceAdmission.create( + new AgentGatewayAdmissionConfig(1, 0, 1, 0, 1, 0)); + try { + AgentToolProvider invalid = provider("order_status", input -> { + throw new IllegalArgumentException("invalid private input"); + }, input -> { + admitted.incrementAndGet(); + return Mono.just(input.getArguments()); + }); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher(new AgentToolRegistry(List.of(invalid)), + "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, null, admission); + StepVerifier.create(dispatcher.dispatch(request("tools/call", "1", "order_status"), () -> context("A", Set.of("order_status")))) + .assertNext(response -> assertTrue(response.path("result").path("isError").booleanValue())) + .verifyComplete(); + assertEquals(0, admitted.get()); + } finally { + admission.close(); + } + } + private AgentMcpExecutionContext context(final String subject, final Set grants) { return new AgentMcpExecutionContext("internal-" + subject, subject, "rule", 1, Set.of("order_status"), grants); } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java new file mode 100644 index 000000000000..824174538352 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java @@ -0,0 +1,195 @@ +/* + * 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.plugin.agent.gateway.protocol; + +import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; +import org.apache.shenyu.common.metrics.AgentAdmissionMetrics; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import java.util.Objects; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; +import reactor.test.StepVerifier; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AgentResourceAdmissionTest { + + private AgentResourceAdmission controller; + + @AfterEach + void closeController() { + if (Objects.nonNull(controller)) { + controller.close(); + } + } + + @Test + void rejectQueueOverflowWithExplicitOverload() throws Exception { + controller = new AgentResourceAdmission(new AgentGatewayAdmissionConfig(1, 1, 1, 1, 1, 1)); + Sinks.Empty first = Sinks.empty(); + ExecutorService executor = Executors.newFixedThreadPool(3); + try { + final Future active = executor.submit(() -> StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(30), first.asMono())).expectComplete().verify()); + await(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + final Future queued = executor.submit(() -> StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(30), Mono.empty())) + .expectComplete().verify()); + awaitQueued(controller, 1); + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(30), Mono.empty())) + .expectErrorMatches(error -> error instanceof AgentResourceAdmission.AgentAdmissionException + || error instanceof java.util.concurrent.TimeoutException).verify(); + first.tryEmitEmpty(); + active.get(5, TimeUnit.SECONDS); + queued.get(5, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + assertEquals(1, controller.snapshot().get(0).rejected()); + } + + @Test + void rejectQueuedWaiterAfterDeadline() throws Exception { + controller = new AgentResourceAdmission(new AgentGatewayAdmissionConfig(1, 1, 1, 1, 1, 1)); + Sinks.Empty active = Sinks.empty(); + StepVerifier.create(controller.withLocal(Instant.now().plusMillis(100), active.asMono())).expectComplete().verifyLater(); + await(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + AtomicInteger calls = new AtomicInteger(); + StepVerifier.create(controller.withLocal(Instant.now().plusMillis(100), Mono.fromCallable(calls::incrementAndGet))) + .expectErrorMatches(error -> error instanceof AgentResourceAdmission.AgentAdmissionException + && ((AgentResourceAdmission.AgentAdmissionException) error).isTimeout()).verify(Duration.ofSeconds(2)); + assertEquals(0, calls.get()); + active.tryEmitEmpty(); + } + + @Test + void cancellationRemovesQueuedWaiterWithoutReleasingActivePermit() throws Exception { + controller = new AgentResourceAdmission(new AgentGatewayAdmissionConfig(1, 1, 1, 1, 1, 1)); + Sinks.Empty active = Sinks.empty(); + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(5), active.asMono())).expectComplete().verifyLater(); + await(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + reactor.core.Disposable queued = controller.withLocal(Instant.now().plusSeconds(5), Mono.just("unused")) + .subscribe(); + awaitQueued(controller, 1); + queued.dispose(); + awaitQueued(controller, 0); + assertEquals(1, controller.snapshot().get(0).inFlight()); + active.tryEmitEmpty(); + await(controller, AgentAdmissionMetrics.Scope.GLOBAL, 0); + } + + @Test + void closeRejectsQueuedWaiterWithoutExecutingAction() throws Exception { + controller = new AgentResourceAdmission(new AgentGatewayAdmissionConfig(1, 1, 1, 1, 1, 1)); + Sinks.Empty active = Sinks.empty(); + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(5), active.asMono())).expectComplete().verifyLater(); + await(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + AtomicInteger calls = new AtomicInteger(); + java.util.concurrent.atomic.AtomicReference failure = new java.util.concurrent.atomic.AtomicReference<>(); + controller.withLocal(Instant.now().plusSeconds(5), Mono.fromCallable(calls::incrementAndGet)) + .subscribe(value -> { }, failure::set); + awaitQueued(controller, 1); + controller.close(); + org.awaitility.Awaitility.await().atMost(Duration.ofSeconds(2)).until(() -> Objects.nonNull(failure.get())); + assertTrue(failure.get() instanceof AgentResourceAdmission.AgentAdmissionException); + assertEquals(0, calls.get()); + assertEquals(0, controller.snapshot().get(0).queued()); + active.tryEmitEmpty(); + } + + @Test + void isolateSlowRemoteServerFromIndependentTarget() { + controller = new AgentResourceAdmission(new AgentGatewayAdmissionConfig(4, 4, 4, 4, 1, 1)); + Sinks.Empty slow = Sinks.empty(); + StepVerifier.create(controller.withRemote("slow", Instant.now().plusSeconds(2), slow.asMono())).expectComplete().verifyLater(); + StepVerifier.create(controller.withRemote("fast", Instant.now().plusSeconds(2), Mono.just("ok"))) + .expectNext("ok").verifyComplete(); + slow.tryEmitEmpty(); + } + + @Test + void releasePermitsExactlyOnceOnTerminalPaths() throws Exception { + controller = new AgentResourceAdmission(new AgentGatewayAdmissionConfig(1, 1, 1, 1, 1, 1)); + Sinks.Empty release = Sinks.empty(); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future first = executor.submit(() -> StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), release.asMono())).expectComplete().verify()); + await(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + release.tryEmitEmpty(); + first.get(5, TimeUnit.SECONDS); + AtomicInteger calls = new AtomicInteger(); + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), Mono.fromCallable(calls::incrementAndGet))).expectNext(1).verifyComplete(); + assertEquals(1, calls.get()); + } finally { + executor.shutdownNow(); + } + } + + @Test + void replacingControllerRetiresOldMetricsAndKeepsNewLimits() { + AgentMcpResourceAdmission.ResourceAdmissionController first = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 1, 1, 1, 1, 1)); + AgentMcpResourceAdmission.ResourceAdmissionController second = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(2, 1, 1, 1, 1, 1)); + try { + first.replace(second); + List snapshots = AgentAdmissionMetrics.snapshots(); + assertEquals(2, snapshots.size()); + assertEquals(2, snapshots.stream().filter(state -> state.scope() == AgentAdmissionMetrics.Scope.GLOBAL) + .mapToInt(AgentAdmissionMetrics.Snapshot::inFlightLimit).sum()); + } finally { + first.close(); + } + } + + @Test + void rejectInvalidConfigurationBeforeControllerCreation() { + assertThrows(IllegalArgumentException.class, () -> new AgentGatewayAdmissionConfig(0, 0, 1, 0, 1, 0)); + assertThrows(IllegalArgumentException.class, () -> new AgentGatewayAdmissionConfig(1, 0, 1, 0, 33, 0)); + } + + private static void await(final AgentResourceAdmission controller, final AgentAdmissionMetrics.Scope scope, final int expected) throws InterruptedException { + for (int i = 0; i < 200; i++) { + if (controller.snapshot().stream().anyMatch(state -> state.scope() == scope && state.inFlight() >= expected)) { + return; + } + TimeUnit.MILLISECONDS.sleep(10); + } + assertTrue(false, "admission permit was not acquired"); + } + + private static void awaitQueued(final AgentResourceAdmission controller, final int expected) throws InterruptedException { + for (int i = 0; i < 200; i++) { + if (controller.snapshot().stream().mapToInt(AgentAdmissionMetrics.Snapshot::queued).max().orElse(0) == expected) { + return; + } + TimeUnit.MILLISECONDS.sleep(10); + } + assertTrue(false, "admission waiter was not queued"); + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalogTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalogTest.java index d8db97a88908..7545f7a41f0d 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalogTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalogTest.java @@ -107,6 +107,22 @@ void newerFencedEventClearsOnlyTheSupersededFailureDiagnostic() throws Exception } } + @Test + void validConfigurationReplacesAdmissionLimitsAfterCredentialResolution() throws InterruptedException { + ManagedRemoteMcpCatalog catalog = new ManagedRemoteMcpCatalog(Set.of(URI.create("https://192.0.2.10:443/mcp")), Set.of(), target -> + new RemoteServerBinding.Credential(target, "fixed-test-token")); + try { + assertEquals(128, catalog.admissionConfig().globalInFlight()); + catalog.accept(event(true, configWithAdmission(16, 8, 4))); + await(() -> catalog.diagnosticsState().lifecycle().currentVersion() > 1L); + assertEquals(16, catalog.admissionConfig().globalInFlight()); + assertEquals(8, catalog.admissionConfig().remoteInFlight()); + assertEquals(4, catalog.admissionConfig().remoteQueued()); + } finally { + catalog.close(); + } + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void withdrawnDuringSuccessfulCredentialResolutionDoesNotStartRemoteHandshake(final boolean emptyConfiguration) throws Exception { @@ -286,6 +302,12 @@ private static String config() { + "\"credentialRef\":\"service/orders\",\"credentialVersion\":\"v1\"}]}}"; } + private static String configWithAdmission(final int global, final int remoteInFlight, final int remoteQueued) { + return "{\"aggregation\":{\"revision\":\"admission\",\"servers\":[]},\"admission\":{" + + "\"globalInFlight\":" + global + ",\"globalQueued\":32,\"localInFlight\":16," + + "\"localQueued\":8,\"remoteInFlight\":" + remoteInFlight + ",\"remoteQueued\":" + remoteQueued + "}}"; + } + private static void await(final BooleanSupplier condition) throws InterruptedException { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (!condition.getAsBoolean() && System.nanoTime() < deadline) { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientAdmissionTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientAdmissionTest.java new file mode 100644 index 000000000000..9af5be80563e --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientAdmissionTest.java @@ -0,0 +1,193 @@ +/* + * 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.plugin.agent.gateway.remote; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sun.net.httpserver.HttpServer; +import io.modelcontextprotocol.spec.McpSchema; +import reactor.core.publisher.Mono; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; +import org.junit.jupiter.api.Test; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.List; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class RequestScopedMcpClientAdmissionTest { + + @Test + void slowFailingAndLargeUpstreamsRemainBoundedAndIndependent() throws Exception { + try (Fixture slowFixture = new Fixture(); Fixture fastFixture = new Fixture()) { + RequestScopedMcpClient slow = slowFixture.client("slow"); + RequestScopedMcpClient fast = fastFixture.client("fast"); + slow.initialize().block(Duration.ofSeconds(5)); + fast.initialize().block(Duration.ofSeconds(5)); + AgentMcpResourceAdmission.ResourceAdmissionController admission = + AgentMcpResourceAdmission.create(new org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig( + 4, 4, 4, 4, 1, 2)); + try { + final var slowCall = admission.withRemote("slow", Instant.now().plusSeconds(5), + call(slow, "slow", 700)).toFuture(); + await().atMost(Duration.ofSeconds(2)).until(() -> slowFixture.active.get() == 1); + assertEquals("fast", call(fast, "fast", 0) + .block(Duration.ofSeconds(5)).path("structuredContent").path("token").textValue()); + assertEquals(1, slowFixture.active.get()); + + List failures = new CopyOnWriteArrayList<>(); + admission.withRemote("fast", Instant.now().plusSeconds(5), call(fast, "upstream-failure", 0)) + .subscribe(value -> { }, failures::add); + await().atMost(Duration.ofSeconds(2)).until(() -> failures.size() == 1); + await().atMost(Duration.ofSeconds(2)).until(() -> fastFixture.active.get() == 0); + + List oversize = new CopyOnWriteArrayList<>(); + admission.withRemote("fast", Instant.now().plusSeconds(5), call(fast, "large", 0)) + .subscribe(value -> { }, oversize::add); + await().atMost(Duration.ofSeconds(2)).until(() -> oversize.size() == 1); + assertEquals(1, fastFixture.oversizeResponses.get()); + await().atMost(Duration.ofSeconds(2)).until(() -> fastFixture.active.get() == 0); + + assertEquals("slow", slowCall.get(5, TimeUnit.SECONDS) + .path("structuredContent").path("token").textValue()); + assertEquals(0, slowFixture.active.get()); + } finally { + admission.close(); + slow.closeGracefully().onErrorResume(ignored -> Mono.empty()).block(Duration.ofSeconds(5)); + fast.closeGracefully().onErrorResume(ignored -> Mono.empty()).block(Duration.ofSeconds(5)); + } + } + } + + private static Mono call(final RequestScopedMcpClient client, final String token, final int delay) { + return client.callRaw(new McpSchema.CallToolRequest("lookup", Map.of("token", token, "delay", delay))); + } + + private static final class Fixture implements AutoCloseable { + + private final ObjectMapper json = new ObjectMapper(); + + private final HttpServer server; + + private final ExecutorService executor = Executors.newFixedThreadPool(8); + + private final AtomicInteger active = new AtomicInteger(); + + private final AtomicInteger oversizeResponses = new AtomicInteger(); + + private Fixture() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.setExecutor(executor); + server.createContext("/ready", exchange -> { + exchange.sendResponseHeaders(204, -1); + exchange.close(); + }); + server.createContext("/mcp", exchange -> { + try { + ObjectNode request = (ObjectNode) json.readTree(exchange.getRequestBody()); + String method = request.path("method").textValue(); + if ("notifications/initialized".equals(method)) { + exchange.sendResponseHeaders(202, -1); + return; + } + ObjectNode result = json.createObjectNode(); + if ("initialize".equals(method)) { + exchange.getResponseHeaders().set("MCP-Session-Id", "unit-session"); + result.put("protocolVersion", "2025-06-18"); + result.putObject("capabilities").putObject("tools"); + result.putObject("serverInfo").put("name", "unit").put("version", "1"); + } else if ("tools/list".equals(method)) { + var tool = result.putArray("tools").addObject().put("name", "lookup").put("description", "lookup"); + tool.putObject("inputSchema").put("type", "object"); + } else { + String token = request.path("params").path("arguments").path("token").textValue(); + int delay = request.path("params").path("arguments").path("delay").asInt(); + int slot = active.incrementAndGet(); + try { + if ("upstream-failure".equals(token)) { + exchange.sendResponseHeaders(503, -1); + return; + } + if ("large".equals(token)) { + result.putArray("content").addObject().put("type", "text").put("text", "x".repeat(16384)); + } else { + if (delay > 0) { + Thread.sleep(delay); + } + result.putArray("content").addObject().put("type", "text").put("text", "native"); + result.putObject("structuredContent").put("token", token); + } + } finally { + active.decrementAndGet(); + if (slot == 0) { + throw new IllegalStateException("Invalid active slot"); + } + } + } + ObjectNode envelope = json.createObjectNode().put("jsonrpc", "2.0"); + envelope.set("id", request.get("id")); + envelope.set("result", result); + byte[] response = envelope.toString().getBytes(StandardCharsets.UTF_8); + if (response.length > 8192) { + oversizeResponses.incrementAndGet(); + } + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, response.length); + exchange.getResponseBody().write(response); + } catch (Exception expected) { + // Cancelled connections may surface here and are intentionally tolerated. + } finally { + exchange.close(); + } + }); + server.start(); + HttpClient warmup = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build(); + HttpRequest ready = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/ready")) + .timeout(Duration.ofSeconds(30)).GET().build(); + assertEquals(204, warmup.send(ready, HttpResponse.BodyHandlers.discarding()).statusCode()); + } + + private RequestScopedMcpClient client(final String name) { + URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/mcp"); + RemoteServerBinding.Config target = new RemoteServerBinding.Config(name, uri, "service/" + name, "v1"); + return new RequestScopedMcpClient(RemoteServerBinding.resolve(target, Set.of(uri), + ignored -> new RemoteServerBinding.Credential(target, "fixed-test-token")), ignored -> { }); + } + + @Override + public void close() { + server.stop(0); + executor.shutdownNow(); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java index 5eac37ce4780..c47d7d68174d 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java @@ -141,6 +141,12 @@ public AiProxyEngine(final AiProxyProtocolFactory protocols, final AiProxyProvid this(protocols, providers, routeResolver, transport, new AiProxyRetryProperties(3, 1, retryBackoff)); } + public AiProxyEngine(final AiProxyProtocolFactory protocols, final AiProxyProviderFactory providers, + final AiProtocolRouteResolver routeResolver, final AiProxyTransport transport, + final Duration retryBackoff, final AiCallObserver observer) { + this(protocols, providers, routeResolver, transport, new AiProxyRetryProperties(3, 1, retryBackoff), observer); + } + public AiProxyEngine(final AiProxyProtocolFactory protocols, final AiProxyProviderFactory providers, final AiProtocolConverterFactory converters, final AiProxyTransport transport, final Duration retryBackoff, final AiCallObserver observer) { diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollector.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollector.java new file mode 100644 index 000000000000..03281af24dde --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollector.java @@ -0,0 +1,72 @@ +/* + * 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.plugin.metrics.prometheus; + +import io.prometheus.client.Collector; +import io.prometheus.client.GaugeMetricFamily; +import org.apache.shenyu.common.metrics.AgentAdmissionMetrics; + +import java.util.List; +import java.util.stream.Collectors; + +/** On-scrape admission state using bounded aggregate labels. */ +public final class AgentAdmissionMetricsCollector extends Collector implements Collector.Describable { + + @Override + public List collect() { + return samples(AgentAdmissionMetrics.snapshots()); + } + + @Override + public List describe() { + return samples(List.of()); + } + + private List samples(final List states) { + GaugeMetricFamily inFlight = new GaugeMetricFamily("shenyu_agent_admission_inflight", + "Admitted work by fixed scope", List.of("scope")); + GaugeMetricFamily queued = new GaugeMetricFamily("shenyu_agent_admission_queued", + "Queued work by fixed scope", List.of("scope")); + GaugeMetricFamily inFlightLimit = new GaugeMetricFamily("shenyu_agent_admission_inflight_limit", + "Configured in-flight limit by fixed scope", List.of("scope")); + GaugeMetricFamily queueLimit = new GaugeMetricFamily("shenyu_agent_admission_queue_limit", + "Configured queue limit by fixed scope", List.of("scope")); + GaugeMetricFamily rejected = new GaugeMetricFamily("shenyu_agent_admission_rejections_total", + "Explicit admission rejections by fixed scope", List.of("scope")); + for (AgentAdmissionMetrics.Scope scope : AgentAdmissionMetrics.Scope.values()) { + List scoped = states.stream() + .filter(state -> state.scope() == scope).collect(Collectors.toList()); + inFlight.addMetric(label(scope), sum(scoped, AgentAdmissionMetrics.Snapshot::inFlight)); + queued.addMetric(label(scope), sum(scoped, AgentAdmissionMetrics.Snapshot::queued)); + inFlightLimit.addMetric(label(scope), sum(scoped, AgentAdmissionMetrics.Snapshot::inFlightLimit)); + queueLimit.addMetric(label(scope), sum(scoped, AgentAdmissionMetrics.Snapshot::queueLimit)); + rejected.addMetric(label(scope), states.stream().filter(state -> state.scope() == scope) + .mapToLong(AgentAdmissionMetrics.Snapshot::rejected).sum()); + } + return List.of(inFlight, queued, inFlightLimit, queueLimit, rejected); + } + + private long sum(final List states, + final java.util.function.ToIntFunction value) { + return states.stream().mapToLong(value::applyAsInt).sum(); + } + + private List label(final AgentAdmissionMetrics.Scope scope) { + return List.of(scope.name().toLowerCase(java.util.Locale.ROOT)); + } +} diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java index fbe9bf7db1ba..45e8bc91c968 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java @@ -103,6 +103,7 @@ private void register(final MetricsConfig config) { } new LoggingQueueMetricsCollector().register(); new AgentCatalogMetricsCollector().register(); + new AgentAdmissionMetricsCollector().register(); String jvmEnabled = String.valueOf(config.getProps().getProperty("jvm_enabled")); if (StringUtils.isNotEmpty(jvmEnabled)) { boolean enabled = Boolean.parseBoolean(jvmEnabled); diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollectorTest.java b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollectorTest.java new file mode 100644 index 000000000000..66865b8f4e5f --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollectorTest.java @@ -0,0 +1,38 @@ +/* + * 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.plugin.metrics.prometheus; + +import org.apache.shenyu.common.metrics.AgentAdmissionMetrics; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AgentAdmissionMetricsCollectorTest { + + @Test + void shouldAggregateFixedScopesWithoutIdentityLabels() { + AgentAdmissionMetrics.Snapshot snapshot = new AgentAdmissionMetrics.Snapshot( + AgentAdmissionMetrics.Scope.REMOTE, 2, 3, 4, 5, 6); + List names = new AgentAdmissionMetricsCollector().collect().stream() + .map(family -> family.samples.stream().map(sample -> sample.name).toList()).flatMap(List::stream).toList(); + assertEquals(15, names.size()); + assertEquals(5, names.stream().filter(name -> name.startsWith("shenyu_agent_admission_")).distinct().count()); + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java index b03a44e4aa1a..9038296b2dcf 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java @@ -29,6 +29,7 @@ import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpHttpHandler; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpRemoteCatalog; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpSecurityResolver; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolProvider; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry; @@ -67,7 +68,7 @@ public class AgentGatewayPluginConfiguration { * Create a plugin with an optional managed remote catalog. * @param providers local providers * @param resolvers trusted identity adapters - * @param catalogs optional, unambiguous managed remote catalog + * @param managedCatalogs optional, unambiguous managed remote catalog * @param tracers optional tracing bridge * @param terminalObservers optional application-owned terminal event sink * @param aiObservers optional application-owned AI attempt and terminal sink @@ -78,7 +79,7 @@ public class AgentGatewayPluginConfiguration { */ @Bean public ShenyuPlugin agentGatewayPlugin(final ObjectProvider providers, final ObjectProvider resolvers, - final ObjectProvider catalogs, final ObjectProvider tracers, + final ObjectProvider managedCatalogs, final ObjectProvider tracers, final ObjectProvider terminalObservers, final ObjectProvider aiObservers, final ObjectProvider auditors, @@ -103,7 +104,7 @@ public ShenyuPlugin agentGatewayPlugin(final ObjectProvider p && !beanFactory.containsBean(JWT_SECURITY_RESOLVER_BEAN_NAME)) { throw new IllegalStateException("Enabled MCP JWT identity requires the optional JWT adapter dependencies"); } - return createPlugin(providers, authorities, catalogs.getIfAvailable(), tracer, + return createPlugin(providers, authorities, managedCatalogs.getIfAvailable(), tracer, AgentInvocationAuditBridge.mcp(terminalObservers.getIfAvailable(), auditors.getIfAvailable()), AgentInvocationAuditBridge.ai(aiObservers.getIfAvailable(), auditors.getIfAvailable()), environment.getProperty("shenyu.plugins.agent.gateway.security.llm.enabled", Boolean.class, false)); @@ -119,7 +120,8 @@ private ShenyuPlugin createPlugin(final ObjectProvider provid throw new IllegalStateException("Enabled LLM identity mapping requires an authoritative security resolver"); } return new AgentGatewayPlugin(new AgentMcpHttpHandler(new AgentMcpDispatcher(registry, "shenyu-agent-gateway", - AgentGatewayConstants.MCP_SERVER_VERSION, catalog), resolver, tracer, terminalObserver), + AgentGatewayConstants.MCP_SERVER_VERSION, catalog, + java.util.Objects.isNull(catalog) ? AgentMcpResourceAdmission.NOOP : catalog.admission()), resolver, tracer, terminalObserver), llmIdentityEnabled ? resolver : null, aiObserver); } From 2324714aad1189ef1a9c39ad91fab2eef1f1b1e9 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Sun, 25 Oct 2026 19:56:31 +0800 Subject: [PATCH 06/36] ci: re-run agent gateway checks From b015555a62ebdd5219f1ab38ab7b34aba5f95b3b Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 26 Oct 2026 07:28:46 +0800 Subject: [PATCH 07/36] test(agent-gateway): locate migration null fixture structurally --- .github/scripts/test-agent-gateway-migrations.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/scripts/test-agent-gateway-migrations.py b/.github/scripts/test-agent-gateway-migrations.py index e8b53e603a75..68770c97c4ac 100644 --- a/.github/scripts/test-agent-gateway-migrations.py +++ b/.github/scripts/test-agent-gateway-migrations.py @@ -17,6 +17,7 @@ import importlib.util from pathlib import Path +import re import sys import tempfile import unittest @@ -84,7 +85,8 @@ def test_null_keyword_case_is_ignored(self): self.assertEqual(24, CHECK.check_pair(self.schema, self.migration.replace("NULL", "null"))) def test_quoted_null_is_not_a_null_literal(self): - changed = self.migration.replace("'68', NULL, 198", "'68', 'NULL', 198") + changed, replacements = re.subn(r"('68', )NULL(, \d+)", r"\1'NULL'\2", self.migration, count=1) + self.assertEqual(1, replacements, "fixture drifted: no '68', NULL, row found") with self.assertRaisesRegex(ValueError, "mismatch"): CHECK.check_pair(self.schema, changed) From 423278e10f9982c1dc6ecc588ebdaa16ae698344 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 26 Oct 2026 11:05:34 +0800 Subject: [PATCH 08/36] test(agent-gateway): harden migration null fixture --- .github/scripts/test-agent-gateway-migrations.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/scripts/test-agent-gateway-migrations.py b/.github/scripts/test-agent-gateway-migrations.py index e8b53e603a75..246352e542de 100644 --- a/.github/scripts/test-agent-gateway-migrations.py +++ b/.github/scripts/test-agent-gateway-migrations.py @@ -17,6 +17,7 @@ import importlib.util from pathlib import Path +import re import sys import tempfile import unittest @@ -84,7 +85,17 @@ def test_null_keyword_case_is_ignored(self): self.assertEqual(24, CHECK.check_pair(self.schema, self.migration.replace("NULL", "null"))) def test_quoted_null_is_not_a_null_literal(self): - changed = self.migration.replace("'68', NULL, 198", "'68', 'NULL', 198") + changed, replacements = re.subn( + r"('68', )NULL(, \d+)", + r"\1'NULL'\2", + self.migration, + count=1, + ) + self.assertEqual( + 1, + replacements, + "fixture drifted: no '68', NULL, row found", + ) with self.assertRaisesRegex(ValueError, "mismatch"): CHECK.check_pair(self.schema, changed) From 4736952eba12953cd6f781a7b07ac542e20be2eb Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 26 Oct 2026 11:05:35 +0800 Subject: [PATCH 09/36] test(agent-gateway): harden migration null fixture --- .github/scripts/test-agent-gateway-migrations.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/scripts/test-agent-gateway-migrations.py b/.github/scripts/test-agent-gateway-migrations.py index e8b53e603a75..246352e542de 100644 --- a/.github/scripts/test-agent-gateway-migrations.py +++ b/.github/scripts/test-agent-gateway-migrations.py @@ -17,6 +17,7 @@ import importlib.util from pathlib import Path +import re import sys import tempfile import unittest @@ -84,7 +85,17 @@ def test_null_keyword_case_is_ignored(self): self.assertEqual(24, CHECK.check_pair(self.schema, self.migration.replace("NULL", "null"))) def test_quoted_null_is_not_a_null_literal(self): - changed = self.migration.replace("'68', NULL, 198", "'68', 'NULL', 198") + changed, replacements = re.subn( + r"('68', )NULL(, \d+)", + r"\1'NULL'\2", + self.migration, + count=1, + ) + self.assertEqual( + 1, + replacements, + "fixture drifted: no '68', NULL, row found", + ) with self.assertRaisesRegex(ValueError, "mismatch"): CHECK.check_pair(self.schema, changed) From 1664140420e3c9a5031981e650ffe24fac900f5a Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 26 Oct 2026 13:52:49 +0800 Subject: [PATCH 10/36] fix(agent-gateway): address observation and ordering review --- RELEASE-NOTES.md | 7 ++++++ db/upgrade/2.7.2-agent-gateway-order.sql | 1 + docs/agent-gateway-governance-order.md | 12 ++++++---- .../common/metrics/AiRequestObservation.java | 2 +- .../protocol/AgentMcpTerminalObservation.java | 5 ++++- .../AgentMcpTerminalObservationTest.java | 11 ++++++++++ .../ai/proxy/enhanced/AiProxyPlugin.java | 1 - .../service/AiObservationSupport.java | 12 ++++++---- .../proxy/enhanced/service/AiProxyEngine.java | 9 ++++---- .../ai/proxy/enhanced/AiProxyPluginTest.java | 11 ++++++++++ .../AiProxyEngineOrchestrationTest.java | 3 ++- .../enhanced/service/AiProxyEngineTest.java | 3 +-- .../AgentGatewayPluginOrderingTest.java | 22 +++++++++---------- 13 files changed, 70 insertions(+), 29 deletions(-) diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index 0b7089135bae..ff9100424883 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -38,6 +38,13 @@ ### Behavior Changes +- Agent Gateway's default order changes from 198 to 169. Matched MCP traffic now + terminates in Agent Gateway before `mcpServer`, Kafka/ElasticSearch logging, + sensitive-word filtering, Prompt, Token Limiter, RocketMQ logging and AI Proxy. + Deployments that previously relied on the later `mcpServer` handling an overlapping + path must review their selectors and explicit plugin orders; the migration changes + only old Agent Gateway sort values and does not rewrite custom orders. + - In `DividePlugin`, `headerMaxSize` now accounts for the complete HTTP header field section: header names, field values, line framing (`: ` and CRLF), and section-terminating CRLF. Previously only header values were counted. Existing diff --git a/db/upgrade/2.7.2-agent-gateway-order.sql b/db/upgrade/2.7.2-agent-gateway-order.sql index 8c53fafb4460..a8c1622fabd0 100644 --- a/db/upgrade/2.7.2-agent-gateway-order.sql +++ b/db/upgrade/2.7.2-agent-gateway-order.sql @@ -26,6 +26,7 @@ -- Run both UPDATEs in one operator-managed transaction, verify, then commit. -- Database writes alone do not refresh Admin/gateway caches: resynchronize -- all affected namespaces before routing traffic through the updated gateway. +-- Syntax verified against MySQL, PostgreSQL and Oracle upgrade paths. UPDATE plugin SET sort = 169 WHERE name = 'agentGateway' AND sort = 198; diff --git a/docs/agent-gateway-governance-order.md b/docs/agent-gateway-governance-order.md index e1532e4c0af5..df0b8b53a8ab 100644 --- a/docs/agent-gateway-governance-order.md +++ b/docs/agent-gateway-governance-order.md @@ -31,10 +31,14 @@ existing AI chain. AG must not read, buffer or subscribe to the LLM request body body consumption remains with the existing AI plugins. A matched MCP request terminates in AG and does not enter Prompt, the LLM Token Limiter or AI Proxy. Unmatched/disabled AG continues the original chain. Moving the terminal entry -earlier also bypasses later plugins for matched MCP, including RocketMQ logging -and sensitiveWord. Do not assume those plugins still observe or filter MCP; -review any deployment relying on their old position. Authentication plugins -must still be enabled and match the intended paths; order alone is not authentication. +earlier also bypasses later plugins for matched MCP, including `mcpServer` and +`loggingKafka` (180), `sensitiveWord` and `loggingElasticSearch` (190), the LLM +Token Limiter (171), RocketMQ logging (170), Prompt and AI Proxy. In particular, +this flips the previous overlap with `mcpServer`: AG at 198 formerly ran after +it, while AG at 169 now runs first and terminates the matched MCP path. Do not +assume those plugins still observe, filter or route MCP; review any deployment +relying on their old position. Authentication plugins must still be enabled and +match the intended paths; order alone is not authentication. ## Effective order is configuration, not only the enum diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java index f9954343969f..9a2a16f99fce 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AiRequestObservation.java @@ -131,7 +131,7 @@ public void finish(final SignalType signal, final Integer httpStatus) { return; } completed = true; - attemptEvent = Objects.isNull(active) ? null : active.freeze(signal, AiCallOutcome.ERROR); + attemptEvent = Objects.isNull(active) ? null : active.freeze(signal, terminalOutcome(active.status, failure)); AiCallOutcome error = Objects.isNull(failure) && signal == SignalType.ON_ERROR ? AiCallOutcome.ERROR : failure; AiCallOutcome outcome = signal == SignalType.CANCEL ? AiCallOutcome.CANCELLED : terminalOutcome(httpStatus, error); terminalEvent = new AiTerminalEvent(context, outcome, httpStatus, elapsed(started), attempts, usage); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java index 2d5c334a1d5e..eb627b4270ab 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservation.java @@ -57,6 +57,8 @@ final class AgentMcpTerminalObservation { private Outcome outcome = Outcome.SERVER_ERROR; + private boolean failureClassified; + private boolean completed; AgentMcpTerminalObservation(final AgentMcpTerminalObserver observer, final AgentTrafficContext traffic, final long configurationVersion) { @@ -93,9 +95,10 @@ synchronized void response(final boolean toolError) { } synchronized void failure(final Throwable error, final Integer transportStatus) { - if (completed) { + if (completed || failureClassified) { return; } + failureClassified = true; Integer status = transportStatus; if (error instanceof AgentMcpProtocolException) { status = ((AgentMcpProtocolException) error).getHttpStatus(); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java index ef3c93587876..93d72a178f68 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java @@ -226,6 +226,17 @@ void explicit504IsClassifiedAsTimeout() { observer.only(Outcome.TIMEOUT); } + @Test + void failedRecoveryWriteDoesNotOverwriteTheOriginalClassification() { + Recording observer = new Recording(); + MockServerWebExchange exchange = exchange("tools/call"); + exchange.getResponse().setWriteHandler(buffers -> buffers.doOnNext(DataBufferUtils::release).then(Mono.error(new IllegalStateException("write")))); + StepVerifier.create(handler(Mono.error(new AgentMcpProtocolException(403, -32001, "denied", null, null)), identity(), observer) + .handle(exchange, config("json", 30000), traffic, 1)).expectError().verify(); + AgentMcpTerminalEvent event = observer.only(Outcome.REJECTED); + assertEquals(403, event.getHttpStatus()); + } + @ParameterizedTest @ValueSource(strings = {"json", "sse"}) void cancellingAStalledWriteIsNotSuccess(final String mode) { diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java index ef4953fa51db..b9678f706a1c 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java @@ -98,7 +98,6 @@ protected Mono doExecute(final ServerWebExchange exchange, final ShenyuPlu return executeRequest(exchange, selector) .doOnError(error -> observation.failure(AiObservationSupport.outcome(error))) .onErrorResume(error -> handleFailure(exchange.getResponse(), error)) - .doOnError(observation::error) .doFinally(signal -> { if (Objects.isNull(inherited)) { HttpStatusCode status = exchange.getResponse().getStatusCode(); diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiObservationSupport.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiObservationSupport.java index 5ffe3bc0bb8a..c1ded6d276e2 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiObservationSupport.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiObservationSupport.java @@ -18,13 +18,13 @@ package org.apache.shenyu.plugin.ai.proxy.enhanced.service; import org.apache.shenyu.common.dto.AgentRequestContext; -import org.apache.shenyu.common.exception.ShenyuException; import org.apache.shenyu.common.metrics.AiCallOutcome; import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiProxyException; import org.apache.shenyu.plugin.ai.proxy.enhanced.transport.AiTransportException; import org.springframework.core.io.buffer.DataBufferLimitException; import reactor.util.context.ContextView; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeoutException; @@ -54,8 +54,12 @@ public static AgentRequestContext context(final ContextView view, final String s * @return bounded classification */ public static AiCallOutcome outcome(final Throwable error) { - if (error instanceof TimeoutException) { - return AiCallOutcome.TIMEOUT; + Throwable cause = error; + for (int depth = 0; depth < 16 && Objects.nonNull(cause); depth++) { + if (cause instanceof TimeoutException) { + return AiCallOutcome.TIMEOUT; + } + cause = cause.getCause(); } if (error instanceof AiTransportException transport) { return switch (transport.getKind()) { @@ -63,7 +67,7 @@ public static AiCallOutcome outcome(final Throwable error) { default -> AiCallOutcome.ERROR; }; } - if (error instanceof ShenyuException || error instanceof DataBufferLimitException + if (error instanceof DataBufferLimitException || error instanceof AiProxyException proxy && proxy.getKind() == AiProxyException.Kind.REQUEST) { return AiCallOutcome.REJECTED; } diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java index 277a4c782b46..d8ba968c8687 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java @@ -244,16 +244,16 @@ private Mono consumeResponse( private PreparedExchange prepare(final String requestBody, final AiCommonConfig config) { if (Objects.isNull(requestBody) || requestBody.isBlank()) { - throw new ShenyuException("AI request body must not be empty"); + throw new AiProxyException(AiProxyException.Kind.REQUEST, "AI request body must not be empty", null); } final JsonNode root; try { root = OBJECT_MAPPER.readTree(requestBody); } catch (JsonProcessingException error) { - throw new ShenyuException("AI request body must be valid JSON", error); + throw new AiProxyException(AiProxyException.Kind.REQUEST, "AI request body must be valid JSON", error); } if (!root.isObject()) { - throw new ShenyuException("AI request body must be a JSON object"); + throw new AiProxyException(AiProxyException.Kind.REQUEST, "AI request body must be a JSON object", null); } ObjectNode payload = (ObjectNode) root; String upstreamBody = requestBody; @@ -264,7 +264,8 @@ private PreparedExchange prepare(final String requestBody, final AiCommonConfig AiProxyProtocol protocol = Objects.isNull(config.getProtocol()) || config.getProtocol().isBlank() ? aiProxyProtocolFactory.detect(payload) : aiProxyProtocolFactory.getProtocol(config.getProtocol()); if (!protocol.matches(payload)) { - throw new ShenyuException("Request body does not match AI protocol: " + protocol.name()); + throw new AiProxyException(AiProxyException.Kind.REQUEST, + "Request body does not match AI protocol: " + protocol.name(), null); } ShenyuAiRequest decoded = applyModelOverride(protocol.decodeRequest(upstreamBody, payload), protocol, config); AiProxyProvider provider = aiProxyProviderFactory.getProvider( diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPluginTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPluginTest.java index bc1eea67bd4e..ba3f1c2b8e4e 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPluginTest.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPluginTest.java @@ -26,6 +26,7 @@ import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.dto.convert.rule.AiProxyHandle; import org.apache.shenyu.common.enums.PluginEnum; +import org.apache.shenyu.common.exception.ShenyuException; import org.apache.shenyu.common.metrics.AiAttemptEvent; import org.apache.shenyu.common.metrics.AiCallObserver; import org.apache.shenyu.common.metrics.AiCallOutcome; @@ -65,6 +66,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.TimeoutException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -268,6 +270,15 @@ void mapsConnectionFailureBeforeCommitmentToBadGateway() { assertEquals(4, requests.size()); } + @Test + void wrappedTimeoutKeepsTimeoutClassificationBeforeRecovery() { + final List events = new ArrayList<>(); + final AiProxyPlugin plugin = plugin(request -> Mono.error(new ShenyuException(new TimeoutException("upstream deadline"))), events::add); + StepVerifier.create(execute(plugin)).verifyComplete(); + assertEquals(HttpStatus.BAD_REQUEST, exchange.getResponse().getStatusCode()); + assertEquals(AiCallOutcome.TIMEOUT, events.get(0).outcome()); + } + @Test void filtersHopHeadersAndPreservesEndToEndHeaders() { AiProxyPlugin plugin = plugin(request -> Mono.just(new AiUpstreamResponse(200, Map.of("Connection", List.of("X-Hop"), diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java index fb610e0729d8..48207aaed0fa 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java @@ -414,7 +414,8 @@ void validationFailuresDoNotExecuteOrFallBack() { return Mono.error(networkFailure()); }); StepVerifier.create(engine.execute("invalid", config(true, "main"), Optional.of(config(true, "fallback")), response -> response.getBody().then())) - .expectError(ShenyuException.class).verify(); + .expectErrorMatches(error -> error instanceof AiProxyException request + && request.getKind() == AiProxyException.Kind.REQUEST).verify(); assertEquals(0, calls.get()); } diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineTest.java index d908fa52368e..fb6c95653e1c 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineTest.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineTest.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.shenyu.common.exception.ShenyuException; import org.apache.shenyu.plugin.ai.common.config.AiCommonConfig; import org.apache.shenyu.plugin.ai.proxy.enhanced.conversion.AiProtocolConversion; import org.apache.shenyu.plugin.ai.proxy.enhanced.conversion.AiProtocolConverter; @@ -130,7 +129,7 @@ void testBuildRequestAppliesOverridesAndPreservesUnknownFields() throws Exceptio @Test void testBuildRequestRejectsMalformedJson() { - assertThrows(ShenyuException.class, () -> engine.buildRequest("not-json", config)); + assertThrows(AiProxyException.class, () -> engine.buildRequest("not-json", config)); } @Test diff --git a/shenyu-web/src/test/java/org/apache/shenyu/web/handler/AgentGatewayPluginOrderingTest.java b/shenyu-web/src/test/java/org/apache/shenyu/web/handler/AgentGatewayPluginOrderingTest.java index 07da86e2834f..779db717b5bb 100644 --- a/shenyu-web/src/test/java/org/apache/shenyu/web/handler/AgentGatewayPluginOrderingTest.java +++ b/shenyu-web/src/test/java/org/apache/shenyu/web/handler/AgentGatewayPluginOrderingTest.java @@ -51,7 +51,7 @@ class AgentGatewayPluginOrderingTest { private static final List PLUGINS = Arrays.asList(PluginEnum.AI_PROXY, PluginEnum.AI_TOKEN_LIMITER, - PluginEnum.AI_PROMPT, PluginEnum.AGENT_GATEWAY, PluginEnum.KEY_AUTH); + PluginEnum.AI_PROMPT, PluginEnum.MCP_SERVER, PluginEnum.AGENT_GATEWAY, PluginEnum.KEY_AUTH); private final Map previous = new HashMap<>(); @@ -75,7 +75,7 @@ void restorePluginCache() { @Test void shouldUseEnumOrderWithoutCachedConfiguration() { - assertOrder(handler(false), "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"); + assertOrder(handler(false), "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "mcpServer", "aiProxy"); } @Test @@ -83,20 +83,20 @@ void shouldUseCachedDefaultsWhenPluginsAreEnabled() { PLUGINS.forEach(plugin -> cache(plugin, plugin.getCode())); ShenyuWebHandler handler = handler(false); handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.ENABLED, data(PluginEnum.AGENT_GATEWAY, PluginEnum.AGENT_GATEWAY.getCode()))); - assertOrder(handler, "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"); + assertOrder(handler, "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "mcpServer", "aiProxy"); } @Test void shouldNotSilentlyRepairAnUnmigratedCachedGateway() { cache(PluginEnum.AGENT_GATEWAY, 198); - assertOrder(handler(false), "keyAuth", "aiPrompt", "aiTokenLimiter", "agentGateway", "aiProxy"); + assertOrder(handler(false), "keyAuth", "aiPrompt", "aiTokenLimiter", "mcpServer", "agentGateway", "aiProxy"); } @Test void shouldRetainExplicitCustomOrdersEvenWhenUnsafe() { cache(PluginEnum.AGENT_GATEWAY, 149); cache(PluginEnum.AI_PROXY, 148); - assertOrder(handler(false), "aiProxy", "agentGateway", "keyAuth", "aiPrompt", "aiTokenLimiter"); + assertOrder(handler(false), "aiProxy", "agentGateway", "keyAuth", "aiPrompt", "aiTokenLimiter", "mcpServer"); } @Test @@ -104,23 +104,23 @@ void shouldApplyAnAdminSortEventAndFallBackAfterCacheRemoval() { ShenyuWebHandler handler = handler(false); cache(PluginEnum.AGENT_GATEWAY, 198); handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.SORTED, data(PluginEnum.AGENT_GATEWAY, 198))); - assertOrder(handler, "keyAuth", "aiPrompt", "aiTokenLimiter", "agentGateway", "aiProxy"); + assertOrder(handler, "keyAuth", "aiPrompt", "aiTokenLimiter", "mcpServer", "agentGateway", "aiProxy"); cache(PluginEnum.AGENT_GATEWAY, PluginEnum.AGENT_GATEWAY.getCode()); handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.SORTED, data(PluginEnum.AGENT_GATEWAY, PluginEnum.AGENT_GATEWAY.getCode()))); - assertOrder(handler, "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"); + assertOrder(handler, "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "mcpServer", "aiProxy"); BaseDataCache.getInstance().removePluginDataByPluginName(PluginEnum.AGENT_GATEWAY.getName()); handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.SORTED, data(PluginEnum.AGENT_GATEWAY, 198))); - assertOrder(handler, "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"); + assertOrder(handler, "keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "mcpServer", "aiProxy"); } @Test void shouldContinueFromGatewayThroughTheExistingAiChain() { verifyChain(handler(false)); - assertEquals(Arrays.asList("keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "aiProxy"), executed); + assertEquals(Arrays.asList("keyAuth", "agentGateway", "aiPrompt", "aiTokenLimiter", "mcpServer", "aiProxy"), executed); } @Test - void shouldNotReachLlmPluginsWhenGatewayTerminates() { + void shouldNotReachLaterPluginsWhenGatewayTerminates() { verifyChain(handler(true)); assertEquals(Arrays.asList("keyAuth", "agentGateway"), executed); } @@ -130,7 +130,7 @@ void shouldLeaveTheOriginalAiChainWhenGatewayIsDisabled() { ShenyuWebHandler handler = handler(false); handler.onApplicationEvent(new PluginHandlerEvent(PluginHandlerEventEnum.DISABLED, data(PluginEnum.AGENT_GATEWAY, PluginEnum.AGENT_GATEWAY.getCode()))); verifyChain(handler); - assertEquals(Arrays.asList("keyAuth", "aiPrompt", "aiTokenLimiter", "aiProxy"), executed); + assertEquals(Arrays.asList("keyAuth", "aiPrompt", "aiTokenLimiter", "mcpServer", "aiProxy"), executed); } private ShenyuWebHandler handler(final boolean gatewayTerminates) { From 5b0a4597c0a3a3fba57a622a18d1aed2fe3a702b Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 26 Oct 2026 14:44:51 +0800 Subject: [PATCH 11/36] fix(agent-gateway): preserve metrics and tracing compatibility --- .../metrics/reporter/MetricsReporter.java | 32 +++++++++++++++++++ .../AgentGatewayPluginConfiguration.java | 18 +++++++++-- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java index 56cd02bab672..678542a8ae37 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java @@ -19,11 +19,13 @@ import org.apache.shenyu.plugin.metrics.config.Metric; import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.apache.shenyu.plugin.metrics.constant.CanaryMetric; import org.apache.shenyu.plugin.metrics.constant.LabelNames; import org.apache.shenyu.plugin.metrics.spi.MetricsRegister; import java.util.Collection; import java.util.List; +import java.util.Objects; import java.util.Optional; /** @@ -64,6 +66,13 @@ public static synchronized void register(final MetricsRegister metricsRegister) MetricsReporter.registerCounter(LabelNames.RESILIENCE4J_REQUEST_CIRCUITBREAKER_TOTAL, "shenyu resilience4j circuitbreaker request total count"); MetricsReporter.registerCounter(LabelNames.HYSTRIX_REQUEST_CIRCUITBREAKER_TOTAL, "shenyu hystrix circuitbreaker request total count"); MetricsReporter.registerCounter(LabelNames.RATELIMITER_REQUEST_RESTRICT_TOTAL, "shenyu ratelimiter request restrict total count"); + for (CanaryMetric metric : CanaryMetric.values()) { + if (Objects.isNull(metric.getBuckets())) { + registerCounter(metric.getName(), metric.getLabelNames(), metric.getDescription()); + } else { + registerHistogram(metric.getName(), metric.getLabelNames(), metric.getDescription(), metric.getBuckets()); + } + } MetricsReporter.registerCounter(LabelNames.AGENT_REQUESTS_TOTAL, new String[]{"traffic", "outcome", "reason"}, "Terminal Agent request subscriptions including pre-dispatch rejection"); MetricsReporter.registerHistogram(LabelNames.AGENT_REQUEST_LATENCY, new String[]{"traffic", "outcome"}, "Agent request terminal latency millis"); MetricsReporter.registerGauge(LabelNames.AGENT_REQUESTS_INFLIGHT, new String[]{"traffic"}, "Active Agent logical request subscriptions, not sessions"); @@ -150,6 +159,18 @@ public static void registerHistogram(final String name, final String[] labelName Optional.ofNullable(metricsRegister).ifPresent(register -> register.registerHistogram(name, labelNames, document)); } + /** + * Register a histogram with explicit bucket boundaries. + * + * @param name metric name + * @param labelNames label names + * @param document metric description + * @param buckets bucket boundaries in the observation's unit + */ + public static void registerHistogram(final String name, final String[] labelNames, final String document, final double[] buckets) { + Optional.ofNullable(metricsRegister).ifPresent(register -> register.registerHistogram(name, labelNames, document, buckets)); + } + /** * Register histogram. * @@ -249,6 +270,17 @@ public static void recordTime(final String name, final long duration) { recordTime(name, null, duration); } + /** + * Record a fractional histogram observation without converting its unit. + * + * @param name metric name + * @param labelValues label values + * @param value fractional observation + */ + public static void observe(final String name, final String[] labelValues, final double value) { + Optional.ofNullable(metricsRegister).ifPresent(register -> register.observe(name, labelValues, value)); + } + /** * Clean. */ diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java index 1110faf0ce2c..5b0f66966835 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java @@ -38,6 +38,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.core.env.Environment; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -48,6 +49,7 @@ import java.nio.file.Path; import java.util.Arrays; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import reactor.core.publisher.Mono; @@ -276,13 +278,23 @@ static class TracingConfiguration { /** * Use the explicitly supplied application telemetry, never a second SDK or global singleton. - * @param telemetry application-owned telemetry + * @param telemetry optional application-owned telemetry (takes precedence) + * @param gatewayTracer optional tracer owned by the ShenYu tracing starter * @return request-local tracing bridge */ @Bean @ConditionalOnMissingBean(AgentMcpCallTracer.class) - AgentMcpCallTracer agentGatewayCallTracer(final OpenTelemetry telemetry) { - return new OpenTelemetryAgentMcpCallTracer(telemetry); + AgentMcpCallTracer agentGatewayCallTracer(final ObjectProvider telemetry, + @Qualifier("tracingTracer") final ObjectProvider gatewayTracer) { + OpenTelemetry application = telemetry.getIfAvailable(); + if (Objects.nonNull(application)) { + return new OpenTelemetryAgentMcpCallTracer(application); + } + io.opentelemetry.api.trace.Tracer shared = gatewayTracer.getIfAvailable(); + if (Objects.isNull(shared)) { + throw new IllegalStateException("Enabled MCP tracing requires application OpenTelemetry, tracingTracer, or a custom AgentMcpCallTracer"); + } + return new OpenTelemetryAgentMcpCallTracer(shared); } } } From e69b7cc1dff07d2ccf3245eba982cf461874bb40 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 26 Oct 2026 16:19:57 +0800 Subject: [PATCH 12/36] fix(agent-gateway): align audit module version --- .../shenyu-spring-boot-starter-agent-audit/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/pom.xml b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/pom.xml index 7115703bfd5a..013e8e9c8987 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/pom.xml +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/pom.xml @@ -20,7 +20,7 @@ org.apache.shenyu shenyu-spring-boot-starter - 2.7.2-SNAPSHOT + 2.7.3-SNAPSHOT shenyu-spring-boot-starter-agent-audit From c8b7a329fbe24102933bd97daca660102210ed34 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 26 Oct 2026 16:21:15 +0800 Subject: [PATCH 13/36] chore: retrigger checks From f9eb7ba866668bcca8deed04d5e9cadcd67f1365 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Tue, 27 Oct 2026 09:11:49 +0800 Subject: [PATCH 14/36] fix(agent-gateway): preserve released upgrade migrations --- .../scripts/check-agent-gateway-migrations.py | 66 ++++++++++++++++++- .../scripts/test-agent-gateway-migrations.py | 2 +- db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql | 4 +- db/upgrade/2.7.1-upgrade-2.7.2-ob.sql | 4 +- db/upgrade/2.7.1-upgrade-2.7.2-og.sql | 4 +- db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql | 4 +- db/upgrade/2.7.1-upgrade-2.7.2-pg.sql | 4 +- db/upgrade/2.7.2-agent-gateway-order.sql | 35 ---------- db/upgrade/2.7.2-upgrade-2.7.3-h2.sql | 7 ++ db/upgrade/2.7.2-upgrade-2.7.3-mysql.sql | 7 ++ db/upgrade/2.7.2-upgrade-2.7.3-ob.sql | 7 ++ db/upgrade/2.7.2-upgrade-2.7.3-og.sql | 7 ++ db/upgrade/2.7.2-upgrade-2.7.3-oracle.sql | 7 ++ db/upgrade/2.7.2-upgrade-2.7.3-pg.sql | 7 ++ docs/agent-gateway-governance-order.md | 14 ++-- .../enums/AgentGatewayPluginOrderTest.java | 59 +++++++++++++---- 16 files changed, 168 insertions(+), 70 deletions(-) delete mode 100644 db/upgrade/2.7.2-agent-gateway-order.sql diff --git a/.github/scripts/check-agent-gateway-migrations.py b/.github/scripts/check-agent-gateway-migrations.py index 93b49d2756da..50c849dc0cc3 100644 --- a/.github/scripts/check-agent-gateway-migrations.py +++ b/.github/scripts/check-agent-gateway-migrations.py @@ -20,6 +20,12 @@ from pathlib import Path DIALECTS = ("mysql", "ob", "og", "oracle", "pg") +RELEASED_ORDER = 198 +CURRENT_ORDER = 169 +ORDER_KEYS = { + ("plugin", "68"), + ("namespace_plugin_rel", "1960000000000001030"), +} EXPECTED = { "plugin": {"68"}, "plugin_handle": {str(1960000000000001000 + i) for i in range(2)}, @@ -63,12 +69,66 @@ def seeds(sql): return result +def agent_order_token(values): + """Return the Agent Gateway sort token range and value.""" + tokens = normalized_tokens(values) + if "'agentGateway'" in tokens: + marker = tokens.index("'agentGateway'") + else: + marker = tokens.index("'68'") + order_start = next(index for index, token in enumerate(tokens[marker + 1:], marker + 1) if token.isdigit()) + order_end = order_start + 1 + while order_end < len(tokens) and tokens[order_end].isdigit() and order_end - order_start < 3: + order_end += 1 + return (order_start, order_end), int("".join(tokens[order_start:order_end])) + + +def normalized_tokens(values): + """Normalize tokenizer character runs into complete numeric literals.""" + tokens = [] + number = [] + + def flush_number(): + if number: + tokens.append("".join(number)) + number.clear() + + for token in values: + if len(token) == 1 and token.isdigit(): + number.append(token) + else: + flush_number() + tokens.append(token) + flush_number() + return tuple(tokens) + + +def only_order_moved(expected, actual): + """Whether two seeds differ in exactly the allowed Agent Gateway order value.""" + expected = normalized_tokens(expected) + actual = normalized_tokens(actual) + (expected_start, expected_end), expected_order = agent_order_token(expected) + (actual_start, actual_end), actual_order = agent_order_token(actual) + return ( + expected_order == CURRENT_ORDER + and actual_order == RELEASED_ORDER + and len(expected) == len(actual) + and all(expected[index] == actual[index] + for index in range(len(expected)) + if not (expected_start <= index < expected_end or actual_start <= index < actual_end)) + ) + + def check_pair(schema, migration): - """Compare every value and column list in each dialect's own seed records.""" + """Compare released seeds, allowing only the deliberate 2.7.3 order move.""" expected, actual = seeds(schema), seeds(migration) for key in expected: - if expected[key] != actual[key]: - raise ValueError(f"fresh-install/upgrade mismatch: {key}") + if expected[key] == actual[key]: + continue + if key in ORDER_KEYS: + if only_order_moved(expected[key], actual[key]): + continue + raise ValueError(f"fresh-install/upgrade mismatch: {key}") return len(expected) diff --git a/.github/scripts/test-agent-gateway-migrations.py b/.github/scripts/test-agent-gateway-migrations.py index 246352e542de..dd928c31306a 100644 --- a/.github/scripts/test-agent-gateway-migrations.py +++ b/.github/scripts/test-agent-gateway-migrations.py @@ -86,7 +86,7 @@ def test_null_keyword_case_is_ignored(self): def test_quoted_null_is_not_a_null_literal(self): changed, replacements = re.subn( - r"('68', )NULL(, \d+)", + r"('68', 'agentGateway', )null(, 'Ai', \d+)", r"\1'NULL'\2", self.migration, count=1, diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql b/db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql index a44ab8e5fe68..94d2784913a6 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql @@ -59,7 +59,7 @@ ALTER TABLE `selector` ADD INDEX `idx_selector_plugin_id` (`plugin_id`) USING BT ALTER TABLE `permission` ADD INDEX `idx_permission_resource_id` (`resource_id`) USING BTREE; -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. -INSERT INTO `plugin` VALUES ('68', 'agentGateway', null, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); +INSERT INTO `plugin` VALUES ('68', 'agentGateway', null, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); INSERT INTO `plugin_handle` VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `plugin_handle` VALUES ('1960000000000001001', '68', 'responseRequestId', 'responseRequestId', 3, 2, 1, '{"required":"0","defaultValue":"false","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `resource` VALUES ('1960000000000001010', '1346775491550474240', 'agentGateway', 'agentGateway', '/plug/agentGateway', 'agentGateway', 1, 0, 'pic-center', 0, 0, '', 1, '2026-09-19 00:00:00', '2026-09-19 00:00:00'); @@ -82,7 +82,7 @@ INSERT INTO `permission` VALUES ('1960000000000001026', '1346358560427216896', ' INSERT INTO `permission` VALUES ('1960000000000001027', '1346358560427216896', '1960000000000001017', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `permission` VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `permission` VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); -INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); -- add index to speed up the meta data path uniqueness check ALTER TABLE `meta_data` ADD INDEX `idx_meta_data_namespace_path` (`namespace_id`, `path`) USING BTREE; diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-ob.sql b/db/upgrade/2.7.1-upgrade-2.7.2-ob.sql index 5ba5f076c6a2..a2bcadaf73b8 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-ob.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-ob.sql @@ -62,7 +62,7 @@ ALTER TABLE `resource` ADD INDEX `idx_resource_parent_id` (`parent_id`) USING BT ALTER TABLE `user_role` ADD INDEX `idx_user_role_user_id` (`user_id`) USING BTREE; -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. -INSERT INTO `plugin` VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); +INSERT INTO `plugin` VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', null); INSERT INTO `plugin_handle` VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `plugin_handle` VALUES ('1960000000000001001', '68', 'responseRequestId', 'responseRequestId', 3, 2, 1, '{"required":"0","defaultValue":"false","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `resource` VALUES ('1960000000000001010', '1346775491550474240', 'agentGateway', 'agentGateway', '/plug/agentGateway', 'agentGateway', 1, 0, 'pic-center', 0, 0, '', 1, '2026-09-19 00:00:00', '2026-09-19 00:00:00'); @@ -85,7 +85,7 @@ INSERT INTO `permission` VALUES ('1960000000000001026', '1346358560427216896', ' INSERT INTO `permission` VALUES ('1960000000000001027', '1346358560427216896', '1960000000000001017', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `permission` VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO `permission` VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); -INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO `namespace_plugin_rel` (`id`,`namespace_id`,`plugin_id`, `config`, `sort`, `enabled`, `date_created`, `date_updated`) VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); -- add index to speed up the meta data path uniqueness check ALTER TABLE `meta_data` ADD INDEX `idx_meta_data_namespace_path` (`namespace_id`, `path`) USING BTREE; ALTER TABLE `operation_record_log` ADD INDEX `idx_operation_log_time` (`operation_time`) USING BTREE; diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-og.sql b/db/upgrade/2.7.1-upgrade-2.7.2-og.sql index b2d8ba94a532..4fb3763d92a3 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-og.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-og.sql @@ -62,7 +62,7 @@ CREATE INDEX IF NOT EXISTS "idx_resource_parent_id" ON "public"."resource" USING CREATE INDEX IF NOT EXISTS "idx_user_role_user_id" ON "public"."user_role" USING btree ("user_id"); -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. -INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); +INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); INSERT INTO "public"."plugin_handle" VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."plugin_handle" VALUES ('1960000000000001001', '68', 'responseRequestId', 'responseRequestId', 3, 2, 1, '{"required":"0","defaultValue":"false","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."resource" VALUES ('1960000000000001010', '1346775491550474240', 'agentGateway', 'agentGateway', '/plug/agentGateway', 'agentGateway', 1, 0, 'pic-center', 0, 0, '', 1, '2026-09-19 00:00:00', '2026-09-19 00:00:00'); @@ -85,7 +85,7 @@ INSERT INTO "public"."permission" VALUES ('1960000000000001026', '13463585604272 INSERT INTO "public"."permission" VALUES ('1960000000000001027', '1346358560427216896', '1960000000000001017', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."permission" VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."permission" VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); -INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); -- add index to speed up the meta data path uniqueness check CREATE INDEX "idx_meta_data_namespace_path" ON "public"."meta_data" USING btree ("namespace_id","path"); CREATE INDEX "idx_operation_log_time" ON "public"."operation_record_log" USING btree ("operation_time"); diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql b/db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql index f58ee596bd99..d0fceb9bae67 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql @@ -63,7 +63,7 @@ create index idx_user_role_user_id on user_role (user_id); -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(plugin(id)) */ INTO plugin (id, name, config, role, sort, enabled, date_created, date_updated) -VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, sysdate, sysdate); +VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, sysdate, sysdate); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(plugin_handle(id)) */ INTO plugin_handle (id, plugin_id, field, label, data_type, type, sort, ext_obj, date_created, date_updated) VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', sysdate, sysdate); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(plugin_handle(id)) */ INTO plugin_handle (id, plugin_id, field, label, data_type, type, sort, ext_obj, date_created, date_updated) @@ -99,7 +99,7 @@ INSERT INTO permission (id, object_id, resource_id, date_created, date_updated) INSERT INTO permission (id, object_id, resource_id, date_created, date_updated) VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', sysdate, sysdate); INSERT INTO permission (id, object_id, resource_id, date_created, date_updated) VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', sysdate, sysdate); INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX (namespace_plugin_rel(id)) */ INTO namespace_plugin_rel (id,namespace_id,plugin_id, config, sort, enabled) -VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0); +VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0); -- add index to speed up the meta data path uniqueness check create index idx_meta_data_namespace_path on meta_data (namespace_id, path); create index idx_operation_log_time on operation_record_log (operation_time); diff --git a/db/upgrade/2.7.1-upgrade-2.7.2-pg.sql b/db/upgrade/2.7.1-upgrade-2.7.2-pg.sql index ee28318b3c9f..d74e83a736ae 100644 --- a/db/upgrade/2.7.1-upgrade-2.7.2-pg.sql +++ b/db/upgrade/2.7.1-upgrade-2.7.2-pg.sql @@ -62,7 +62,7 @@ CREATE INDEX IF NOT EXISTS "idx_resource_parent_id" ON "public"."resource" USING CREATE INDEX IF NOT EXISTS "idx_user_role_user_id" ON "public"."user_role" USING btree ("user_id"); -- Agent Gateway: keep upgrade seeds consistent with the fresh-install schema. -INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 169, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); +INSERT INTO "public"."plugin" VALUES ('68', 'agentGateway', NULL, 'Ai', 198, 0, '2026-09-19 00:00:00', '2026-09-19 00:00:00', NULL); INSERT INTO "public"."plugin_handle" VALUES ('1960000000000001000', '68', 'trafficType', 'trafficType', 2, 2, 0, '{"required":"1","defaultValue":"LLM","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."plugin_handle" VALUES ('1960000000000001001', '68', 'responseRequestId', 'responseRequestId', 3, 2, 1, '{"required":"0","defaultValue":"false","rule":""}', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."resource" VALUES ('1960000000000001010', '1346775491550474240', 'agentGateway', 'agentGateway', '/plug/agentGateway', 'agentGateway', 1, 0, 'pic-center', 0, 0, '', 1, '2026-09-19 00:00:00', '2026-09-19 00:00:00'); @@ -85,7 +85,7 @@ INSERT INTO "public"."permission" VALUES ('1960000000000001026', '13463585604272 INSERT INTO "public"."permission" VALUES ('1960000000000001027', '1346358560427216896', '1960000000000001017', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."permission" VALUES ('1960000000000001028', '1346358560427216896', '1960000000000001018', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); INSERT INTO "public"."permission" VALUES ('1960000000000001029', '1346358560427216896', '1960000000000001019', '2026-09-19 00:00:00', '2026-09-19 00:00:00'); -INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 169, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); +INSERT INTO "public"."namespace_plugin_rel" VALUES ('1960000000000001030','649330b6-c2d7-4edc-be8e-8a54df9eb385','68', NULL, 198, 0, '2026-09-19 00:00:00.000', '2026-09-19 00:00:00.000'); -- add index to speed up the meta data path uniqueness check CREATE INDEX "idx_meta_data_namespace_path" ON "public"."meta_data" USING btree ("namespace_id","path"); CREATE INDEX "idx_operation_log_time" ON "public"."operation_record_log" USING btree ("operation_time"); diff --git a/db/upgrade/2.7.2-agent-gateway-order.sql b/db/upgrade/2.7.2-agent-gateway-order.sql deleted file mode 100644 index a8c1622fabd0..000000000000 --- a/db/upgrade/2.7.2-agent-gateway-order.sql +++ /dev/null @@ -1,35 +0,0 @@ --- 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. - --- Explicit, repeatable migration for an EXISTING Agent Gateway installation. --- Use the application's database/schema; these statements use common SQL. --- Before running, follow docs/agent-gateway-governance-order.md: back up and --- review BOTH plugin and namespace_plugin_rel rows, including disabled rows. --- A custom value equal to the old default 198 cannot be distinguished by SQL. --- If any 198 row was deliberately customized, do NOT run this whole script; --- restrict each UPDATE to the explicitly approved row IDs instead. --- No plugin is enabled, no credentials/configuration are changed, and values --- other than 198 are preserved. Prompt/limiter/proxy sorts are NOT migrated. --- Run both UPDATEs in one operator-managed transaction, verify, then commit. --- Database writes alone do not refresh Admin/gateway caches: resynchronize --- all affected namespaces before routing traffic through the updated gateway. --- Syntax verified against MySQL, PostgreSQL and Oracle upgrade paths. - -UPDATE plugin SET sort = 169 WHERE name = 'agentGateway' AND sort = 198; - -UPDATE namespace_plugin_rel SET sort = 169 -WHERE sort = 198 - AND plugin_id IN (SELECT id FROM plugin WHERE name = 'agentGateway'); diff --git a/db/upgrade/2.7.2-upgrade-2.7.3-h2.sql b/db/upgrade/2.7.2-upgrade-2.7.3-h2.sql index 93b6e45b5996..836aee670bad 100644 --- a/db/upgrade/2.7.2-upgrade-2.7.3-h2.sql +++ b/db/upgrade/2.7.2-upgrade-2.7.3-h2.sql @@ -18,6 +18,13 @@ ALTER TABLE selector RENAME COLUMN loged TO logged; ALTER TABLE rule RENAME COLUMN loged TO logged; +-- Move Agent Gateway ahead of the AI governance chain for existing installs. +-- Preserve deliberate custom orders: only the old default sort value changes. +UPDATE plugin SET sort = 169 WHERE name = 'agentGateway' AND sort = 198; +UPDATE namespace_plugin_rel SET sort = 169 +WHERE sort = 198 + AND plugin_id IN (SELECT id FROM plugin WHERE name = 'agentGateway'); + -- Stop all Admin writers and back up instance_info before this one-time migration. -- Retain the latest heartbeat, then latest update/create timestamp, then greatest id. -- Rows upgraded from 2.7.1 have heartbeat 0 and are ordered by timestamps and id. diff --git a/db/upgrade/2.7.2-upgrade-2.7.3-mysql.sql b/db/upgrade/2.7.2-upgrade-2.7.3-mysql.sql index c550610917f3..8ef2a1f4a737 100644 --- a/db/upgrade/2.7.2-upgrade-2.7.3-mysql.sql +++ b/db/upgrade/2.7.2-upgrade-2.7.3-mysql.sql @@ -18,6 +18,13 @@ ALTER TABLE `selector` RENAME COLUMN `loged` TO `logged`; ALTER TABLE `rule` RENAME COLUMN `loged` TO `logged`; +-- Move Agent Gateway ahead of the AI governance chain for existing installs. +-- Preserve deliberate custom orders: only the old default sort value changes. +UPDATE `plugin` SET `sort` = 169 WHERE `name` = 'agentGateway' AND `sort` = 198; +UPDATE `namespace_plugin_rel` SET `sort` = 169 +WHERE `sort` = 198 + AND `plugin_id` IN (SELECT `id` FROM `plugin` WHERE `name` = 'agentGateway'); + -- Stop all Admin writers and back up instance_info before this one-time migration. -- Retain the latest heartbeat, then latest update/create timestamp, then greatest id. -- Rows upgraded from 2.7.1 have heartbeat 0 and are ordered by timestamps and id. diff --git a/db/upgrade/2.7.2-upgrade-2.7.3-ob.sql b/db/upgrade/2.7.2-upgrade-2.7.3-ob.sql index f9959945f74e..28fff3775448 100644 --- a/db/upgrade/2.7.2-upgrade-2.7.3-ob.sql +++ b/db/upgrade/2.7.2-upgrade-2.7.3-ob.sql @@ -18,6 +18,13 @@ ALTER TABLE `selector` RENAME COLUMN `loged` TO `logged`; ALTER TABLE `rule` RENAME COLUMN `loged` TO `logged`; +-- Move Agent Gateway ahead of the AI governance chain for existing installs. +-- Preserve deliberate custom orders: only the old default sort value changes. +UPDATE `plugin` SET `sort` = 169 WHERE `name` = 'agentGateway' AND `sort` = 198; +UPDATE `namespace_plugin_rel` SET `sort` = 169 +WHERE `sort` = 198 + AND `plugin_id` IN (SELECT `id` FROM `plugin` WHERE `name` = 'agentGateway'); + -- Stop all Admin writers and back up instance_info before this one-time migration. -- Retain the latest heartbeat, then latest update/create timestamp, then greatest id. -- Rows upgraded from 2.7.1 have heartbeat 0 and are ordered by timestamps and id. diff --git a/db/upgrade/2.7.2-upgrade-2.7.3-og.sql b/db/upgrade/2.7.2-upgrade-2.7.3-og.sql index 382cad4c5a24..a94f67f40199 100644 --- a/db/upgrade/2.7.2-upgrade-2.7.3-og.sql +++ b/db/upgrade/2.7.2-upgrade-2.7.3-og.sql @@ -18,6 +18,13 @@ ALTER TABLE "public"."selector" RENAME COLUMN "loged" TO "logged"; ALTER TABLE "public"."rule" RENAME COLUMN "loged" TO "logged"; +-- Move Agent Gateway ahead of the AI governance chain for existing installs. +-- Preserve deliberate custom orders: only the old default sort value changes. +UPDATE "public"."plugin" SET "sort" = 169 WHERE "name" = 'agentGateway' AND "sort" = 198; +UPDATE "public"."namespace_plugin_rel" SET "sort" = 169 +WHERE "sort" = 198 + AND "plugin_id" IN (SELECT "id" FROM "public"."plugin" WHERE "name" = 'agentGateway'); + -- Stop all Admin writers and back up instance_info before this one-time migration. -- Retain the latest heartbeat, then latest update/create timestamp, then greatest id. -- Rows upgraded from 2.7.1 have heartbeat 0 and are ordered by timestamps and id. diff --git a/db/upgrade/2.7.2-upgrade-2.7.3-oracle.sql b/db/upgrade/2.7.2-upgrade-2.7.3-oracle.sql index f51c04e9d612..e6b1b5f985df 100644 --- a/db/upgrade/2.7.2-upgrade-2.7.3-oracle.sql +++ b/db/upgrade/2.7.2-upgrade-2.7.3-oracle.sql @@ -18,6 +18,13 @@ ALTER TABLE selector RENAME COLUMN loged TO logged; ALTER TABLE rule RENAME COLUMN loged TO logged; +-- Move Agent Gateway ahead of the AI governance chain for existing installs. +-- Preserve deliberate custom orders: only the old default sort value changes. +UPDATE plugin SET sort = 169 WHERE name = 'agentGateway' AND sort = 198; +UPDATE namespace_plugin_rel SET sort = 169 +WHERE sort = 198 + AND plugin_id IN (SELECT id FROM plugin WHERE name = 'agentGateway'); + -- Stop all Admin writers and back up instance_info before this one-time migration. -- Retain the latest heartbeat, then latest update/create timestamp, then greatest id. -- Rows upgraded from 2.7.1 have heartbeat 0 and are ordered by timestamps and id. diff --git a/db/upgrade/2.7.2-upgrade-2.7.3-pg.sql b/db/upgrade/2.7.2-upgrade-2.7.3-pg.sql index ca3a38ac3407..c9c28865dcc0 100644 --- a/db/upgrade/2.7.2-upgrade-2.7.3-pg.sql +++ b/db/upgrade/2.7.2-upgrade-2.7.3-pg.sql @@ -18,6 +18,13 @@ ALTER TABLE "public"."selector" RENAME COLUMN "loged" TO "logged"; ALTER TABLE "public"."rule" RENAME COLUMN "loged" TO "logged"; +-- Move Agent Gateway ahead of the AI governance chain for existing installs. +-- Preserve deliberate custom orders: only the old default sort value changes. +UPDATE "public"."plugin" SET "sort" = 169 WHERE "name" = 'agentGateway' AND "sort" = 198; +UPDATE "public"."namespace_plugin_rel" SET "sort" = 169 +WHERE "sort" = 198 + AND "plugin_id" IN (SELECT "id" FROM "public"."plugin" WHERE "name" = 'agentGateway'); + -- Stop all Admin writers and back up instance_info before this one-time migration. -- Retain the latest heartbeat, then latest update/create timestamp, then greatest id. -- Rows upgraded from 2.7.1 have heartbeat 0 and are ordered by timestamps and id. diff --git a/docs/agent-gateway-governance-order.md b/docs/agent-gateway-governance-order.md index df0b8b53a8ab..a191bf9479ed 100644 --- a/docs/agent-gateway-governance-order.md +++ b/docs/agent-gateway-governance-order.md @@ -129,13 +129,13 @@ plugins, selector matching and unsynchronized caches require separate inspection an intentional custom 198 from the default. If any such row is custom, do not run the broad script: restrict each UPDATE to explicitly approved row IDs. Other custom values, including invalid ones, are left untouched. -3. For approved default-only deployments, run - `db/upgrade/2.7.2-agent-gateway-order.sql` in one client-managed transaction. - It updates only AG rows with `sort = 198` to 169, globally and in all namespaces, - and is repeatable. It does not change enabled/config fields or other plugins. - MySQL/OceanBase use `START TRANSACTION`; PostgreSQL/openGauss use `BEGIN`; - disable autocommit for H2/Oracle as appropriate. Inspect affected counts before - committing; roll back if they differ from the reviewed candidate list. +3. For approved default-only deployments, run the database's + `db/upgrade/2.7.2-upgrade-2.7.3-.sql` migration. Its Agent Gateway + section updates only AG rows with `sort = 198` to 169, globally and in all + namespaces, and is repeatable. It does not change enabled/config fields or + other plugins. Run the whole migration in one transaction, inspect affected + counts before committing, and roll back if they differ from the reviewed + candidate list. 4. Inspect legacy Prompt/Proxy drift separately. For each reviewed row, use the Admin namespace plugin editor to set Prompt 170 or Proxy 199, or an explicit row-ID-and-old-sort-guarded UPDATE. Never blanket-normalize custom orders. diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/enums/AgentGatewayPluginOrderTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/enums/AgentGatewayPluginOrderTest.java index 97409161560d..e0aa43b0ec88 100644 --- a/shenyu-common/src/test/java/org/apache/shenyu/common/enums/AgentGatewayPluginOrderTest.java +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/enums/AgentGatewayPluginOrderTest.java @@ -60,16 +60,24 @@ void shouldPlaceGatewayAfterAuthenticationAndBeforeTheExistingAiChain() { "db/init/mysql/schema.sql", "db/init/pg/create-table.sql", "db/init/oracle/schema.sql", - "shenyu-admin/src/main/resources/sql-script/h2/schema.sql", + "shenyu-admin/src/main/resources/sql-script/h2/schema.sql" + }) + void shouldKeepGatewayAndNamespaceSeedsInSync(final String script) throws IOException { + String sql = Files.readString(repositoryRoot().resolve(script)); + assertSeedOrder(sql, "68", PluginEnum.AGENT_GATEWAY, script); + } + + @ParameterizedTest + @ValueSource(strings = { "db/upgrade/2.7.1-upgrade-2.7.2-mysql.sql", "db/upgrade/2.7.1-upgrade-2.7.2-pg.sql", "db/upgrade/2.7.1-upgrade-2.7.2-og.sql", "db/upgrade/2.7.1-upgrade-2.7.2-ob.sql", "db/upgrade/2.7.1-upgrade-2.7.2-oracle.sql" }) - void shouldKeepGatewayAndNamespaceSeedsInSync(final String script) throws IOException { + void shouldKeepReleasedUpgradeSeedsImmutableAtThePreviousOrder(final String script) throws IOException { String sql = Files.readString(repositoryRoot().resolve(script)); - assertSeedOrder(sql, "68", PluginEnum.AGENT_GATEWAY, script); + assertSeedOrder(sql, "68", 198, script); } @ParameterizedTest @@ -88,26 +96,49 @@ void shouldKeepTheCompleteFreshInstallAiChainInSync(final String script) throws } private void assertSeedOrder(final String sql, final String id, final PluginEnum plugin, final String script) { - String value = Integer.toString(plugin.getCode()); + assertSeedOrder(sql, id, plugin.getName(), plugin.getCode(), script); + } + + private void assertSeedOrder(final String sql, final String id, final int order, final String script) { + assertSeedOrder(sql, id, PluginEnum.AGENT_GATEWAY.getName(), order, script); + } + + private void assertSeedOrder(final String sql, final String id, final String name, final int order, final String script) { + String value = Integer.toString(order); String field = "(?:NULL|'(?:''|[^'])*')"; - String pluginRow = "'" + id + "'[ ]*,[ ]*'" + plugin.getName() + String pluginRow = "'" + id + "'[ ]*,[ ]*'" + name + "'[ ]*,[ ]*(?:'[^']+'[ ]*,[ ]*" + value + "|" + field + "[ ]*,[ ]*'[^']+'[ ]*,[ ]*" + value + ")[ ]*,"; String namespaceRow = "'[^']+'[ ]*,[ ]*'649330b6-c2d7-4edc-be8e-8a54df9eb385'[ ]*,[ ]*'" + id + "'[ ]*,[ ]*" + field + "[ ]*,[ ]*" + value + "[ ]*,"; String normalized = sql.lines().collect(Collectors.joining(" ")).replace((char) 9, ' '); - assertTrue(Pattern.compile(pluginRow, Pattern.CASE_INSENSITIVE).matcher(normalized).find(), script + ": plugin " + plugin.getName()); - assertTrue(Pattern.compile(namespaceRow, Pattern.CASE_INSENSITIVE).matcher(normalized).find(), script + ": namespace " + plugin.getName()); + assertTrue(Pattern.compile(pluginRow, Pattern.CASE_INSENSITIVE).matcher(normalized).find(), script + ": plugin " + name); + assertTrue(Pattern.compile(namespaceRow, Pattern.CASE_INSENSITIVE).matcher(normalized).find(), script + ": namespace " + name); } - @Test - void shouldKeepTheExistingInstallationMigrationExplicitAndDefaultOnly() throws IOException { - String sql = Files.readString(repositoryRoot().resolve("db/upgrade/2.7.2-agent-gateway-order.sql")); - String statements = sql.lines().filter(line -> !line.startsWith("--")) + @ParameterizedTest + @ValueSource(strings = { + "db/upgrade/2.7.2-upgrade-2.7.3-h2.sql", + "db/upgrade/2.7.2-upgrade-2.7.3-mysql.sql", + "db/upgrade/2.7.2-upgrade-2.7.3-ob.sql", + "db/upgrade/2.7.2-upgrade-2.7.3-og.sql", + "db/upgrade/2.7.2-upgrade-2.7.3-oracle.sql", + "db/upgrade/2.7.2-upgrade-2.7.3-pg.sql" + }) + void shouldMoveOnlyTheReleasedDefaultOrderInEveryDialectMigration(final String script) throws IOException { + String sql = Files.readString(repositoryRoot().resolve(script)); + String statements = sql.lines().filter(line -> !line.trim().startsWith("--")) .map(String::trim).filter(line -> !line.isEmpty()).collect(Collectors.joining(" ")); - assertEquals("UPDATE plugin SET sort = " + PluginEnum.AGENT_GATEWAY.getCode() - + " WHERE name = 'agentGateway' AND sort = 198; UPDATE namespace_plugin_rel SET sort = " + Pattern plugin = Pattern.compile("UPDATE\\s+(?:\"public\"\\s*\\.\\s*)?[`\"]?plugin[`\"]?\\s+SET\\s+[`\"]?sort[`\"]?\\s*=\\s*" + + PluginEnum.AGENT_GATEWAY.getCode() + + "\\s+WHERE\\s+[`\"]?name[`\"]?\\s*=\\s*'agentGateway'\\s+AND\\s+[`\"]?sort[`\"]?\\s*=\\s*198", + Pattern.CASE_INSENSITIVE); + Pattern namespace = Pattern.compile("UPDATE\\s+(?:\"public\"\\s*\\.\\s*)?[`\"]?namespace_plugin_rel[`\"]?\\s+SET\\s+[`\"]?sort[`\"]?\\s*=\\s*" + PluginEnum.AGENT_GATEWAY.getCode() - + " WHERE sort = 198 AND plugin_id IN (SELECT id FROM plugin WHERE name = 'agentGateway');", statements); + + "\\s+WHERE\\s+[`\"]?sort[`\"]?\\s*=\\s*198\\s+AND\\s+[`\"]?plugin_id[`\"]?\\s+IN\\s*\\(\\s*SELECT\\s+[`\"]?id[`\"]?\\s+FROM\\s+" + + "(?:\"public\"\\s*\\.\\s*)?[`\"]?plugin[`\"]?\\s+WHERE\\s+[`\"]?name[`\"]?\\s*=\\s*'agentGateway'", + Pattern.CASE_INSENSITIVE); + assertTrue(plugin.matcher(statements).find(), script + ": plugin order migration"); + assertTrue(namespace.matcher(statements).find(), script + ": namespace order migration"); assertFalse(statements.contains("enabled")); assertFalse(statements.contains("config")); } From a34127bc8a492e6de33efdb48285b3abd6c476e6 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Tue, 27 Oct 2026 09:35:19 +0800 Subject: [PATCH 15/36] test(admin): cover plugin tables in migration contract fixtures --- .../org/apache/shenyu/admin/mapper/InstanceInfoUpsertTest.java | 2 ++ .../shenyu/admin/mapper/MockRequestHeaderMigrationTest.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/InstanceInfoUpsertTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/InstanceInfoUpsertTest.java index 96cc90609f24..306365a9eedf 100644 --- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/InstanceInfoUpsertTest.java +++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/InstanceInfoUpsertTest.java @@ -206,6 +206,8 @@ void migrationRetainsLatestCompleteRowsAndRejectsDuplicates() { jdbc.execute("CREATE TABLE selector (loged INT)"); jdbc.execute("CREATE TABLE rule (loged INT)"); jdbc.execute("CREATE TABLE mock_request_record (header VARCHAR(1024))"); + jdbc.execute("CREATE TABLE plugin (id VARCHAR(128), name VARCHAR(128), sort INT)"); + jdbc.execute("CREATE TABLE namespace_plugin_rel (plugin_id VARCHAR(128), sort INT)"); insertLegacy("old-heartbeat", "ns", 100, "2026-01-03 00:00:00"); insertLegacy("latest-heartbeat", "ns", 200, "2026-01-01 00:00:00"); insertLegacy("tie-a", "ns-tie", 0, "2026-01-01 00:00:00"); diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/MockRequestHeaderMigrationTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/MockRequestHeaderMigrationTest.java index 369065871fb5..e019ff07f114 100644 --- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/MockRequestHeaderMigrationTest.java +++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/MockRequestHeaderMigrationTest.java @@ -74,6 +74,8 @@ public void testMigrationPreservesLegacyDataAndAcceptsLongHeaders() throws Excep statement.execute("CREATE TABLE rule (loged INT)"); statement.execute("CREATE TABLE instance_info (id VARCHAR(128), namespace_id VARCHAR(50), instance_ip VARCHAR(128)," + "instance_port VARCHAR(128), instance_type VARCHAR(128), last_heart_beat_time BIGINT, date_updated TIMESTAMP, date_created TIMESTAMP)"); + statement.execute("CREATE TABLE plugin (id VARCHAR(128), name VARCHAR(128), sort INT)"); + statement.execute("CREATE TABLE namespace_plugin_rel (plugin_id VARCHAR(128), sort INT)"); new ResourceDatabasePopulator(new FileSystemResource(upgradeScript())).execute(dataSource); MockRequestRecordDO restored = mapper.queryById("legacy"); From d093d0e5272a6ded6c29e0d7d1a472a463719b15 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Tue, 27 Oct 2026 23:06:21 +0800 Subject: [PATCH 16/36] fix(ai-proxy): preserve audit mapping after master merge --- .../apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java | 1 + 1 file changed, 1 insertion(+) diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java index 9f85f1b24ebe..0e0bdb084ba8 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java @@ -19,6 +19,7 @@ import org.apache.shenyu.common.constant.Constants; import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.dto.ProxyApiKeyData; import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.dto.convert.rule.AiProxyHandle; From cb5c27604c1058f378edb7f7094594a9c3b56ccc Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Wed, 28 Oct 2026 00:39:40 +0800 Subject: [PATCH 17/36] fix(agent-gateway): align migration baseline fixes --- db/upgrade/2.7.2-agent-gateway-order.sql | 34 ------------------- .../admin/mapper/InstanceInfoUpsertTest.java | 2 ++ .../MockRequestHeaderMigrationTest.java | 2 ++ 3 files changed, 4 insertions(+), 34 deletions(-) delete mode 100644 db/upgrade/2.7.2-agent-gateway-order.sql diff --git a/db/upgrade/2.7.2-agent-gateway-order.sql b/db/upgrade/2.7.2-agent-gateway-order.sql deleted file mode 100644 index 8c53fafb4460..000000000000 --- a/db/upgrade/2.7.2-agent-gateway-order.sql +++ /dev/null @@ -1,34 +0,0 @@ --- 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. - --- Explicit, repeatable migration for an EXISTING Agent Gateway installation. --- Use the application's database/schema; these statements use common SQL. --- Before running, follow docs/agent-gateway-governance-order.md: back up and --- review BOTH plugin and namespace_plugin_rel rows, including disabled rows. --- A custom value equal to the old default 198 cannot be distinguished by SQL. --- If any 198 row was deliberately customized, do NOT run this whole script; --- restrict each UPDATE to the explicitly approved row IDs instead. --- No plugin is enabled, no credentials/configuration are changed, and values --- other than 198 are preserved. Prompt/limiter/proxy sorts are NOT migrated. --- Run both UPDATEs in one operator-managed transaction, verify, then commit. --- Database writes alone do not refresh Admin/gateway caches: resynchronize --- all affected namespaces before routing traffic through the updated gateway. - -UPDATE plugin SET sort = 169 WHERE name = 'agentGateway' AND sort = 198; - -UPDATE namespace_plugin_rel SET sort = 169 -WHERE sort = 198 - AND plugin_id IN (SELECT id FROM plugin WHERE name = 'agentGateway'); diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/InstanceInfoUpsertTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/InstanceInfoUpsertTest.java index 96cc90609f24..306365a9eedf 100644 --- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/InstanceInfoUpsertTest.java +++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/InstanceInfoUpsertTest.java @@ -206,6 +206,8 @@ void migrationRetainsLatestCompleteRowsAndRejectsDuplicates() { jdbc.execute("CREATE TABLE selector (loged INT)"); jdbc.execute("CREATE TABLE rule (loged INT)"); jdbc.execute("CREATE TABLE mock_request_record (header VARCHAR(1024))"); + jdbc.execute("CREATE TABLE plugin (id VARCHAR(128), name VARCHAR(128), sort INT)"); + jdbc.execute("CREATE TABLE namespace_plugin_rel (plugin_id VARCHAR(128), sort INT)"); insertLegacy("old-heartbeat", "ns", 100, "2026-01-03 00:00:00"); insertLegacy("latest-heartbeat", "ns", 200, "2026-01-01 00:00:00"); insertLegacy("tie-a", "ns-tie", 0, "2026-01-01 00:00:00"); diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/MockRequestHeaderMigrationTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/MockRequestHeaderMigrationTest.java index 369065871fb5..e019ff07f114 100644 --- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/MockRequestHeaderMigrationTest.java +++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mapper/MockRequestHeaderMigrationTest.java @@ -74,6 +74,8 @@ public void testMigrationPreservesLegacyDataAndAcceptsLongHeaders() throws Excep statement.execute("CREATE TABLE rule (loged INT)"); statement.execute("CREATE TABLE instance_info (id VARCHAR(128), namespace_id VARCHAR(50), instance_ip VARCHAR(128)," + "instance_port VARCHAR(128), instance_type VARCHAR(128), last_heart_beat_time BIGINT, date_updated TIMESTAMP, date_created TIMESTAMP)"); + statement.execute("CREATE TABLE plugin (id VARCHAR(128), name VARCHAR(128), sort INT)"); + statement.execute("CREATE TABLE namespace_plugin_rel (plugin_id VARCHAR(128), sort INT)"); new ResourceDatabasePopulator(new FileSystemResource(upgradeScript())).execute(dataSource); MockRequestRecordDO restored = mapper.queryById("legacy"); From 361ee7549ae4265a86a1ebf3bd1efffb744d595f Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Wed, 28 Oct 2026 09:51:41 +0800 Subject: [PATCH 18/36] fix(agent-gateway): preserve admission state across reloads --- .../protocol/AgentMcpResourceAdmission.java | 13 +++--- .../protocol/AgentResourceAdmission.java | 34 ++++++++++++-- .../protocol/AgentResourceAdmissionTest.java | 29 ++++++++++-- .../proxy/enhanced/service/AiProxyEngine.java | 12 +++-- .../AiProxyEngineOrchestrationTest.java | 6 +-- ...gentGatewayAdmissionControllerService.java | 2 +- .../AgentGatewayPluginConfiguration.java | 7 +-- .../AgentGatewayPluginConfigurationTest.java | 46 +++++++++++++++++++ 8 files changed, 125 insertions(+), 24 deletions(-) diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java index 502ae72dfe47..5de88a82121b 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java @@ -87,7 +87,9 @@ public Mono withRemote(final String server, final Instant deadline, final } /** - * Atomically install new limits and close only the retired active controller. + * Apply replacement limits without replacing the shared accounting state. + * Requests owned by the active controller remain admitted or queued across reloads. + * * @param replacement validated replacement controller */ public void replace(final ResourceAdmissionController replacement) { @@ -96,12 +98,11 @@ public void replace(final ResourceAdmissionController replacement) { replacement.delegate.close(); return; } - AgentResourceAdmission retired; - synchronized (this) { - retired = current; - current = replacement.delegate; + try { + current.updateLimits(replacement.delegate); + } finally { + replacement.delegate.close(); } - retired.close(); } @Override diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java index 5a57197a14c0..dffcc70a83ff 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java @@ -33,7 +33,7 @@ /** Deterministic gateway resource admission with bounded deadline-aware queues. */ public final class AgentResourceAdmission implements AutoCloseable { - private final AgentGatewayAdmissionConfig config; + private volatile AgentGatewayAdmissionConfig config; private final Scope global; @@ -135,6 +135,26 @@ public AgentGatewayAdmissionConfig config() { return config; } + /** + * Apply new limits to the same accounting state. Requests already admitted or queued + * remain owned by this controller, so a configuration reload cannot reset their permits. + * + * @param replacement trusted controller whose validated configuration is applied + */ + void updateLimits(final AgentResourceAdmission replacement) { + Objects.requireNonNull(replacement, "replacement"); + if (closed) { + throw new IllegalStateException("Admission controller is closed"); + } + final AgentGatewayAdmissionConfig replacementConfig = replacement.config(); + synchronized (remotes) { + config = replacementConfig; + global.updateLimits(replacementConfig.globalInFlight(), replacementConfig.globalQueued()); + local.updateLimits(replacementConfig.localInFlight(), replacementConfig.localQueued()); + remotes.forEach(scope -> scope.updateLimits(replacementConfig.remoteInFlight(), replacementConfig.remoteQueued())); + } + } + /** * Whether this controller has already been closed. * @return terminal close state @@ -210,9 +230,9 @@ private static final class Scope { private final String name; - private final int inFlightLimit; + private int inFlightLimit; - private final int queueLimit; + private int queueLimit; private final AtomicLong rejected = new AtomicLong(); @@ -319,6 +339,14 @@ AgentAdmissionMetrics.Snapshot snapshot(final AgentAdmissionMetrics.Scope scope) return new AgentAdmissionMetrics.Snapshot(scope, inFlight, queued, inFlightLimit, queueLimit, rejected.get()); } } + + void updateLimits(final int inFlightLimit, final int queueLimit) { + synchronized (lock) { + this.inFlightLimit = inFlightLimit; + this.queueLimit = queueLimit; + promote(); + } + } } private static final class Waiter { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java index 99705c594d1a..c2b4b22726b2 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java @@ -151,7 +151,7 @@ void releasePermitsExactlyOnceOnTerminalPaths() throws Exception { } @Test - void replacingControllerRetiresOldMetricsAndKeepsNewLimits() { + void replacingControllerKeepsSharedAccountingAndAppliesNewLimits() { AgentMcpResourceAdmission.ResourceAdmissionController first = AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 1, 1, 1, 1, 1)); AgentMcpResourceAdmission.ResourceAdmissionController second = @@ -161,14 +161,14 @@ void replacingControllerRetiresOldMetricsAndKeepsNewLimits() { List snapshots = AgentAdmissionMetrics.snapshots(); assertEquals(2, snapshots.size()); assertEquals(2, snapshots.stream().filter(state -> state.scope() == AgentAdmissionMetrics.Scope.GLOBAL) - .mapToInt(AgentAdmissionMetrics.Snapshot::inFlightLimit).sum()); + .mapToInt(AgentAdmissionMetrics.Snapshot::inFlightLimit).sum(), "replacement metrics must stay retired"); } finally { first.close(); } } @Test - void everyReplacementBecomesActiveAndFinalCloseRemovesMetrics() throws Exception { + void everyReplacementUpdatesActiveControllerAndFinalCloseRemovesMetrics() throws Exception { AgentMcpResourceAdmission.ResourceAdmissionController controller = AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 1, 1, 1, 1, 1)); try { @@ -197,6 +197,29 @@ void everyReplacementBecomesActiveAndFinalCloseRemovesMetrics() throws Exception .noneMatch(snapshot -> snapshot.inFlightLimit() == 3), "active admission metrics must be removed after close"); } + @Test + void unchangedReplacementDoesNotResetActiveRequestAccounting() throws Exception { + AgentMcpResourceAdmission.ResourceAdmissionController controller = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 0, 1, 0, 1, 0)); + Sinks.Empty active = Sinks.empty(); + try { + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), active.asMono())) + .expectComplete().verifyLater(); + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + controller.replace(AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 0, 1, 0, 1, 0))); + AtomicInteger calls = new AtomicInteger(); + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), Mono.fromCallable(calls::incrementAndGet))) + .expectError(AgentResourceAdmission.AgentAdmissionException.class).verify(Duration.ofSeconds(2)); + assertEquals(0, calls.get()); + assertEquals(1, controller.snapshot().stream() + .filter(snapshot -> snapshot.scope() == AgentAdmissionMetrics.Scope.GLOBAL) + .findFirst().orElseThrow().inFlight()); + } finally { + active.tryEmitEmpty(); + controller.close(); + } + } + @Test void redundantReplacementIsClosedWithoutReplacingActiveLimits() { AgentMcpResourceAdmission.ResourceAdmissionController active = diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java index a251ceea2eb0..16876f6ca8f2 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java @@ -78,6 +78,7 @@ public final class AiProxyEngine { private final AiProxyRetryProperties retryProperties; private final AiCallObserver observer; + private final AiProxyAttemptListener attemptListener; public AiProxyEngine(final AiProxyProtocolFactory protocols, final AiProxyProviderFactory providers, final AiProxyTransport transport) { @@ -126,7 +127,7 @@ public AiProxyEngine( public AiProxyEngine(final AiProxyProtocolFactory protocols, final AiProxyProviderFactory providers, final AiProtocolRouteResolver routeResolver, final AiProxyTransport transport, final AiProxyRetryProperties retryProperties) { - this(protocols, providers, routeResolver, transport, retryProperties, event -> { + this(protocols, providers, routeResolver, transport, retryProperties, (AiProxyAttemptListener) event -> { }); } @@ -483,16 +484,16 @@ private Mono consumeResponse( private PreparedExchange prepare(final String requestBody, final AiCommonConfig config) { if (Objects.isNull(requestBody) || requestBody.isBlank()) { - throw new ShenyuException("AI request body must not be empty"); + throw new AiProxyException(AiProxyException.Kind.REQUEST, "AI request body must not be empty", null); } final JsonNode root; try { root = OBJECT_MAPPER.readTree(requestBody); } catch (JsonProcessingException error) { - throw new ShenyuException("AI request body must be valid JSON", error); + throw new AiProxyException(AiProxyException.Kind.REQUEST, "AI request body must be valid JSON", error); } if (!root.isObject()) { - throw new ShenyuException("AI request body must be a JSON object"); + throw new AiProxyException(AiProxyException.Kind.REQUEST, "AI request body must be a JSON object", null); } ObjectNode payload = (ObjectNode) root; String upstreamBody = requestBody; @@ -503,7 +504,8 @@ private PreparedExchange prepare(final String requestBody, final AiCommonConfig AiProxyProtocol protocol = Objects.isNull(config.getProtocol()) || config.getProtocol().isBlank() ? aiProxyProtocolFactory.detect(payload) : aiProxyProtocolFactory.getProtocol(config.getProtocol()); if (!protocol.matches(payload)) { - throw new ShenyuException("Request body does not match AI protocol: " + protocol.name()); + throw new AiProxyException(AiProxyException.Kind.REQUEST, + "Request body does not match AI protocol: " + protocol.name(), null); } ShenyuAiRequest decoded = applyModelOverride(protocol.decodeRequest(upstreamBody, payload), protocol, config); AiProxyProvider provider = aiProxyProviderFactory.getProvider(providerName(config)); diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java index adcff7a737d4..540da315c9b8 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java @@ -280,7 +280,7 @@ void attemptListenerReceivesBoundedIdentityAndReasons() { return attempt == 1 ? Mono.just(response(429, Map.of("Retry-After", List.of("1")), Flux.just(bytes("busy")))) : Mono.just(response(200, Flux.just(bytes("ok")))); - }, retryProperties(Duration.ZERO, Duration.ofMinutes(1)), events::add); + }, retryProperties(Duration.ZERO, Duration.ofMinutes(1)), (AiProxyAttemptListener) events::add); StepVerifier.create(engine.execute(BODY, config(false, "main"), Optional.empty(), response -> response.getBody().then())).verifyComplete(); @@ -304,7 +304,7 @@ void fallbackAttemptsKeepThePrimaryAttemptIndexSequence() { return body.contains("\"model\":\"fallback\"") ? Mono.just(response(200, Flux.just(bytes("fallback response")))) : Mono.just(response(429, Flux.just(bytes("busy")))); - }, properties, events::add); + }, properties, (AiProxyAttemptListener) events::add); StepVerifier.create(engine.execute(BODY, config(false, "main"), Optional.of(config(false, "fallback")), response -> response.getBody().then())) @@ -616,7 +616,7 @@ void neverRetriesOrFallsBackAfterBodyEmission() { protocolRouteResolver(), request -> { calls.incrementAndGet(); return Mono.just(response(200, Flux.just(bytes("data: {\"first\":true}\n\n")).concatWith(Flux.error(networkFailure())))); - }, retryProperties(Duration.ZERO, Duration.ofMinutes(1)), events::add); + }, retryProperties(Duration.ZERO, Duration.ofMinutes(1)), (AiProxyAttemptListener) events::add); StepVerifier.create(engine.execute(BODY, config(true, "main"), Optional.of(config(true, "fallback")), response -> consume(response, received))) .expectError(AiTransportException.class).verify(); assertEquals(1, calls.get()); diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayAdmissionControllerService.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayAdmissionControllerService.java index 53def109ae92..b617fb33b623 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayAdmissionControllerService.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayAdmissionControllerService.java @@ -31,7 +31,7 @@ public final class AgentGatewayAdmissionControllerService { } /** - * Validate and atomically replace the active controller. + * Validate limits and atomically update the active controller's accounting state. * @param source complete trusted plugin configuration * @return immutable active limits */ diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java index 418f6c3175c1..4c00b134ae7a 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java @@ -152,12 +152,13 @@ public PluginDataHandler agentGatewayPluginDataHandler(final ObjectProvider { - if (java.util.Objects.nonNull(admission)) { - admission.update(java.util.Objects.requireNonNull(plugin.getConfig(), "{}")); - } if (java.util.Objects.nonNull(catalog)) { catalog.accept(plugin); } + if (java.util.Objects.nonNull(admission)) { + String config = plugin.getConfig(); + admission.update(java.util.Objects.isNull(config) || config.isBlank() ? "{}" : config); + } }); } diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java index 89f33b77050d..f22a18b43114 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java @@ -35,11 +35,13 @@ import org.apache.shenyu.common.dto.PluginData; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; +import org.apache.shenyu.plugin.agent.gateway.remote.ManagedRemoteMcpCatalog; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.shenyu.plugin.api.ShenyuPlugin; import org.apache.shenyu.plugin.base.handler.PluginDataHandler; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; @@ -50,6 +52,7 @@ import java.util.Set; import java.util.List; +import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -61,8 +64,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doAnswer; import static org.mockito.ArgumentMatchers.any; class AgentGatewayPluginConfigurationTest { @@ -308,6 +314,9 @@ public Mono invoke(final org.apache.shenyu.plugin.agent.gateway.tool final Future first = executor.submit(() -> StepVerifier.create(handler.handle(firstExchange, config, new AgentTrafficContext("first", "mcp", "selector", "rule"), 1)).verifyComplete()); awaitLocalInFlight(admission, 1); + context.getBean(PluginDataHandler.class).handlerPlugin(pluginData("{\"admission\":{" + + "\"globalInFlight\":8,\"globalQueued\":4,\"localInFlight\":1,\"localQueued\":0," + + "\"remoteInFlight\":2,\"remoteQueued\":2}}")); MockServerWebExchange rejectedExchange = exchange(); StepVerifier.create(handler.handle(rejectedExchange, config, new AgentTrafficContext("second", "mcp", "selector", "rule"), 1)) @@ -343,6 +352,43 @@ private PluginData pluginData(final String config) { return plugin; } + @Test + void pluginRemovalAndBlankConfigStillReachCatalogAndAdmission() { + ManagedRemoteMcpCatalog catalog = mock(ManagedRemoteMcpCatalog.class); + List events = new ArrayList<>(); + doAnswer(invocation -> events.add(invocation.getArgument(0, PluginData.class))) + .when(catalog).accept(any(PluginData.class)); + try (AgentMcpResourceAdmission.ResourceAdmissionController controller = + AgentMcpResourceAdmission.create(new org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig( + 8, 4, 4, 2, 2, 2))) { + AgentGatewayAdmissionControllerService admission = new AgentGatewayAdmissionControllerService(controller); + PluginDataHandler handler = new AgentGatewayPluginConfiguration() + .agentGatewayPluginDataHandler(provider(catalog), provider(admission)); + + handler.removePlugin(new PluginData()); + handler.handlerPlugin(pluginData(" ")); + + assertEquals(2, events.size()); + assertEquals(Boolean.FALSE, events.get(0).getEnabled()); + assertNull(events.get(0).getConfig()); + assertEquals(128, controller.config().globalInFlight()); + assertEquals(32, controller.config().localInFlight()); + + PluginData invalid = pluginData("{\"admission\":{\"globalInFlight\":999,\"globalQueued\":4," + + "\"localInFlight\":4,\"localQueued\":2,\"remoteInFlight\":2,\"remoteQueued\":2}}"); + assertThrows(IllegalArgumentException.class, () -> handler.handlerPlugin(invalid)); + assertEquals(3, events.size()); + assertSame(invalid, events.get(2)); + } + } + + @SuppressWarnings("unchecked") + private ObjectProvider provider(final T value) { + ObjectProvider provider = mock(ObjectProvider.class); + when(provider.getIfAvailable()).thenReturn(value); + return provider; + } + @Test void shouldFailAssemblyForAmbiguousSecurityAdapters() { contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true") From 220521aa6ed704b92f2e196c8bbc2d3e8529e923 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Wed, 28 Oct 2026 16:12:13 +0800 Subject: [PATCH 19/36] fix(agent-gateway): drain admission queues after limit reloads --- .../protocol/AgentResourceAdmission.java | 61 +++++---- .../protocol/AgentResourceAdmissionTest.java | 120 +++++++++++++++++- 2 files changed, 149 insertions(+), 32 deletions(-) diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java index dffcc70a83ff..a33498e6d084 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java @@ -41,14 +41,16 @@ public final class AgentResourceAdmission implements AutoCloseable { private final Deque remotes = new ArrayDeque<>(); + private final Object promotionLock = new Object(); + private final AgentAdmissionMetrics registration; private volatile boolean closed; public AgentResourceAdmission(final AgentGatewayAdmissionConfig config) { this.config = Objects.requireNonNull(config, "config"); - global = new Scope("global", config.globalInFlight(), config.globalQueued()); - local = new Scope("local", config.localInFlight(), config.localQueued()); + global = new Scope("global", promotionLock, config.globalInFlight(), config.globalQueued()); + local = new Scope("local", promotionLock, config.localInFlight(), config.localQueued()); registration = AgentAdmissionMetrics.register(this::snapshot); } @@ -109,7 +111,7 @@ private Scope remote(final String name) { return scope; } } - Scope scope = new Scope(name, config.remoteInFlight(), config.remoteQueued()); + Scope scope = new Scope(name, promotionLock, config.remoteInFlight(), config.remoteQueued()); remotes.add(scope); return scope; } @@ -147,12 +149,17 @@ void updateLimits(final AgentResourceAdmission replacement) { throw new IllegalStateException("Admission controller is closed"); } final AgentGatewayAdmissionConfig replacementConfig = replacement.config(); - synchronized (remotes) { - config = replacementConfig; - global.updateLimits(replacementConfig.globalInFlight(), replacementConfig.globalQueued()); - local.updateLimits(replacementConfig.localInFlight(), replacementConfig.localQueued()); - remotes.forEach(scope -> scope.updateLimits(replacementConfig.remoteInFlight(), replacementConfig.remoteQueued())); + synchronized (promotionLock) { + synchronized (remotes) { + config = replacementConfig; + global.installLimits(replacementConfig.globalInFlight(), replacementConfig.globalQueued()); + local.installLimits(replacementConfig.localInFlight(), replacementConfig.localQueued()); + remotes.forEach(scope -> scope.installLimits(replacementConfig.remoteInFlight(), replacementConfig.remoteQueued())); + } } + global.promote(); + local.promote(); + remotes.forEach(Scope::promote); } /** @@ -238,6 +245,8 @@ private static final class Scope { private final Object lock = new Object(); + private final Object promotionLock; + private final Deque waiting = new ArrayDeque<>(); private int inFlight; @@ -246,8 +255,9 @@ private static final class Scope { private boolean closed; - private Scope(final String name, final int inFlightLimit, final int queueLimit) { + private Scope(final String name, final Object promotionLock, final int inFlightLimit, final int queueLimit) { this.name = name; + this.promotionLock = promotionLock; this.inFlightLimit = inFlightLimit; this.queueLimit = queueLimit; } @@ -278,20 +288,21 @@ AcquireResult acquire(final Instant deadline) { } void release(final Wait wait) { - if (Objects.isNull(wait.waiter)) { - completeActive(wait); - return; - } - boolean promoted; - synchronized (lock) { - promoted = wait.waiter.state == State.PROMOTED; - if (wait.waiter.state == State.WAITING && waiting.remove(wait.waiter)) { - queued--; - rejected.incrementAndGet(); - } - wait.waiter.completeExceptionally(AgentAdmissionException.deadline()); - if (promoted) { - completeActive(wait); + synchronized (promotionLock) { + synchronized (lock) { + if (Objects.isNull(wait.waiter)) { + completeActive(wait); + return; + } + boolean promoted = wait.waiter.state == State.PROMOTED; + if (wait.waiter.state == State.WAITING && waiting.remove(wait.waiter)) { + queued--; + rejected.incrementAndGet(); + } + wait.waiter.completeExceptionally(AgentAdmissionException.deadline()); + if (promoted) { + completeActive(wait); + } } } } @@ -317,7 +328,6 @@ private void promote() { } inFlight++; next.complete(); - return; } } @@ -340,11 +350,10 @@ AgentAdmissionMetrics.Snapshot snapshot(final AgentAdmissionMetrics.Scope scope) } } - void updateLimits(final int inFlightLimit, final int queueLimit) { + void installLimits(final int inFlightLimit, final int queueLimit) { synchronized (lock) { this.inFlightLimit = inFlightLimit; this.queueLimit = queueLimit; - promote(); } } } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java index c2b4b22726b2..ffc8a8986354 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java @@ -28,6 +28,7 @@ import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -220,6 +221,93 @@ void unchangedReplacementDoesNotResetActiveRequestAccounting() throws Exception } } + @Test + void localLimitReloadInstallsBeforePromotingQueuedRequests() throws Exception { + AgentMcpResourceAdmission.ResourceAdmissionController controller = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 4, 1, 0, 1, 4)); + List> actions = new ArrayList<>(); + try { + for (int i = 0; i < 4; i++) { + Sinks.Empty action = Sinks.empty(); + actions.add(action); + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), action.asMono())) + .expectComplete().verifyLater(); + if (i == 0) { + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + } + } + awaitQueued(controller, AgentAdmissionMetrics.Scope.GLOBAL, 3); + + controller.replace(AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(4, 4, 4, 4, 1, 4))); + + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 4); + awaitActive(controller, AgentAdmissionMetrics.Scope.LOCAL, 4); + assertEquals(0, snapshot(controller, AgentAdmissionMetrics.Scope.GLOBAL).queued()); + assertEquals(0, snapshot(controller, AgentAdmissionMetrics.Scope.LOCAL).queued()); + } finally { + actions.forEach(Sinks.Empty::tryEmitEmpty); + controller.close(); + } + } + + @Test + void remoteLimitReloadInstallsBeforePromotingQueuedRequests() throws Exception { + AgentMcpResourceAdmission.ResourceAdmissionController controller = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 4, 4, 4, 1, 0)); + List> actions = new ArrayList<>(); + try { + for (int i = 0; i < 4; i++) { + Sinks.Empty action = Sinks.empty(); + actions.add(action); + StepVerifier.create(controller.withRemote("orders", Instant.now().plusSeconds(2), action.asMono())) + .expectComplete().verifyLater(); + if (i == 0) { + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + } + } + awaitQueued(controller, AgentAdmissionMetrics.Scope.GLOBAL, 3); + + controller.replace(AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(4, 4, 4, 4, 4, 4))); + + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 4); + awaitActive(controller, AgentAdmissionMetrics.Scope.REMOTE, 4); + assertEquals(0, snapshot(controller, AgentAdmissionMetrics.Scope.GLOBAL).queued()); + assertEquals(0, snapshot(controller, AgentAdmissionMetrics.Scope.REMOTE).queued()); + } finally { + actions.forEach(Sinks.Empty::tryEmitEmpty); + controller.close(); + } + } + + @Test + void globalLimitReloadPromotesAllNewlyAvailableWaiters() throws Exception { + AgentMcpResourceAdmission.ResourceAdmissionController controller = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 4, 4, 4, 4, 4)); + List> actions = new ArrayList<>(); + try { + for (int i = 0; i < 4; i++) { + Sinks.Empty action = Sinks.empty(); + actions.add(action); + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), action.asMono())) + .expectComplete().verifyLater(); + if (i == 0) { + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + } + } + awaitQueued(controller, AgentAdmissionMetrics.Scope.GLOBAL, 3); + + controller.replace(AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(4, 4, 4, 4, 4, 4))); + + AgentAdmissionMetrics.Snapshot global = snapshot(controller, AgentAdmissionMetrics.Scope.GLOBAL); + assertEquals(4, global.inFlight()); + assertEquals(0, global.queued()); + assertEquals(4, snapshot(controller, AgentAdmissionMetrics.Scope.LOCAL).inFlight()); + } finally { + actions.forEach(Sinks.Empty::tryEmitEmpty); + controller.close(); + } + } + @Test void redundantReplacementIsClosedWithoutReplacingActiveLimits() { AgentMcpResourceAdmission.ResourceAdmissionController active = @@ -257,24 +345,44 @@ private static void await(final AgentResourceAdmission controller, final AgentAd assertTrue(false, "admission permit was not acquired"); } - private static void awaitActive(final AgentMcpResourceAdmission.ResourceAdmissionController controller, - final AgentAdmissionMetrics.Scope scope, final int expected) throws InterruptedException { + private static void awaitQueued(final AgentResourceAdmission controller, final int expected) throws InterruptedException { for (int i = 0; i < 200; i++) { - if (controller.snapshot().stream().anyMatch(state -> state.scope() == scope && state.inFlight() >= expected)) { + if (controller.snapshot().stream().mapToInt(AgentAdmissionMetrics.Snapshot::queued).max().orElse(0) == expected) { return; } TimeUnit.MILLISECONDS.sleep(10); } - assertTrue(false, "admission permit was not acquired"); + assertTrue(false, "admission waiter was not queued"); } - private static void awaitQueued(final AgentResourceAdmission controller, final int expected) throws InterruptedException { + private static void awaitQueued(final AgentMcpResourceAdmission.ResourceAdmissionController controller, + final AgentAdmissionMetrics.Scope scope, + final int expected) throws InterruptedException { for (int i = 0; i < 200; i++) { - if (controller.snapshot().stream().mapToInt(AgentAdmissionMetrics.Snapshot::queued).max().orElse(0) == expected) { + if (snapshot(controller, scope).queued() == expected) { return; } TimeUnit.MILLISECONDS.sleep(10); } assertTrue(false, "admission waiter was not queued"); } + + private static AgentAdmissionMetrics.Snapshot snapshot(final AgentMcpResourceAdmission.ResourceAdmissionController controller, + final AgentAdmissionMetrics.Scope scope) { + return controller.snapshot().stream() + .filter(state -> state.scope() == scope) + .findFirst() + .orElseThrow(); + } + + private static void awaitActive(final AgentMcpResourceAdmission.ResourceAdmissionController controller, + final AgentAdmissionMetrics.Scope scope, final int expected) throws InterruptedException { + for (int i = 0; i < 200; i++) { + if (controller.snapshot().stream().anyMatch(state -> state.scope() == scope && state.inFlight() >= expected)) { + return; + } + TimeUnit.MILLISECONDS.sleep(10); + } + assertTrue(false, "admission permit was not acquired"); + } } From 98b1f423ad3204fba4fcdfa193a77fc912db1434 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Wed, 28 Oct 2026 21:55:00 +0800 Subject: [PATCH 20/36] fix(agent-gateway): synchronize admission queue promotion --- .../protocol/AgentResourceAdmission.java | 26 +++--- .../protocol/AgentResourceAdmissionTest.java | 85 ++++++++++++++++++- 2 files changed, 98 insertions(+), 13 deletions(-) diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java index a33498e6d084..f530ce5aa310 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java @@ -315,19 +315,21 @@ private void completeActive(final Wait wait) { } private void promote() { - while (inFlight < inFlightLimit) { - Waiter next = waiting.pollFirst(); - if (Objects.isNull(next)) { - return; - } - queued--; - if (!Instant.now().isBefore(next.deadline) || closed) { - rejected.incrementAndGet(); - next.completeExceptionally(AgentAdmissionException.deadline()); - continue; + synchronized (lock) { + while (inFlight < inFlightLimit) { + Waiter next = waiting.pollFirst(); + if (Objects.isNull(next)) { + return; + } + queued--; + if (!Instant.now().isBefore(next.deadline) || closed) { + rejected.incrementAndGet(); + next.completeExceptionally(AgentAdmissionException.deadline()); + continue; + } + inFlight++; + next.complete(); } - inFlight++; - next.complete(); } } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java index ffc8a8986354..2192d2577349 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java @@ -30,13 +30,17 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -189,7 +193,7 @@ void everyReplacementUpdatesActiveControllerAndFinalCloseRemovesMetrics() throws } finally { executor.shutdownNow(); } - StepVerifier.create(controller.withLocal(Instant.now(), Mono.just("third"))).expectNext("third").verifyComplete(); + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), Mono.just("third"))).expectNext("third").verifyComplete(); } finally { controller.close(); } @@ -308,6 +312,70 @@ void globalLimitReloadPromotesAllNewlyAvailableWaiters() throws Exception { } } + @Test + void globalLimitReloadDoesNotRaceDirectSubscriptions() throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(3); + try { + for (int trial = 0; trial < 100; trial++) { + AgentMcpResourceAdmission.ResourceAdmissionController controller = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 4, 4, 4, 4, 4)); + List> actions = new ArrayList<>(); + AtomicReference failure = new AtomicReference<>(); + for (int i = 0; i < 4; i++) { + actions.add(Sinks.empty()); + } + subscribe(controller, actions.get(0), failure); + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + subscribe(controller, actions.get(1), failure); + awaitQueued(controller, AgentAdmissionMetrics.Scope.GLOBAL, 1); + + CyclicBarrier barrier = new CyclicBarrier(3); + CountDownLatch finished = new CountDownLatch(3); + executor.execute(() -> { + await(barrier); + try { + controller.replace(AgentMcpResourceAdmission.create( + new AgentGatewayAdmissionConfig(3, 4, 4, 4, 4, 4))); + } finally { + finished.countDown(); + } + }); + executor.execute(() -> { + await(barrier); + try { + subscribe(controller, actions.get(2), failure); + } finally { + finished.countDown(); + } + }); + executor.execute(() -> { + await(barrier); + try { + subscribe(controller, actions.get(3), failure); + } finally { + finished.countDown(); + } + }); + assertTrue(finished.await(5, TimeUnit.SECONDS)); + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 3); + + AgentAdmissionMetrics.Snapshot global = snapshot(controller, AgentAdmissionMetrics.Scope.GLOBAL); + assertEquals(3, global.inFlightLimit()); + assertTrue(global.inFlight() <= 3, "reload and direct subscriptions admitted " + global.inFlight() + " actions"); + assertEquals(1, global.queued()); + assertEquals(3, snapshot(controller, AgentAdmissionMetrics.Scope.LOCAL).inFlight()); + assertNull(failure.get()); + + actions.forEach(Sinks.Empty::tryEmitEmpty); + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 0); + awaitQueued(controller, AgentAdmissionMetrics.Scope.GLOBAL, 0); + controller.close(); + } + } finally { + executor.shutdownNow(); + } + } + @Test void redundantReplacementIsClosedWithoutReplacingActiveLimits() { AgentMcpResourceAdmission.ResourceAdmissionController active = @@ -345,6 +413,14 @@ private static void await(final AgentResourceAdmission controller, final AgentAd assertTrue(false, "admission permit was not acquired"); } + private static void await(final CyclicBarrier barrier) { + try { + barrier.await(5, TimeUnit.SECONDS); + } catch (Exception e) { + throw new IllegalStateException("concurrent admission workers did not start together", e); + } + } + private static void awaitQueued(final AgentResourceAdmission controller, final int expected) throws InterruptedException { for (int i = 0; i < 200; i++) { if (controller.snapshot().stream().mapToInt(AgentAdmissionMetrics.Snapshot::queued).max().orElse(0) == expected) { @@ -385,4 +461,11 @@ private static void awaitActive(final AgentMcpResourceAdmission.ResourceAdmissio } assertTrue(false, "admission permit was not acquired"); } + + private static void subscribe(final AgentMcpResourceAdmission.ResourceAdmissionController controller, + final Sinks.Empty action, + final AtomicReference failure) { + controller.withLocal(Instant.now().plusSeconds(2), action.asMono()) + .subscribe(ignored -> { }, error -> failure.compareAndSet(null, error)); + } } From 6c14893fb5f5816ca9a3dfea3a17d3acdf3fd3e4 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Fri, 30 Oct 2026 11:39:46 +0800 Subject: [PATCH 21/36] fix(agent-gateway): record local attempts only after admission --- docs/agent-gateway-resource-admission.md | 1 + .../agent/gateway/tool/AgentToolRegistry.java | 10 ++-- .../AgentMcpTerminalObservationTest.java | 43 ++++++++++++++++- .../gateway/tool/AgentToolRegistryTest.java | 48 +++++++++++++++++++ 4 files changed, 97 insertions(+), 5 deletions(-) diff --git a/docs/agent-gateway-resource-admission.md b/docs/agent-gateway-resource-admission.md index 11221a9aef4f..95d7bbe8a828 100644 --- a/docs/agent-gateway-resource-admission.md +++ b/docs/agent-gateway-resource-admission.md @@ -29,6 +29,7 @@ Omitting the object or supplying an empty object selects these defaults. Admin a - Admission checks the absolute request deadline before granting each global/local/remote permit, before reporting queue overflow, and immediately before subscribing to execution. An already-expired request never executes its provider, even with free capacity. Time spent waiting counts against execution time. - Queue overflow returns HTTP `429` and JSON-RPC `-32026`; an expired request returns HTTP `504` and `-32026`. - Every success, business error, gateway error, cancellation, timeout, configuration withdrawal and shutdown releases each acquired permit once. +- Local validation runs before resource admission. The execution-attempt callback and provider invocation run only when the admitted action is subscribed. Overload, queue timeout and cancellation before admission produce no execution-attempt audit record; their logical terminal record remains available. - Existing byte limits, transport concurrency, catalog generation leases and no-retry behavior remain in force. Configuration reload preserves active and queued accounting. All scope limits are installed before newly available slots are drained. Reload draining, terminal release and shutdown follow the same controller-promotion-monitor then scope-monitor order, including synchronous completion of promoted actions. Remote scope collections are copied under their registry monitor before callbacks or snapshot reads acquire scope monitors. diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java index 32d334ea413e..9359c1c644dc 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java @@ -159,8 +159,8 @@ public Mono invoke(final String name, final Set allowedTools * @param name tool name * @param allowedTools effective permissions * @param input request-local invocation factory - * @param onAttempt nonblocking callback before provider execution - * @param executionWrapper admission or lifecycle boundary around one execution + * @param onAttempt nonblocking callback when the admitted execution is subscribed + * @param executionWrapper admission or lifecycle boundary around notification and provider execution * @return request-local result */ public Mono invoke(final String name, final Set allowedTools, @@ -184,8 +184,10 @@ public Mono invoke(final String name, final Set allowedTools } catch (IllegalArgumentException error) { throw new AgentToolArgumentException(error); } - onAttempt.run(); - return executionWrapper.apply(provider.invoke(invocation)) + return executionWrapper.apply(Mono.defer(() -> { + onAttempt.run(); + return provider.invoke(invocation); + })) .switchIfEmpty(Mono.error(new IllegalStateException("Tool completed without a result"))) .map(JsonObject::deepCopy); }); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java index 64de4b5bd6a6..cfd7ed248288 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpTerminalObservationTest.java @@ -23,6 +23,7 @@ import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; import org.apache.shenyu.common.constant.Constants; import org.apache.shenyu.common.dto.AgentGatewayMcpConfig; +import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; import org.apache.shenyu.common.dto.AgentRequestContext; import org.apache.shenyu.common.metrics.AgentMcpCallObserver; import org.apache.shenyu.common.metrics.AgentMcpCallObserver.Outcome; @@ -101,6 +102,42 @@ void auditUsesActualAttemptAndTerminalOwner() { assertTrue(events.get(0).getSubject().isEmpty()); } + @ParameterizedTest + @ValueSource(strings = {"global", "local", "timeout"}) + void localAdmissionRejectionOnlyProducesLogicalAudit(final String scenario) { + boolean queued = "timeout".equals(scenario); + AgentMcpResourceAdmission.ResourceAdmissionController admission = AgentMcpResourceAdmission.create( + new AgentGatewayAdmissionConfig("local".equals(scenario) ? 2 : 1, queued ? 1 : 0, 1, 0, 1, 0)); + reactor.core.Disposable active = admission.withLocal(java.time.Instant.now().plusSeconds(30), Mono.never()).subscribe(); + AtomicInteger calls = new AtomicInteger(); + List events = new java.util.concurrent.CopyOnWriteArrayList<>(); + AgentMcpHttpHandler handler = new AgentMcpHttpHandler(dispatcher(Mono.fromSupplier(() -> { + calls.incrementAndGet(); + return new JsonObject(); + }), admission), identity(), null, AgentInvocationAuditBridge.mcp(null, events::add)); + try { + MockServerWebExchange rejected = exchange("tools/call"); + StepVerifier.create(handler.handle(rejected, config("json", queued ? 150 : 30000), traffic, 7)) + .verifyComplete(); + assertEquals(queued ? 504 : 429, rejected.getResponse().getStatusCode().value()); + assertEquals(0, calls.get()); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals(1, events.size())); + assertEquals(AgentInvocationAuditEvent.RecordType.LOGICAL, events.get(0).getRecordType()); + assertEquals(queued ? "TIMEOUT" : "REJECTED", events.get(0).getOutcome()); + active.dispose(); + events.clear(); + StepVerifier.create(handler.handle(exchange("tools/call"), config("json", 30000), traffic, 7)).verifyComplete(); + assertEquals(1, calls.get()); + await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals(2, events.size())); + assertEquals(List.of(AgentInvocationAuditEvent.RecordType.ATTEMPT, AgentInvocationAuditEvent.RecordType.LOGICAL), + events.stream().map(AgentInvocationAuditEvent::getRecordType).toList()); + assertTrue(events.stream().allMatch(event -> "SUCCESS".equals(event.getOutcome()))); + } finally { + active.dispose(); + admission.close(); + } + } + @ParameterizedTest @ValueSource(strings = {"missing", "long", " padded", "padded ", "control\nname", "delete-control"}) void deniedToolCallsPreserveLogicalAuditForInvalidTargetMetadata(final String input) { @@ -556,13 +593,17 @@ private AgentMcpHttpHandler handler(final Mono action, final AgentMc } private AgentMcpDispatcher dispatcher(final Mono action) { + return dispatcher(action, AgentMcpResourceAdmission.NOOP); + } + + private AgentMcpDispatcher dispatcher(final Mono action, final AgentMcpResourceAdmission admission) { AgentToolProvider tool = mock(AgentToolProvider.class); when(tool.getName()).thenReturn("read"); when(tool.getDescription()).thenReturn("Read test data"); when(tool.getInputSchema()).thenReturn(JsonParser.parseString("{\"type\":\"object\"}").getAsJsonObject()); when(tool.getRequiredClientCapabilities()).thenReturn(new JsonObject()); when(tool.invoke(any())).thenReturn(action); - return new AgentMcpDispatcher(new AgentToolRegistry(List.of(tool)), "test", "1"); + return new AgentMcpDispatcher(new AgentToolRegistry(List.of(tool)), "test", "1", null, admission); } private AgentMcpSecurityResolver identity() { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistryTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistryTest.java index ee3fd851cb20..90900ec0d399 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistryTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistryTest.java @@ -18,7 +18,11 @@ package org.apache.shenyu.plugin.agent.gateway.tool; import com.google.gson.JsonObject; +import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentResourceAdmission; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; @@ -26,6 +30,7 @@ import reactor.test.StepVerifier; import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -49,6 +54,49 @@ void shouldRejectDuplicateNames() { assertThrows(IllegalArgumentException.class, () -> new AgentToolRegistry(List.of(tool, tool))); } + @ParameterizedTest + @ValueSource(strings = {"global", "local", "timeout", "cancel"}) + void admissionRejectionMustNotRecordAnExecutionAttempt(final String scenario) { + AtomicInteger attempts = new AtomicInteger(); + AtomicInteger invocations = new AtomicInteger(); + AtomicInteger subscriptions = new AtomicInteger(); + AgentToolRegistry registry = registry(input -> { + invocations.incrementAndGet(); + return Mono.fromSupplier(() -> { + subscriptions.incrementAndGet(); + return input.getArguments(); + }); + }); + boolean queued = "timeout".equals(scenario) || "cancel".equals(scenario); + try (AgentResourceAdmission admission = new AgentResourceAdmission( + new AgentGatewayAdmissionConfig("local".equals(scenario) ? 2 : 1, queued ? 1 : 0, 1, 0, 1, 0))) { + reactor.core.Disposable active = admission.withLocal(Instant.now().plusSeconds(30), Mono.never()).subscribe(); + try { + Instant deadline = Instant.now().plusMillis("timeout".equals(scenario) ? 150 : 30000); + Mono execution = registry.invoke("order_status", Set.of("order_status"), () -> invocation("A"), attempts::incrementAndGet, + action -> admission.withLocal(deadline, action)); + if ("cancel".equals(scenario)) { + StepVerifier.create(execution).then(() -> assertTrue(admission.snapshot().stream().anyMatch(state -> state.queued() == 1))) + .thenCancel().verify(Duration.ofSeconds(5)); + } else { + StepVerifier.create(execution).expectErrorMatches(error -> error instanceof AgentResourceAdmission.AgentAdmissionException + && ((AgentResourceAdmission.AgentAdmissionException) error).isTimeout() == queued).verify(Duration.ofSeconds(5)); + } + assertEquals(0, attempts.get()); + assertEquals(0, invocations.get()); + assertEquals(0, subscriptions.get()); + } finally { + active.dispose(); + } + StepVerifier.create(registry.invoke("order_status", Set.of("order_status"), () -> invocation("A"), attempts::incrementAndGet, + execution -> admission.withLocal(Instant.now().plusSeconds(30), execution))).expectNextCount(1).verifyComplete(); + assertEquals(1, attempts.get()); + assertEquals(1, invocations.get()); + assertEquals(1, subscriptions.get()); + assertTrue(admission.snapshot().stream().allMatch(state -> state.inFlight() == 0 && state.queued() == 0)); + } + } + @Test void shouldKeepRegistrationAndSchemaSnapshots() { List tools = new ArrayList<>(); From 83645b7207f3647118451e9e4ed82b1f25c56be1 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 5 Nov 2026 10:24:13 +0800 Subject: [PATCH 22/36] feat(common): add shared governance decisions --- docs/agent-governance-decision.md | 25 ++ .../audit/AgentGovernanceAuditAdapter.java | 50 ++++ .../AgentGovernanceContractLabels.java | 63 +++++ .../governance/AgentGovernanceDecision.java | 231 ++++++++++++++++++ .../AgentGovernanceDecisionRouter.java | 134 ++++++++++ .../AgentGovernanceShadowLedger.java | 219 +++++++++++++++++ .../AgentGovernanceAuditAdapterTest.java | 64 +++++ .../AgentGovernanceContractLabelsTest.java | 42 ++++ .../AgentGovernanceDecisionRouterTest.java | 121 +++++++++ .../AgentGovernanceShadowLedgerTest.java | 212 ++++++++++++++++ 10 files changed, 1161 insertions(+) create mode 100644 docs/agent-governance-decision.md create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceContractLabels.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouter.java create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceShadowLedger.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceContractLabelsTest.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouterTest.java create mode 100644 shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceShadowLedgerTest.java diff --git a/docs/agent-governance-decision.md b/docs/agent-governance-decision.md new file mode 100644 index 000000000000..8128030dde39 --- /dev/null +++ b/docs/agent-governance-decision.md @@ -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. diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java new file mode 100644 index 000000000000..0f371edc3b41 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java @@ -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(); + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceContractLabels.java b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceContractLabels.java new file mode 100644 index 000000000000..57832f73ac99 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceContractLabels.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.shenyu.common.governance; + +import java.util.Objects; + +/** + * The only bounded labels exposed to metrics. Identity and correlation values stay + * in the decision and its audit adapter rather than becoming metric cardinality. + */ +public final class AgentGovernanceContractLabels { + + private final String consumer; + + private final String mode; + + private final String result; + + private final String reason; + + private AgentGovernanceContractLabels(final AgentGovernanceDecision decision) { + Objects.requireNonNull(decision, "decision"); + consumer = decision.getConsumer().name(); + mode = decision.getMode().name(); + result = decision.getResult().name(); + reason = decision.getReason().name(); + } + + public static AgentGovernanceContractLabels from(final AgentGovernanceDecision decision) { + return new AgentGovernanceContractLabels(decision); + } + + public String getConsumer() { + return consumer; + } + + public String getMode() { + return mode; + } + + public String getResult() { + return result; + } + + public String getReason() { + return reason; + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java new file mode 100644 index 000000000000..b4d1552d247f --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java @@ -0,0 +1,231 @@ +/* + * 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.governance; + +import java.time.Instant; +import java.util.Objects; + +/** + * Immutable shadow/enforce decision shared by MCP quota and LLM budget consumers. + * Tenant, subject and trace id are intentionally absent: they are correlation facts, + * not bounded metric labels. + */ +public final class AgentGovernanceDecision { + + public static final int SCHEMA_VERSION = 1; + + private final Consumer consumer; + + private final String policyVersion; + + private final String configurationVersion; + + private final Mode mode; + + private final Result result; + + private final Reason reason; + + private final String correlationId; + + private final String ledgerGeneration; + + private final Instant effectiveTime; + + private AgentGovernanceDecision(final Builder builder) { + consumer = Objects.requireNonNull(builder.consumer, "consumer"); + policyVersion = boundedText(builder.policyVersion, "policyVersion"); + configurationVersion = boundedText(builder.configurationVersion, "configurationVersion"); + mode = Objects.requireNonNull(builder.mode, "mode"); + reason = Objects.requireNonNull(builder.reason, "reason"); + correlationId = boundedText(builder.correlationId, "correlationId"); + ledgerGeneration = boundedText(builder.ledgerGeneration, "ledgerGeneration"); + effectiveTime = Objects.requireNonNull(builder.effectiveTime, "effectiveTime"); + result = normalizeResult(Objects.requireNonNull(builder.result, "result"), mode, reason); + } + + public static Builder builder(final Consumer consumer, final Mode mode) { + return new Builder(consumer, mode); + } + + public int getSchemaVersion() { + return SCHEMA_VERSION; + } + + public Consumer getConsumer() { + return consumer; + } + + public String getPolicyVersion() { + return policyVersion; + } + + public String getConfigurationVersion() { + return configurationVersion; + } + + public Mode getMode() { + return mode; + } + + public Result getResult() { + return result; + } + + public Reason getReason() { + return reason; + } + + public String getCorrelationId() { + return correlationId; + } + + public String getLedgerGeneration() { + return ledgerGeneration; + } + + public Instant getEffectiveTime() { + return effectiveTime; + } + + public boolean deniesTraffic() { + return result == Result.DENY; + } + + private static Result normalizeResult(final Result candidate, final Mode mode, final Reason reason) { + if (reason == Reason.ALLOWED) { + if (candidate != Result.ALLOW) { + throw new IllegalArgumentException("ALLOWED reason requires ALLOW result"); + } + return Result.ALLOW; + } + if (candidate == Result.ALLOW) { + throw new IllegalArgumentException("deny reason cannot produce ALLOW result"); + } + if (candidate == Result.WOULD_DENY && mode != Mode.SHADOW) { + throw new IllegalArgumentException("WOULD_DENY is valid only in shadow mode"); + } + if (candidate == Result.DENY && mode != Mode.ENFORCE) { + throw new IllegalArgumentException("DENY is valid only in enforce mode"); + } + return candidate; + } + + private static String boundedText(final String value, final String name) { + if (Objects.isNull(value) || value.isBlank() || value.length() > 128 + || !value.equals(value.strip()) || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(name + " must be bounded nonblank text"); + } + return value; + } + + public enum Consumer { + MCP_QUOTA, + LLM_BUDGET + } + + public enum Mode { + SHADOW, + ENFORCE + } + + public enum Result { + ALLOW, + WOULD_DENY, + DENY + } + + public enum Reason { + ALLOWED, + MCP_INVOCATION_LIMIT, + MCP_CONCURRENCY_LIMIT, + TOKEN_BUDGET_EXCEEDED, + COST_BUDGET_EXCEEDED, + RESERVATION_EXPIRED, + AUTHENTICATION_REJECTED, + AUTHORIZATION_REJECTED, + RESOURCE_LIMIT_REJECTED, + POLICY_ERROR + } + + public static final class Builder { + + private final Consumer consumer; + + private final Mode mode; + + private String policyVersion = "unknown"; + + private String configurationVersion = "unknown"; + + private Result result; + + private Reason reason; + + private String correlationId; + + private String ledgerGeneration = "unknown"; + + private Instant effectiveTime; + + private Builder(final Consumer consumer, final Mode mode) { + this.consumer = consumer; + this.mode = mode; + } + + public Builder policyVersion(final String value) { + policyVersion = value; + return this; + } + + public Builder configurationVersion(final String value) { + configurationVersion = value; + return this; + } + + public Builder result(final Result value) { + result = value; + return this; + } + + public Builder reason(final Reason value) { + reason = value; + return this; + } + + public Builder correlationId(final String value) { + correlationId = value; + return this; + } + + public Builder ledgerGeneration(final String value) { + ledgerGeneration = value; + return this; + } + + public Builder effectiveTime(final Instant value) { + effectiveTime = value; + return this; + } + + public AgentGovernanceDecision build() { + effectiveTime = Objects.requireNonNullElseGet(effectiveTime, Instant::now); + return new AgentGovernanceDecision(this); + } + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouter.java b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouter.java new file mode 100644 index 000000000000..dc9859637884 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouter.java @@ -0,0 +1,134 @@ +/* + * 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.governance; + +import java.time.Instant; +import java.util.Objects; + +/** + * Normalizes a policy evaluation without hiding mandatory security or resource failures. + * Shadow mode changes only the reported result; callers must not debit production state. + */ +public final class AgentGovernanceDecisionRouter { + + private final AgentGovernanceDecision.Consumer consumer; + + private final AgentGovernanceDecision.Mode mode; + + private final String policyVersion; + + private final String configurationVersion; + + private final String ledgerGeneration; + + public AgentGovernanceDecisionRouter(final AgentGovernanceDecision.Consumer consumer, final AgentGovernanceDecision.Mode mode, + final String policyVersion, final String configurationVersion, + final String ledgerGeneration) { + this.consumer = Objects.requireNonNull(consumer, "consumer"); + this.mode = Objects.requireNonNull(mode, "mode"); + this.policyVersion = Objects.requireNonNull(policyVersion, "policyVersion"); + this.configurationVersion = Objects.requireNonNull(configurationVersion, "configurationVersion"); + this.ledgerGeneration = Objects.requireNonNull(ledgerGeneration, "ledgerGeneration"); + } + + public AgentGovernanceDecision allow(final String correlationId, final Instant effectiveTime) { + return decision(correlationId, effectiveTime, AgentGovernanceDecision.Result.ALLOW, AgentGovernanceDecision.Reason.ALLOWED); + } + + /** + * Compares two policy outcomes without treating shadow evaluation as an execution decision. + * A shadow WOULD_DENY differs from the enforce expectation, while ALLOW agrees across modes. + * + * @param shadowDecision the shadow observation to compare + * @param enforceDecision the enforce expectation with the same correlation id + * @return the explicit shadow/enforce comparison outcome + */ + public Comparison compare(final AgentGovernanceDecision shadowDecision, + final AgentGovernanceDecision enforceDecision) { + Objects.requireNonNull(shadowDecision, "shadowDecision"); + Objects.requireNonNull(enforceDecision, "enforceDecision"); + requireOwned(shadowDecision, AgentGovernanceDecision.Mode.SHADOW); + requireOwned(enforceDecision, AgentGovernanceDecision.Mode.ENFORCE); + if (Objects.isNull(shadowDecision.getCorrelationId()) + || !shadowDecision.getCorrelationId().equals(enforceDecision.getCorrelationId())) { + throw new IllegalArgumentException("decisions must use the same correlation id"); + } + boolean shadowWouldDeny = shadowDecision.getResult() == AgentGovernanceDecision.Result.WOULD_DENY; + boolean enforceDeny = enforceDecision.getResult() == AgentGovernanceDecision.Result.DENY; + if (shadowWouldDeny && !enforceDeny) { + return Comparison.SHADOW_STRICTER; + } + if (!shadowWouldDeny && enforceDeny) { + return Comparison.ENFORCE_STRICTER; + } + return Comparison.SAME_EFFECT; + } + + public AgentGovernanceDecision deny(final String correlationId, final Instant effectiveTime, + final AgentGovernanceDecision.Reason reason) { + Objects.requireNonNull(reason, "reason"); + AgentGovernanceDecision.Result result = mode == AgentGovernanceDecision.Mode.SHADOW + ? AgentGovernanceDecision.Result.WOULD_DENY : AgentGovernanceDecision.Result.DENY; + if (reason == AgentGovernanceDecision.Reason.ALLOWED) { + throw new IllegalArgumentException("ALLOWED reason cannot deny"); + } + return decision(correlationId, effectiveTime, result, reason); + } + + public AgentGovernanceDecision mandatoryDeny(final String correlationId, final Instant effectiveTime, + final AgentGovernanceDecision.Reason reason) { + AgentGovernanceDecision.Reason mandatory = mandatoryReason(reason); + return AgentGovernanceDecision.builder(consumer, AgentGovernanceDecision.Mode.ENFORCE) + .policyVersion(policyVersion).configurationVersion(configurationVersion) + .correlationId(correlationId).ledgerGeneration(ledgerGeneration).effectiveTime(effectiveTime) + .result(AgentGovernanceDecision.Result.DENY).reason(mandatory).build(); + } + + private AgentGovernanceDecision decision(final String correlationId, final Instant effectiveTime, + final AgentGovernanceDecision.Result result, + final AgentGovernanceDecision.Reason reason) { + return AgentGovernanceDecision.builder(consumer, mode) + .policyVersion(policyVersion).configurationVersion(configurationVersion) + .correlationId(correlationId).ledgerGeneration(ledgerGeneration).effectiveTime(effectiveTime) + .result(result).reason(reason).build(); + } + + private AgentGovernanceDecision.Reason mandatoryReason(final AgentGovernanceDecision.Reason reason) { + if (reason != AgentGovernanceDecision.Reason.AUTHENTICATION_REJECTED + && reason != AgentGovernanceDecision.Reason.AUTHORIZATION_REJECTED + && reason != AgentGovernanceDecision.Reason.RESOURCE_LIMIT_REJECTED) { + throw new IllegalArgumentException("reason is not mandatory"); + } + return reason; + } + + private void requireOwned(final AgentGovernanceDecision decision, final AgentGovernanceDecision.Mode expectedMode) { + if (decision.getConsumer() != consumer || decision.getMode() != expectedMode + || !decision.getPolicyVersion().equals(policyVersion) + || !decision.getConfigurationVersion().equals(configurationVersion) + || !decision.getLedgerGeneration().equals(ledgerGeneration)) { + throw new IllegalArgumentException("decision does not belong to this router"); + } + } + + public enum Comparison { + SAME_EFFECT, + SHADOW_STRICTER, + ENFORCE_STRICTER + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceShadowLedger.java b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceShadowLedger.java new file mode 100644 index 000000000000..c1c4e9aabe93 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceShadowLedger.java @@ -0,0 +1,219 @@ +/* + * 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.governance; + +import java.util.Collections; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Bounded, in-memory shadow-state example used by the shared contract tests. + * It never mutates enforce quota or budget state, and a generation is immutable + * after replacement so in-flight work can settle in the ledger that admitted it. + */ +public final class AgentGovernanceShadowLedger { + + private final String generation; + + private final long capacity; + + private final Map active; + + private final Map denied; + + private final Clock clock; + + private final AtomicLong accepted; + + private final AtomicLong observedDenials; + + private final AtomicLong overflowed; + + private final AtomicLong settled; + + private final AtomicLong cancelled; + + private final AtomicLong expired; + + private boolean closed; + + public AgentGovernanceShadowLedger(final String generation, final long capacity) { + this(generation, capacity, Clock.systemUTC()); + } + + AgentGovernanceShadowLedger(final String generation, final long capacity, final Clock clock) { + if (Objects.isNull(generation) || generation.isBlank() || generation.length() > 128) { + throw new IllegalArgumentException("generation must be bounded nonblank text"); + } + if (capacity < 1) { + throw new IllegalArgumentException("capacity must be positive"); + } + this.generation = generation; + this.capacity = capacity; + this.active = new HashMap<>(); + this.clock = Objects.requireNonNull(clock, "clock"); + this.denied = new EnumMap<>(AgentGovernanceDecision.Reason.class); + this.accepted = new AtomicLong(); + this.observedDenials = new AtomicLong(); + this.overflowed = new AtomicLong(); + this.settled = new AtomicLong(); + this.cancelled = new AtomicLong(); + this.expired = new AtomicLong(); + } + + public synchronized Reservation begin(final AgentGovernanceDecision decision, final long amount) { + return begin(decision, amount, Duration.ofMinutes(5)); + } + + public synchronized Reservation begin(final AgentGovernanceDecision decision, final long amount, + final Duration reservationTtl) { + Objects.requireNonNull(decision, "decision"); + if (amount < 1) { + throw new IllegalArgumentException("amount must be positive"); + } + if (Objects.isNull(reservationTtl) || reservationTtl.isZero() || reservationTtl.isNegative()) { + throw new IllegalArgumentException("reservationTtl must be positive"); + } + if (decision.getMode() != AgentGovernanceDecision.Mode.SHADOW + || decision.getResult() != AgentGovernanceDecision.Result.ALLOW + || !decision.getLedgerGeneration().equals(generation)) { + throw new IllegalArgumentException("decision does not belong to this shadow ledger"); + } + evictExpired(); + if (closed) { + return null; + } + if (active.containsKey(decision.getCorrelationId()) + || capacity - sumActive() < amount) { + overflowed.incrementAndGet(); + return null; + } + Reservation reservation = new Reservation(generation, decision.getCorrelationId(), amount); + active.put(decision.getCorrelationId(), new ExpirableReservation(reservation, + clock.instant().plus(reservationTtl))); + accepted.incrementAndGet(); + return reservation; + } + + public synchronized boolean observe(final AgentGovernanceDecision decision) { + Objects.requireNonNull(decision, "decision"); + if (decision.getMode() != AgentGovernanceDecision.Mode.SHADOW + || decision.getResult() != AgentGovernanceDecision.Result.WOULD_DENY + || !decision.getLedgerGeneration().equals(generation)) { + throw new IllegalArgumentException("decision does not belong to this shadow ledger"); + } + if (closed) { + return false; + } + denied.computeIfAbsent(decision.getReason(), ignored -> new AtomicLong()).incrementAndGet(); + observedDenials.incrementAndGet(); + return true; + } + + public synchronized boolean settle(final Reservation reservation) { + return complete(reservation, false); + } + + public synchronized boolean cancel(final Reservation reservation) { + return complete(reservation, true); + } + + private boolean complete(final Reservation reservation, final boolean cancelledOperation) { + Objects.requireNonNull(reservation, "reservation"); + evictExpired(); + ExpirableReservation current = active.get(reservation.correlationId); + if (!reservation.generation.equals(generation) || Objects.isNull(current) + || current.reservation() != reservation) { + return false; + } + active.remove(reservation.correlationId); + if (cancelledOperation) { + cancelled.incrementAndGet(); + } else { + settled.incrementAndGet(); + } + return true; + } + + public synchronized AgentGovernanceShadowSnapshot snapshot() { + Map counts = new EnumMap<>(AgentGovernanceDecision.Reason.class); + denied.forEach((reason, count) -> counts.put(reason, count.get())); + evictExpired(); + return new AgentGovernanceShadowSnapshot(generation, capacity, sumActive(), + Collections.unmodifiableMap(counts), accepted.get(), observedDenials.get(), + overflowed.get(), settled.get(), cancelled.get(), expired.get()); + } + + public synchronized void close() { + closed = true; + } + + private long sumActive() { + return active.values().stream().mapToLong(value -> value.reservation().amount).sum(); + } + + private void evictExpired() { + Instant now = clock.instant(); + active.values().removeIf(value -> { + boolean expiredReservation = !value.deadline().isAfter(now); + if (expiredReservation) { + expired.incrementAndGet(); + } + return expiredReservation; + }); + } + + public static final class Reservation { + + private final String generation; + + private final String correlationId; + + private final long amount; + + private Reservation(final String generation, final String correlationId, final long amount) { + this.generation = generation; + this.correlationId = correlationId; + this.amount = amount; + } + + public String getGeneration() { + return generation; + } + + public String getCorrelationId() { + return correlationId; + } + } + + private record ExpirableReservation(Reservation reservation, Instant deadline) { + } + + public record AgentGovernanceShadowSnapshot( + String generation, long capacity, long active, + Map deniedByReason, + long accepted, long observedDenials, long overflowed, long settled, + long cancelled, long expired) { + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java new file mode 100644 index 000000000000..f779a7095c5e --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java @@ -0,0 +1,64 @@ +/* + * 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 org.junit.jupiter.api.Test; + +import java.time.Instant; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +final class AgentGovernanceAuditAdapterTest { + + @Test + void shadowWouldDenyRemainsAllowedInAudit() { + AgentRequestContext context = new AgentRequestContext("request-1", "mcp", "selector-1", "rule-1") + .withConfigurationVersion(17L).withIdentity("tenant-1", "subject-1") + .withTarget("server.tool", "tools/call", "2025-06-18").withApiKeyId("key-1"); + AgentInvocationAuditEvent event = AgentGovernanceAuditAdapter.toEvent(context, decision( + AgentGovernanceDecision.Mode.SHADOW, AgentGovernanceDecision.Result.WOULD_DENY, + AgentGovernanceDecision.Reason.MCP_INVOCATION_LIMIT)); + assertEquals(AgentInvocationAuditEvent.Decision.ALLOWED, event.getDecision()); + assertEquals("SUCCESS", event.getOutcome()); + assertEquals("SHADOW_MCP_INVOCATION_LIMIT", event.getReason()); + } + + @Test + void enforceDenyIsAuditedAsRejection() { + AgentRequestContext context = new AgentRequestContext("request-1", "llm", "selector-1", "rule-1") + .withTarget("model-a", null, null); + AgentInvocationAuditEvent event = AgentGovernanceAuditAdapter.toEvent(context, decision( + AgentGovernanceDecision.Mode.ENFORCE, AgentGovernanceDecision.Result.DENY, + AgentGovernanceDecision.Reason.COST_BUDGET_EXCEEDED)); + assertEquals(AgentInvocationAuditEvent.Decision.REJECTED, event.getDecision()); + assertEquals("REJECTED", event.getOutcome()); + assertEquals("COST_BUDGET_EXCEEDED", event.getReason()); + } + + private AgentGovernanceDecision decision(final AgentGovernanceDecision.Mode mode, + final AgentGovernanceDecision.Result result, + final AgentGovernanceDecision.Reason reason) { + return AgentGovernanceDecision.builder(AgentGovernanceDecision.Consumer.LLM_BUDGET, mode) + .policyVersion("budget-v1").configurationVersion("configuration-1") + .correlationId("request-1").ledgerGeneration("generation-1") + .effectiveTime(Instant.parse("2026-10-26T10:00:00Z")) + .result(result).reason(reason).build(); + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceContractLabelsTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceContractLabelsTest.java new file mode 100644 index 000000000000..58869769a2e5 --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceContractLabelsTest.java @@ -0,0 +1,42 @@ +/* + * 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.governance; + +import org.junit.jupiter.api.Test; + +import java.time.Instant; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +final class AgentGovernanceContractLabelsTest { + + @Test + void exposesOnlyBoundedContractLabels() { + AgentGovernanceDecision decision = AgentGovernanceDecision.builder( + AgentGovernanceDecision.Consumer.LLM_BUDGET, AgentGovernanceDecision.Mode.SHADOW) + .policyVersion("token-budget-v1").configurationVersion("configuration-1") + .correlationId("request-with-tenant-and-trace").ledgerGeneration("generation-1") + .effectiveTime(Instant.parse("2026-10-26T10:00:00Z")) + .result(AgentGovernanceDecision.Result.WOULD_DENY).reason(AgentGovernanceDecision.Reason.TOKEN_BUDGET_EXCEEDED).build(); + AgentGovernanceContractLabels labels = AgentGovernanceContractLabels.from(decision); + assertEquals("LLM_BUDGET", labels.getConsumer()); + assertEquals("SHADOW", labels.getMode()); + assertEquals("WOULD_DENY", labels.getResult()); + assertEquals("TOKEN_BUDGET_EXCEEDED", labels.getReason()); + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouterTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouterTest.java new file mode 100644 index 000000000000..0aae83e913e9 --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouterTest.java @@ -0,0 +1,121 @@ +/* + * 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.governance; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import java.time.Instant; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +final class AgentGovernanceDecisionRouterTest { + + private final Instant effectiveTime = Instant.parse("2026-10-26T10:00:00Z"); + + @Test + void shadowPolicyDenialIsReportedWithoutTrafficDenial() { + AgentGovernanceDecision decision = router(AgentGovernanceDecision.Mode.SHADOW) + .deny("request-1", effectiveTime, AgentGovernanceDecision.Reason.MCP_CONCURRENCY_LIMIT); + assertEquals(AgentGovernanceDecision.Result.WOULD_DENY, decision.getResult()); + assertFalse(decision.deniesTraffic()); + } + + @Test + void enforcePolicyDenialCanRejectTraffic() { + AgentGovernanceDecision decision = router(AgentGovernanceDecision.Mode.ENFORCE) + .deny("request-1", effectiveTime, AgentGovernanceDecision.Reason.TOKEN_BUDGET_EXCEEDED); + assertEquals(AgentGovernanceDecision.Result.DENY, decision.getResult()); + assertTrue(decision.deniesTraffic()); + } + + @Test + void llmBudgetUsesTheSameDecisionSemantics() { + AgentGovernanceDecisionRouter router = new AgentGovernanceDecisionRouter( + AgentGovernanceDecision.Consumer.LLM_BUDGET, AgentGovernanceDecision.Mode.ENFORCE, + "token-budget-v1", "configuration-1", "enforce-generation-1"); + AgentGovernanceDecision decision = router.deny("request-1", effectiveTime, + AgentGovernanceDecision.Reason.COST_BUDGET_EXCEEDED); + assertEquals(AgentGovernanceDecision.Consumer.LLM_BUDGET, decision.getConsumer()); + assertEquals(AgentGovernanceDecision.Result.DENY, decision.getResult()); + } + + @Test + void mandatoryRejectionStaysEnforcedInShadowMode() { + AgentGovernanceDecision decision = router(AgentGovernanceDecision.Mode.SHADOW) + .mandatoryDeny("request-1", effectiveTime, AgentGovernanceDecision.Reason.AUTHORIZATION_REJECTED); + assertEquals(AgentGovernanceDecision.Mode.ENFORCE, decision.getMode()); + assertTrue(decision.deniesTraffic()); + } + + @ParameterizedTest + @EnumSource(value = AgentGovernanceDecision.Reason.class, names = { + "AUTHENTICATION_REJECTED", "AUTHORIZATION_REJECTED", "RESOURCE_LIMIT_REJECTED"}) + void mandatorySecurityAndResourceReasonsCannotBeShadowed(final AgentGovernanceDecision.Reason reason) { + AgentGovernanceDecision decision = router(AgentGovernanceDecision.Mode.SHADOW) + .mandatoryDeny("request-1", effectiveTime, reason); + assertEquals(AgentGovernanceDecision.Mode.ENFORCE, decision.getMode()); + assertEquals(AgentGovernanceDecision.Result.DENY, decision.getResult()); + assertTrue(decision.deniesTraffic()); + } + + @Test + void shadowAndEnforceOutcomesHaveExplicitComparisonSemantics() { + AgentGovernanceDecisionRouter router = new AgentGovernanceDecisionRouter( + AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.SHADOW, + "mcp-quota-v1", "configuration-1", "generation-1"); + AgentGovernanceDecision shadowWouldDeny = AgentGovernanceDecision.builder( + AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.SHADOW) + .policyVersion("mcp-quota-v1").configurationVersion("configuration-1") + .correlationId("request-1").ledgerGeneration("generation-1").effectiveTime(effectiveTime) + .result(AgentGovernanceDecision.Result.WOULD_DENY) + .reason(AgentGovernanceDecision.Reason.MCP_CONCURRENCY_LIMIT).build(); + AgentGovernanceDecision enforceAllow = AgentGovernanceDecision.builder( + AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.ENFORCE) + .policyVersion("mcp-quota-v1").configurationVersion("configuration-1") + .correlationId("request-1").ledgerGeneration("generation-1").effectiveTime(effectiveTime) + .result(AgentGovernanceDecision.Result.ALLOW).reason(AgentGovernanceDecision.Reason.ALLOWED).build(); + assertEquals(AgentGovernanceDecisionRouter.Comparison.SHADOW_STRICTER, + router.compare(shadowWouldDeny, enforceAllow)); + } + + @Test + void rejectInvalidDecisionCombinations() { + assertThrows(IllegalArgumentException.class, () -> AgentGovernanceDecision.builder( + AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.SHADOW) + .correlationId("request-1").result(AgentGovernanceDecision.Result.DENY) + .reason(AgentGovernanceDecision.Reason.MCP_INVOCATION_LIMIT).build()); + assertThrows(IllegalArgumentException.class, () -> AgentGovernanceDecision.builder( + AgentGovernanceDecision.Consumer.LLM_BUDGET, AgentGovernanceDecision.Mode.ENFORCE) + .correlationId("request-1").result(AgentGovernanceDecision.Result.WOULD_DENY) + .reason(AgentGovernanceDecision.Reason.COST_BUDGET_EXCEEDED).build()); + assertThrows(IllegalArgumentException.class, () -> AgentGovernanceDecision.builder( + AgentGovernanceDecision.Consumer.LLM_BUDGET, AgentGovernanceDecision.Mode.SHADOW) + .correlationId("request-1").result(AgentGovernanceDecision.Result.ALLOW) + .reason(AgentGovernanceDecision.Reason.RESERVATION_EXPIRED).build()); + } + + private AgentGovernanceDecisionRouter router(final AgentGovernanceDecision.Mode mode) { + return new AgentGovernanceDecisionRouter(AgentGovernanceDecision.Consumer.MCP_QUOTA, mode, + "mcp-quota-v1", "configuration-1", "shadow-generation-1"); + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceShadowLedgerTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceShadowLedgerTest.java new file mode 100644 index 000000000000..477a7a01bb09 --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/governance/AgentGovernanceShadowLedgerTest.java @@ -0,0 +1,212 @@ +/* + * 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.governance; + +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Objects; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +final class AgentGovernanceShadowLedgerTest { + + private final Instant effectiveTime = Instant.parse("2026-10-26T10:00:00Z"); + + @Test + void shadowAllowConsumesAndReleasesIsolatedCapacity() { + AgentGovernanceShadowLedger ledger = new AgentGovernanceShadowLedger("generation-1", 2); + AgentGovernanceShadowLedger.Reservation reservation = ledger.begin(allow("request-1"), 2); + assertNotNull(reservation); + assertEquals(2, ledger.snapshot().active()); + assertTrue(ledger.settle(reservation)); + assertEquals(0, ledger.snapshot().active()); + assertEquals(1, ledger.snapshot().settled()); + assertFalse(ledger.settle(reservation)); + } + + @Test + void generationDoesNotMoveOrDoubleSettleReservations() { + AgentGovernanceShadowLedger oldLedger = new AgentGovernanceShadowLedger("generation-1", 2); + AgentGovernanceShadowLedger newLedger = new AgentGovernanceShadowLedger("generation-2", 2); + AgentGovernanceShadowLedger.Reservation reservation = oldLedger.begin(allow("request-1"), 1); + assertFalse(newLedger.settle(reservation)); + assertTrue(oldLedger.settle(reservation)); + assertFalse(oldLedger.settle(reservation)); + } + + @Test + void oldGenerationCanStillSettleAfterReplacement() { + AgentGovernanceShadowLedger oldLedger = new AgentGovernanceShadowLedger("generation-1", 2); + AgentGovernanceShadowLedger.Reservation reservation = oldLedger.begin(allow("request-1"), 1); + oldLedger.close(); + assertTrue(oldLedger.settle(reservation)); + assertEquals(1, oldLedger.snapshot().settled()); + } + + @Test + void capacityOverflowAndRepeatedWouldDenyAreObserved() { + AgentGovernanceShadowLedger ledger = new AgentGovernanceShadowLedger("generation-1", 1); + assertNotNull(ledger.begin(allow("request-1"), 1)); + assertNull(ledger.begin(allow("request-2"), 1)); + assertTrue(ledger.observe(wouldDeny("request-3"))); + AgentGovernanceShadowLedger.AgentGovernanceShadowSnapshot snapshot = ledger.snapshot(); + assertEquals(1, snapshot.active()); + assertEquals(1, snapshot.accepted()); + assertEquals(1, snapshot.observedDenials()); + assertEquals(1, snapshot.overflowed()); + assertEquals(0, snapshot.settled()); + } + + @Test + void rejectsForeignAndClosedState() { + AgentGovernanceShadowLedger ledger = new AgentGovernanceShadowLedger("generation-1", 1); + assertThrows(IllegalArgumentException.class, () -> ledger.begin(wouldDeny("request-1"), 1)); + assertThrows(IllegalArgumentException.class, () -> ledger.begin(enforceDeny("request-1"), 1)); + AgentGovernanceShadowLedger.Reservation reservation = ledger.begin(allow("request-1"), 1); + ledger.close(); + assertNull(ledger.begin(allow("request-2"), 1)); + assertFalse(ledger.observe(wouldDeny("request-3"))); + } + + @Test + void cancellationAndExpiryReleaseCapacityExactlyOnce() { + ZonedDateTime time = ZonedDateTime.parse("2026-10-26T10:00:00Z"); + MutableClock clock = new MutableClock(time); + AgentGovernanceShadowLedger ledger = new AgentGovernanceShadowLedger("generation-1", 2, clock); + final AgentGovernanceShadowLedger.Reservation cancelledReservation = ledger.begin(allow("request-1"), 1, + Duration.ofSeconds(30)); + final AgentGovernanceShadowLedger.Reservation expiredReservation = ledger.begin(allow("request-2"), 1, + Duration.ofSeconds(30)); + assertTrue(ledger.cancel(cancelledReservation)); + assertFalse(ledger.cancel(cancelledReservation)); + assertFalse(ledger.settle(cancelledReservation)); + clock.advanceSeconds(31); + assertFalse(ledger.settle(expiredReservation)); + assertEquals(1, ledger.snapshot().cancelled()); + assertEquals(1, ledger.snapshot().expired()); + assertEquals(0, ledger.snapshot().active()); + assertNotNull(ledger.begin(allow("request-3"), 2)); + } + + @Test + void concurrentAllowReservationsAreBounded() throws Exception { + int tasks = 24; + AgentGovernanceShadowLedger ledger = new AgentGovernanceShadowLedger("generation-1", 8); + CountDownLatch ready = new CountDownLatch(tasks); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(tasks); + try { + Future[] results = new Future[tasks]; + for (int index = 0; index < tasks; index++) { + final String correlationId = "request-" + index; + results[index] = executor.submit(() -> { + ready.countDown(); + assertTrue(start.await(5, TimeUnit.SECONDS)); + return Objects.isNull(ledger.begin(allow(correlationId), 1)) ? 0 : 1; + }); + } + assertTrue(ready.await(5, TimeUnit.SECONDS)); + start.countDown(); + int accepted = 0; + for (Future result : results) { + accepted += result.get(5, TimeUnit.SECONDS); + } + assertEquals(8, accepted); + } finally { + executor.shutdown(); + assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + } + AgentGovernanceShadowLedger.AgentGovernanceShadowSnapshot snapshot = ledger.snapshot(); + assertEquals(8, snapshot.active()); + assertEquals(8, snapshot.accepted()); + assertEquals(tasks - 8, snapshot.overflowed()); + } + + @Test + void shadowWouldDenyDoesNotConsumeAllowCapacity() { + AgentGovernanceShadowLedger ledger = new AgentGovernanceShadowLedger("generation-1", 1); + assertTrue(ledger.observe(wouldDeny("request-1"))); + assertNotNull(ledger.begin(allow("request-2"), 1)); + assertEquals(1, ledger.snapshot().observedDenials()); + assertEquals(1, ledger.snapshot().accepted()); + } + + private AgentGovernanceDecision wouldDeny(final String correlationId) { + return AgentGovernanceDecision.builder(AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.SHADOW) + .policyVersion("mcp-quota-v1").configurationVersion("configuration-1") + .correlationId(correlationId).ledgerGeneration("generation-1").effectiveTime(effectiveTime) + .result(AgentGovernanceDecision.Result.WOULD_DENY).reason(AgentGovernanceDecision.Reason.MCP_CONCURRENCY_LIMIT).build(); + } + + private AgentGovernanceDecision allow(final String correlationId) { + return AgentGovernanceDecision.builder(AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.SHADOW) + .policyVersion("mcp-quota-v1").configurationVersion("configuration-1") + .correlationId(correlationId).ledgerGeneration("generation-1").effectiveTime(effectiveTime) + .result(AgentGovernanceDecision.Result.ALLOW).reason(AgentGovernanceDecision.Reason.ALLOWED).build(); + } + + private AgentGovernanceDecision enforceDeny(final String correlationId) { + return AgentGovernanceDecision.builder(AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.ENFORCE) + .policyVersion("mcp-quota-v1").configurationVersion("configuration-1") + .correlationId(correlationId).ledgerGeneration("generation-1").effectiveTime(effectiveTime) + .result(AgentGovernanceDecision.Result.DENY).reason(AgentGovernanceDecision.Reason.MCP_CONCURRENCY_LIMIT).build(); + } + + private static final class MutableClock extends Clock { + private ZonedDateTime value; + + private MutableClock(final ZonedDateTime value) { + this.value = value; + } + + void advanceSeconds(final long seconds) { + value = value.plusSeconds(seconds); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(final ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return value.toInstant(); + } + } +} From 63b02d3ba7dfa11f640164cc7bd7c1badb7175fd Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 5 Nov 2026 10:54:27 +0800 Subject: [PATCH 23/36] fix(metrics): preserve single registration when reconciling audit baseline --- .../plugin/metrics/reporter/MetricsReporter.java | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java index cbc47f9b523a..096bf972a3c1 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java @@ -17,8 +17,8 @@ package org.apache.shenyu.plugin.metrics.reporter; -import org.apache.shenyu.plugin.metrics.config.Metric; import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.apache.shenyu.plugin.metrics.config.Metric; import org.apache.shenyu.plugin.metrics.constant.CanaryMetric; import org.apache.shenyu.plugin.metrics.constant.LabelNames; import org.apache.shenyu.plugin.metrics.spi.MetricsRegister; @@ -81,14 +81,6 @@ public static synchronized void register(final MetricsRegister metricsRegister) registerHistogram(metric.getName(), metric.getLabelNames(), metric.getDescription(), metric.getBuckets()); } } - MetricsReporter.registerCounter(LabelNames.AGENT_REQUESTS_TOTAL, new String[]{"traffic", "outcome", "reason"}, "Terminal Agent request subscriptions including pre-dispatch rejection"); - MetricsReporter.registerHistogram(LabelNames.AGENT_REQUEST_LATENCY, new String[]{"traffic", "outcome"}, "Agent request terminal latency millis"); - MetricsReporter.registerGauge(LabelNames.AGENT_REQUESTS_INFLIGHT, new String[]{"traffic"}, "Active Agent logical request subscriptions, not sessions"); - MetricsReporter.registerCounter(LabelNames.AGENT_AI_ATTEMPTS_TOTAL, new String[]{"kind", "outcome"}, "Actually completed AI upstream attempts"); - MetricsReporter.registerHistogram(LabelNames.AGENT_AI_ATTEMPT_LATENCY, new String[]{"kind", "outcome"}, "AI upstream attempt latency millis"); - MetricsReporter.registerCounter(LabelNames.AGENT_CATALOG_OBSERVATIONS_TOTAL, new String[]{"state"}, "Remote catalog availability observed at request lease acquisition"); - MetricsReporter.registerCounter(LabelNames.AUTHENTICATION_REJECTIONS_TOTAL, new String[]{"source", "reason"}, "Authentication plugin rejections before Agent routing is known"); - agentRuntimeMetrics = new AgentRuntimeMetricsReporter(metricsRegister); } /** From b9a5bdc723b5fdd549ea52057083f54e761df3f8 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 5 Nov 2026 10:59:02 +0800 Subject: [PATCH 24/36] fix(ai-proxy): remove stale transport import from integration baseline --- .../starter/plugin/ai/proxy/AiProxyPluginConfiguration.java | 1 - 1 file changed, 1 deletion(-) diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java index 5879ba557129..b161b8bb154e 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java @@ -20,7 +20,6 @@ import org.apache.shenyu.common.audit.AgentInvocationAuditBridge; import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; -import io.netty.channel.ChannelOption; import org.apache.shenyu.common.metrics.AiCallObserver; import org.apache.shenyu.plugin.ai.proxy.enhanced.AiProxyPlugin; import org.apache.shenyu.plugin.ai.proxy.enhanced.conversion.AiProtocolConverter; From 79a060e26817642f0909cf13ef9af7de18413112 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 5 Nov 2026 10:59:03 +0800 Subject: [PATCH 25/36] fix(metrics): retain runtime registration after baseline synchronization --- .../shenyu/plugin/metrics/reporter/MetricsReporter.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java index a50f7923f1eb..096bf972a3c1 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java @@ -66,6 +66,14 @@ public static synchronized void register(final MetricsRegister metricsRegister) MetricsReporter.registerCounter(LabelNames.RESILIENCE4J_REQUEST_CIRCUITBREAKER_TOTAL, "shenyu resilience4j circuitbreaker request total count"); MetricsReporter.registerCounter(LabelNames.HYSTRIX_REQUEST_CIRCUITBREAKER_TOTAL, "shenyu hystrix circuitbreaker request total count"); MetricsReporter.registerCounter(LabelNames.RATELIMITER_REQUEST_RESTRICT_TOTAL, "shenyu ratelimiter request restrict total count"); + MetricsReporter.registerCounter(LabelNames.AGENT_REQUESTS_TOTAL, new String[]{"traffic", "outcome", "reason"}, "Terminal Agent request subscriptions including pre-dispatch rejection"); + MetricsReporter.registerHistogram(LabelNames.AGENT_REQUEST_LATENCY, new String[]{"traffic", "outcome"}, "Agent request terminal latency millis"); + MetricsReporter.registerGauge(LabelNames.AGENT_REQUESTS_INFLIGHT, new String[]{"traffic"}, "Active Agent logical request subscriptions, not sessions"); + MetricsReporter.registerCounter(LabelNames.AGENT_AI_ATTEMPTS_TOTAL, new String[]{"kind", "outcome"}, "Actually completed AI upstream attempts"); + MetricsReporter.registerHistogram(LabelNames.AGENT_AI_ATTEMPT_LATENCY, new String[]{"kind", "outcome"}, "AI upstream attempt latency millis"); + MetricsReporter.registerCounter(LabelNames.AGENT_CATALOG_OBSERVATIONS_TOTAL, new String[]{"state"}, "Remote catalog availability observed at request lease acquisition"); + MetricsReporter.registerCounter(LabelNames.AUTHENTICATION_REJECTIONS_TOTAL, new String[]{"source", "reason"}, "Authentication plugin rejections before Agent routing is known"); + agentRuntimeMetrics = new AgentRuntimeMetricsReporter(metricsRegister); for (CanaryMetric metric : CanaryMetric.values()) { if (Objects.isNull(metric.getBuckets())) { registerCounter(metric.getName(), metric.getLabelNames(), metric.getDescription()); From 34570563abfcbf84ccd769001c33cc6968a7754b Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 5 Nov 2026 11:26:42 +0800 Subject: [PATCH 26/36] feat(agent-gateway): add distributed MCP invocation and concurrency quotas --- docs/agent-gateway-mcp-quotas.md | 112 ++++++++ .../audit/AgentGovernanceAuditAdapter.java | 3 +- .../governance/AgentGovernanceDecision.java | 5 + .../common/metrics/AgentRuntimeMetrics.java | 9 + .../AgentGovernanceAuditAdapterTest.java | 11 + .../shenyu-plugin-agent-gateway/pom.xml | 15 ++ .../governance/AgentMcpQuotaConfig.java | 99 ++++++++ .../governance/AgentMcpQuotaException.java | 47 ++++ .../governance/AgentMcpQuotaGovernor.java | 198 +++++++++++++++ .../governance/AgentMcpQuotaStore.java | 77 ++++++ .../governance/RedisAgentMcpQuotaStore.java | 89 +++++++ .../gateway/protocol/AgentMcpDispatcher.java | 50 +++- .../src/main/resources/mcp-quota-release.lua | 25 ++ .../src/main/resources/mcp-quota.lua | 42 +++ .../governance/AgentMcpQuotaGovernorTest.java | 240 ++++++++++++++++++ .../AgentMcpQuotaRedisStoreTest.java | 226 +++++++++++++++++ .../protocol/AgentMcpDispatcherTest.java | 192 +++++++++++++- .../plugin/metrics/constant/LabelNames.java | 3 + .../reporter/AgentRuntimeMetricsReporter.java | 12 +- .../metrics/reporter/MetricsReporter.java | 9 + .../plugin/metrics/MetricsPluginTest.java | 8 + .../AgentGatewayPluginConfiguration.java | 39 ++- .../gateway/AgentMcpQuotaProperties.java | 136 ++++++++++ .../AgentGatewayPluginConfigurationTest.java | 72 +++++- 24 files changed, 1705 insertions(+), 14 deletions(-) create mode 100644 docs/agent-gateway-mcp-quotas.md create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaConfig.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaException.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernor.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaStore.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/RedisAgentMcpQuotaStore.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota-release.lua create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota.lua create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernorTest.java create mode 100644 shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java create mode 100644 shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentMcpQuotaProperties.java diff --git a/docs/agent-gateway-mcp-quotas.md b/docs/agent-gateway-mcp-quotas.md new file mode 100644 index 000000000000..46cbeb2c5e1e --- /dev/null +++ b/docs/agent-gateway-mcp-quotas.md @@ -0,0 +1,112 @@ + + +# Agent Gateway distributed MCP quotas + +Agent Gateway can enforce a shared invocation-count window and concurrency +limit for actual MCP `tools/call` requests. The first policy dimensions are +trusted tenant and subject; local and federated tools use the same admission +boundary. Tool discovery, resource reads, and other MCP methods do not consume +these quotas. + +The feature is opt-in. The application owns the Redis connection and supplies +one `ReactiveRedisTemplate` bean; Agent Gateway does not create +a second Redis client or lifecycle. + +## Configuration + +```yaml +shenyu: + plugins: + agent: + gateway: + mcp-quota: + enabled: true + mode: shadow # shadow or enforce + invocation-limit: 1000 + invocation-window: 60s + concurrency-limit: 100 + lease-ttl: 60s + fail-open: false + policy-version: mcp-quota-v1 +``` + +The policy is an immutable startup snapshot. Changing these properties requires +an application restart or recreation of the owning Spring context; runtime rule +updates do not partially replace a running policy. `policy-version` is bounded +diagnostic metadata and does not shard Redis state. + +`shadow` evaluates and records isolated would-deny decisions but never rejects +the call and never debits enforce state. `enforce` rejects at the actual tool +execution boundary. A denied local tool is never executed. + +## Redis semantics + +Admission is one Lua operation. It atomically checks the invocation counter, +removes expired concurrency leases, checks concurrency, debits the count, and +adds a unique lease token. Redis returns one of invocation-limited, +concurrency-limited, or admitted-with-lease; it never debits or acquires a +lease for a rejected request. + +Keys are scoped by mode, tenant, and subject: + +- `shenyu:agent:mcp-quota:invocation:{mode}:{tenant}:{subject}:{windowStart}`; +- `shenyu:agent:mcp-quota:concurrency:{mode}:{tenant}:{subject}`. + +The invocation key expires one second after its fixed window. The concurrency +sorted set stores one member per in-flight lease and expires one second after +the configured lease TTL. Cardinality is therefore bounded by active tenant and +subject identities, one invocation key per active fixed window per identity, +and at most the configured concurrency count per identity. + +Completion, error, cancellation, or subscriber cancellation releases only the +opaque lease returned for that admission. Release is idempotent and cannot +remove another request's lease. Invocation count is never refunded: a retry is +a new admitted invocation, cancellation releases concurrency only, and an +unknown upstream outcome consumes the invocation because its side effect may +have occurred. + +There is no lease renewal in this first policy. A lease carries one immutable +expiry and cannot be resurrected. If a gateway disappears, its lease is ignored +and removed after at most the configured `lease-ttl`, plus the documented +one-second key-expiration buffer. Existing request deadlines remain the +execution-time boundary. + +## Outages and observability + +Redis admission failure is explicit. `fail-open: false` rejects with a policy +error (HTTP 503 / JSON-RPC `-32027`) rather than guessing that admission was +granted. `fail-open: true` executes without a synthetic lease and records a +policy-error decision; concurrency release is not attempted for that request. + +Allowed, would-deny, deny, and policy-error outcomes use the Agent governance +decision contract. Metrics expose only bounded decision labels: + +```text +shenyu_agent_governance_decisions_total{consumer,mode,result,reason} +``` + +Tenant, subject, tool name, endpoint, request id, and trace id are not metric +labels. Non-allow decisions can also be emitted as metadata-only audit events +through the application-provided audit observer. + +## Non-goals + +This is not a second general-purpose rate-limiter platform. It does not bill +elapsed time, enforce LLM token or cost budgets, replay side-effecting tools, +or add per-tool and per-server dimensions. Those require an explicit policy +extension so key cardinality and isolation remain bounded. diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java index 0f371edc3b41..e012a0277bdf 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java @@ -44,7 +44,8 @@ public static AgentInvocationAuditEvent toEvent(final AgentRequestContext contex .decision(denied ? AgentInvocationAuditEvent.Decision.REJECTED : AgentInvocationAuditEvent.Decision.ALLOWED) .target(context.getTarget()) .outcome(denied ? "REJECTED" : "SUCCESS") - .reason(denied ? decision.getReason().name() : "SHADOW_" + decision.getReason().name()) + .reason(denied || decision.getMode() != AgentGovernanceDecision.Mode.SHADOW + ? decision.getReason().name() : "SHADOW_" + decision.getReason().name()) .build(); } } diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java index b4d1552d247f..2019a5597a8f 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java @@ -114,6 +114,11 @@ private static Result normalizeResult(final Result candidate, final Mode mode, f } return Result.ALLOW; } + if (candidate == Result.ALLOW && reason == Reason.POLICY_ERROR) { + // A fail-open adapter explicitly reports an unavailable policy backend while + // allowing traffic. It is not an unexplained allow-after-deny. + return Result.ALLOW; + } if (candidate == Result.ALLOW) { throw new IllegalArgumentException("deny reason cannot produce ALLOW result"); } diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentRuntimeMetrics.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentRuntimeMetrics.java index 4fd85586e3c2..ce9180c5b06b 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentRuntimeMetrics.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentRuntimeMetrics.java @@ -17,6 +17,8 @@ package org.apache.shenyu.common.metrics; +import org.apache.shenyu.common.governance.AgentGovernanceDecision; + /** * Optional request-scoped metrics port. Only closed enums cross this boundary; * identities, tool names, payloads and credentials are never metric labels. @@ -63,6 +65,13 @@ default void catalog(final boolean available) { default void authenticationRejected(final AuthenticationSource source, final AuthenticationReason reason) { } + /** Count one governance decision with bounded closed labels. + * + * @param decision closed shadow/enforce decision + */ + default void governanceDecision(final AgentGovernanceDecision decision) { + } + /** Isolate metrics failures from forwarding, including cancellation cleanup. * @param callback bounded metrics operation */ diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java index f779a7095c5e..1edd25d73cd7 100644 --- a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java @@ -52,6 +52,17 @@ void enforceDenyIsAuditedAsRejection() { assertEquals("COST_BUDGET_EXCEEDED", event.getReason()); } + @Test + void failOpenEnforcePolicyErrorRemainsAnAllowedAudit() { + AgentRequestContext context = new AgentRequestContext("request-1", "mcp", "selector-1", "rule-1"); + AgentInvocationAuditEvent event = AgentGovernanceAuditAdapter.toEvent(context, decision( + AgentGovernanceDecision.Mode.ENFORCE, AgentGovernanceDecision.Result.ALLOW, + AgentGovernanceDecision.Reason.POLICY_ERROR)); + assertEquals(AgentInvocationAuditEvent.Decision.ALLOWED, event.getDecision()); + assertEquals("SUCCESS", event.getOutcome()); + assertEquals("POLICY_ERROR", event.getReason()); + } + private AgentGovernanceDecision decision(final AgentGovernanceDecision.Mode mode, final AgentGovernanceDecision.Result result, final AgentGovernanceDecision.Reason reason) { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml b/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml index c83e95fe13fb..1962a945588c 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml @@ -38,6 +38,12 @@ META-INF/shenyu/agent-gateway-version.properties + + src/main/resources + + META-INF/shenyu/agent-gateway-version.properties + + @@ -82,6 +88,10 @@ org.springframework.boot spring-boot-starter-webflux + + org.springframework.data + spring-data-redis + org.springframework.boot spring-boot-starter-test @@ -92,5 +102,10 @@ reactor-test test + + io.lettuce + lettuce-core + test + diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaConfig.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaConfig.java new file mode 100644 index 000000000000..9bc3eb2b2c74 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaConfig.java @@ -0,0 +1,99 @@ +/* + * 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.plugin.agent.gateway.governance; + +import java.time.Duration; +import java.util.Objects; +import java.util.UUID; + +/** Immutable deployment-owned MCP quota policy. */ +public final class AgentMcpQuotaConfig { + + private final Mode mode; + + private final long invocationLimit; + + private final Duration invocationWindow; + + private final int concurrencyLimit; + + private final Duration leaseTtl; + + private final boolean failOpen; + + private AgentMcpQuotaConfig(final Mode mode, final long invocationLimit, final Duration invocationWindow, + final int concurrencyLimit, final Duration leaseTtl, final boolean failOpen) { + this.mode = Objects.requireNonNull(mode, "mode"); + if (invocationLimit < 1 || invocationLimit > 1_000_000_000L) { + throw new IllegalArgumentException("invocationLimit must be between 1 and 1000000000"); + } + this.invocationLimit = invocationLimit; + this.invocationWindow = requireBounded(invocationWindow, Duration.ofSeconds(1), Duration.ofDays(1), "invocationWindow"); + if (concurrencyLimit < 1 || concurrencyLimit > 100_000) { + throw new IllegalArgumentException("concurrencyLimit must be between 1 and 100000"); + } + this.concurrencyLimit = concurrencyLimit; + this.leaseTtl = requireBounded(leaseTtl, Duration.ofSeconds(1), Duration.ofMinutes(10), "leaseTtl"); + this.failOpen = failOpen; + } + + public static AgentMcpQuotaConfig of(final Mode mode, final long invocationLimit, final Duration invocationWindow, + final int concurrencyLimit, final Duration leaseTtl, final boolean failOpen) { + return new AgentMcpQuotaConfig(mode, invocationLimit, invocationWindow, concurrencyLimit, leaseTtl, failOpen); + } + + public Mode getMode() { + return mode; + } + + public long getInvocationLimit() { + return invocationLimit; + } + + public Duration getInvocationWindow() { + return invocationWindow; + } + + public int getConcurrencyLimit() { + return concurrencyLimit; + } + + public Duration getLeaseTtl() { + return leaseTtl; + } + + public boolean isFailOpen() { + return failOpen; + } + + public String newGeneration() { + return UUID.randomUUID().toString(); + } + + private static Duration requireBounded(final Duration value, final Duration minimum, final Duration maximum, final String name) { + if (Objects.isNull(value) || value.compareTo(minimum) < 0 || value.compareTo(maximum) > 0) { + throw new IllegalArgumentException(name + " is outside its allowed range"); + } + return value; + } + + public enum Mode { + SHADOW, + ENFORCE + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaException.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaException.java new file mode 100644 index 000000000000..871811c06db4 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaException.java @@ -0,0 +1,47 @@ +/* + * 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.plugin.agent.gateway.governance; + +import org.apache.shenyu.common.governance.AgentGovernanceDecision; + +/** Typed quota rejection carrying only closed decision metadata. */ +public final class AgentMcpQuotaException extends RuntimeException { + + private final AgentGovernanceDecision decision; + + public AgentMcpQuotaException(final AgentGovernanceDecision decision) { + super(message(decision)); + this.decision = decision; + } + + public AgentMcpQuotaException(final AgentGovernanceDecision decision, final Throwable cause) { + super(message(decision), cause); + this.decision = decision; + } + + public AgentGovernanceDecision getDecision() { + return decision; + } + + private static String message(final AgentGovernanceDecision decision) { + return decision.getReason() == AgentGovernanceDecision.Reason.POLICY_ERROR + ? "MCP quota policy is unavailable" + : decision.getReason() == AgentGovernanceDecision.Reason.MCP_CONCURRENCY_LIMIT + ? "MCP concurrency quota exceeded" : "MCP invocation quota exceeded"; + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernor.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernor.java new file mode 100644 index 000000000000..794418d1e945 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernor.java @@ -0,0 +1,198 @@ +/* + * 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.plugin.agent.gateway.governance; + +import org.apache.shenyu.common.governance.AgentGovernanceDecision; +import org.apache.shenyu.common.audit.AgentGovernanceAuditAdapter; +import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; +import reactor.util.context.ContextView; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import java.util.Map; + +/** Applies one immutable MCP quota policy at the actual tool execution boundary. */ +public final class AgentMcpQuotaGovernor { + + private static final Logger LOG = LoggerFactory.getLogger(AgentMcpQuotaGovernor.class); + + private final AgentMcpQuotaConfig config; + + private final AgentMcpQuotaStore store; + + private final AgentRuntimeMetrics metrics; + + private final AgentInvocationAuditObserver audit; + + private final String policyVersion; + + private final String ledgerGeneration; + + public AgentMcpQuotaGovernor(final AgentMcpQuotaConfig config, final AgentMcpQuotaStore store, + final AgentRuntimeMetrics metrics, final String policyVersion) { + this(config, store, metrics, policyVersion, null); + } + + /** Create a governor with an optional metadata-only decision audit sink. + * + * @param config immutable policy snapshot + * @param store distributed atomic admission backend + * @param metrics fallback closed-label metrics port + * @param policyVersion deployment-owned policy version + * @param audit optional application-owned decision audit sink + */ + public AgentMcpQuotaGovernor(final AgentMcpQuotaConfig config, final AgentMcpQuotaStore store, + final AgentRuntimeMetrics metrics, final String policyVersion, + final AgentInvocationAuditObserver audit) { + this.config = Objects.requireNonNull(config, "config"); + this.store = Objects.requireNonNull(store, "store"); + this.metrics = Objects.isNull(metrics) ? AgentRuntimeMetrics.NOOP : metrics; + this.audit = audit; + this.policyVersion = bounded(policyVersion, "policyVersion"); + this.ledgerGeneration = config.newGeneration(); + } + + /** Wrap an execution with atomic admission and idempotent lease release. + * + * @param execution result + * @param tenant trusted tenant + * @param subject trusted subject + * @param correlationId request correlation id + * @param configurationVersion immutable rule generation + * @param execution actual tool execution + * @return governed result + */ + public Mono withQuota(final String tenant, final String subject, final String correlationId, + final long configurationVersion, final Mono execution) { + Objects.requireNonNull(execution, "execution"); + String normalizedTenant = bounded(tenant, "tenant"); + String normalizedSubject = bounded(subject, "subject"); + String normalizedCorrelation = bounded(correlationId, "correlationId"); + Instant effectiveTime = Instant.now(); + String configuration = Long.toString(configurationVersion); + return Mono.deferContextual(context -> Mono.just(new GovernorContext(context))) + .flatMap(governorContext -> { + AgentRuntimeMetrics selectedMetrics = governorContext.metrics == AgentRuntimeMetrics.NOOP + ? metrics : governorContext.metrics; + AgentRequestContext requestContext = governorContext.requestContext; + return store.admit(config, normalizedTenant, normalizedSubject, normalizedCorrelation, effectiveTime) + .map(admission -> Map.entry(admission, false)) + .onErrorResume(error -> policyUnavailable(error, selectedMetrics, requestContext, + normalizedCorrelation, configuration, effectiveTime)) + .flatMap(admission -> { + boolean policyUnavailable = admission.getValue(); + AgentGovernanceDecision decision = decision(admission.getKey(), policyUnavailable, + normalizedCorrelation, configuration, effectiveTime); + AgentRuntimeMetrics.safely(() -> selectedMetrics.governanceDecision(decision)); + if (Objects.nonNull(requestContext) && Objects.nonNull(audit) + && decision.getReason() != AgentGovernanceDecision.Reason.ALLOWED) { + AgentRuntimeMetrics.safely(() -> audit.record(AgentGovernanceAuditAdapter.toEvent(requestContext, decision))); + } + if (decision.deniesTraffic()) { + return Mono.error(new AgentMcpQuotaException(decision)); + } + if (policyUnavailable) { + return execution; + } + return Mono.usingWhen(Mono.just(admission.getKey()), + ignored -> execution, + ignored -> releaseOnce(normalizedTenant, normalizedSubject, normalizedCorrelation, admission.getKey().lease()), + (ignored, error) -> releaseOnce(normalizedTenant, normalizedSubject, normalizedCorrelation, admission.getKey().lease()), + ignored -> releaseOnce(normalizedTenant, normalizedSubject, normalizedCorrelation, admission.getKey().lease())); + }); + }); + } + + private Mono> policyUnavailable(final Throwable error, + final AgentRuntimeMetrics selectedMetrics, + final AgentRequestContext requestContext, + final String correlationId, + final String configurationVersion, + final Instant effectiveTime) { + if (config.isFailOpen()) { + return Mono.just(Map.entry(new AgentMcpQuotaStore.Admission(true, false, false, + UUID.randomUUID().toString()), true)); + } + AgentGovernanceDecision decision = AgentGovernanceDecision.builder( + AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.ENFORCE) + .policyVersion(policyVersion).configurationVersion("unknown") + .result(AgentGovernanceDecision.Result.DENY).reason(AgentGovernanceDecision.Reason.POLICY_ERROR) + .correlationId(correlationId).ledgerGeneration(ledgerGeneration) + .effectiveTime(effectiveTime).build(); + AgentRuntimeMetrics.safely(() -> selectedMetrics.governanceDecision(decision)); + if (Objects.nonNull(requestContext) && Objects.nonNull(audit)) { + AgentRuntimeMetrics.safely(() -> audit.record(AgentGovernanceAuditAdapter.toEvent(requestContext, decision))); + } + return Mono.error(new AgentMcpQuotaException(decision, error)); + } + + private Mono releaseOnce(final String tenant, final String subject, final String correlationId, final String lease) { + return store.release(config, tenant, subject, correlationId, lease) + .onErrorResume(error -> store.release(config, tenant, subject, correlationId, lease) + .doOnError(nextError -> LOG.warn("MCP quota lease release failed twice; lease will expire by TTL, correlationId={}", + correlationId, nextError)) + .onErrorComplete()); + } + + private AgentGovernanceDecision decision(final AgentMcpQuotaStore.Admission admission, final boolean policyUnavailable, + final String correlationId, final String configurationVersion, + final Instant effectiveTime) { + AgentGovernanceDecision.Reason reason = policyUnavailable ? AgentGovernanceDecision.Reason.POLICY_ERROR + : admission.invocationLimited() + ? AgentGovernanceDecision.Reason.MCP_INVOCATION_LIMIT + : admission.concurrencyLimited() ? AgentGovernanceDecision.Reason.MCP_CONCURRENCY_LIMIT + : AgentGovernanceDecision.Reason.ALLOWED; + AgentGovernanceDecision.Result result = policyUnavailable && config.isFailOpen() ? AgentGovernanceDecision.Result.ALLOW + : admission.allowed() ? AgentGovernanceDecision.Result.ALLOW + : config.getMode() == AgentMcpQuotaConfig.Mode.SHADOW + ? AgentGovernanceDecision.Result.WOULD_DENY : AgentGovernanceDecision.Result.DENY; + return AgentGovernanceDecision.builder(AgentGovernanceDecision.Consumer.MCP_QUOTA, + config.getMode() == AgentMcpQuotaConfig.Mode.SHADOW + ? AgentGovernanceDecision.Mode.SHADOW : AgentGovernanceDecision.Mode.ENFORCE) + .policyVersion(policyVersion).configurationVersion(configurationVersion) + .result(result).reason(reason).correlationId(correlationId) + .ledgerGeneration(ledgerGeneration).effectiveTime(effectiveTime).build(); + } + + private static String bounded(final String value, final String name) { + if (Objects.isNull(value) || value.isBlank() || value.length() > 256 + || !value.equals(value.strip()) || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(name + " must be bounded nonblank text"); + } + return value; + } + + private static final class GovernorContext { + + private final AgentRuntimeMetrics metrics; + + private final AgentRequestContext requestContext; + + private GovernorContext(final ContextView context) { + AgentRuntimeMetrics requestMetrics = context.getOrDefault(AgentRuntimeMetrics.KEY, AgentRuntimeMetrics.NOOP); + metrics = requestMetrics == AgentRuntimeMetrics.NOOP ? AgentRuntimeMetrics.NOOP : requestMetrics; + requestContext = context.getOrDefault(AgentRequestContext.REACTOR_KEY, null); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaStore.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaStore.java new file mode 100644 index 000000000000..fd9265a3f798 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaStore.java @@ -0,0 +1,77 @@ +/* + * 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.plugin.agent.gateway.governance; + +import reactor.core.publisher.Mono; + +import java.util.Objects; +import java.time.Instant; + +/** Backend port for distributed atomic MCP quota admission. */ +public interface AgentMcpQuotaStore { + + /** Atomically consume one invocation and acquire one bounded concurrency lease. + * + * @param policy trusted policy snapshot + * @param tenant trusted tenant + * @param subject trusted subject + * @param correlationId unique logical request identity + * @param now admission time + * @return atomic admission result + */ + Mono admit(AgentMcpQuotaConfig policy, String tenant, String subject, String correlationId, Instant now); + + /** Idempotently release one lease owned by this request. + * + * @param policy trusted policy snapshot + * @param tenant trusted tenant + * @param subject trusted subject + * @param correlationId unique logical request identity + * @param lease unique opaque lease returned by admission + * @return true when this call released the lease + */ + Mono release(AgentMcpQuotaConfig policy, String tenant, String subject, String correlationId, String lease); + + /** Result of an atomic invocation and concurrency admission. + * + * @param allowed whether both dimensions admitted the request + * @param invocationLimited invocation count would exceed its policy + * @param concurrencyLimited concurrency would exceed its policy + * @param lease opaque lease required for release + */ + record Admission(boolean allowed, boolean invocationLimited, boolean concurrencyLimited, String lease) { + public Admission { + if (allowed && (invocationLimited || concurrencyLimited)) { + throw new IllegalArgumentException("An admitted decision cannot carry a limit flag"); + } + if (!allowed && invocationLimited == concurrencyLimited) { + throw new IllegalArgumentException("A rejected decision must identify one first limit"); + } + if (allowed && Objects.isNull(lease)) { + throw new IllegalArgumentException("An admitted decision requires a lease"); + } + if (allowed && (lease.isBlank() || lease.length() > 128 || !lease.equals(lease.strip()) + || lease.chars().anyMatch(Character::isISOControl))) { + throw new IllegalArgumentException("An admitted lease must be bounded nonblank text"); + } + if (!allowed && !Objects.toString(lease, "").isEmpty()) { + throw new IllegalArgumentException("A rejected decision must not retain a lease"); + } + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/RedisAgentMcpQuotaStore.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/RedisAgentMcpQuotaStore.java new file mode 100644 index 000000000000..7056d8b912e6 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/RedisAgentMcpQuotaStore.java @@ -0,0 +1,89 @@ +/* + * 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.plugin.agent.gateway.governance; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.core.script.RedisScript; +import reactor.core.publisher.Mono; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** Redis implementation using one atomic admission script and one idempotent release script. */ +public final class RedisAgentMcpQuotaStore implements AgentMcpQuotaStore { + + private static final RedisScript ADMIT = RedisScript.of(new ClassPathResource("mcp-quota.lua"), List.class); + + private static final RedisScript RELEASE = RedisScript.of(new ClassPathResource("mcp-quota-release.lua"), Long.class); + + private final ReactiveRedisTemplate redis; + + public RedisAgentMcpQuotaStore(final ReactiveRedisTemplate redis) { + this.redis = Objects.requireNonNull(redis, "redis"); + } + + @Override + public Mono admit(final AgentMcpQuotaConfig policy, final String tenant, final String subject, + final String correlationId, final Instant now) { + Objects.requireNonNull(now, "now"); + long windowSeconds = policy.getInvocationWindow().toSeconds(); + long windowStart = Math.floorDiv(now.getEpochSecond(), windowSeconds) + * policy.getInvocationWindow().toSeconds(); + long invocationTtl = windowStart + windowSeconds - now.getEpochSecond() + 1; + long leaseExpiry = now.plus(policy.getLeaseTtl()).getEpochSecond(); + String lease = UUID.randomUUID().toString(); + String scope = (policy.getMode() == AgentMcpQuotaConfig.Mode.SHADOW ? "shadow" : "enforce") + + ":" + scopePart(tenant) + ":" + scopePart(subject); + String invocationKey = "shenyu:agent:mcp-quota:invocation:" + scope + ":" + windowStart; + String concurrencyKey = "shenyu:agent:mcp-quota:concurrency:" + scope; + return redis.execute(ADMIT, List.of(invocationKey, concurrencyKey), + List.of(Long.toString(policy.getInvocationLimit()), Long.toString(windowStart), + Long.toString(invocationTtl), Integer.toString(policy.getConcurrencyLimit()), + lease, Long.toString(leaseExpiry), Long.toString(policy.getLeaseTtl().toSeconds() + 1), Long.toString(now.getEpochSecond()))) + .next() + .map(values -> new Admission(flag(values, 0), + flag(values, 1), flag(values, 2), + Objects.toString(values.get(3), ""))); + } + + @Override + public Mono release(final AgentMcpQuotaConfig policy, final String tenant, final String subject, + final String correlationId, final String lease) { + Objects.requireNonNull(lease, "lease"); + String scope = (policy.getMode() == AgentMcpQuotaConfig.Mode.SHADOW ? "shadow" : "enforce") + + ":" + scopePart(tenant) + ":" + scopePart(subject); + String concurrencyKey = "shenyu:agent:mcp-quota:concurrency:" + scope; + return redis.execute(RELEASE, List.of(concurrencyKey), List.of(lease)) + .next() + .map(value -> Objects.equals("1", Objects.toString(value, null))); + } + + private static String scopePart(final String value) { + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(value.getBytes(StandardCharsets.UTF_8)); + } + + private static boolean flag(final List values, final int index) { + return Objects.equals("1", Objects.toString(values.get(index), null)); + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java index 69baa4a49cac..63d8a9807ade 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java @@ -25,6 +25,9 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.shenyu.common.dto.AgentGatewayHttpToolConfig; +import org.apache.shenyu.common.governance.AgentGovernanceDecision; +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaException; +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaGovernor; import org.apache.shenyu.plugin.agent.gateway.resource.AgentResourceRegistry; import org.apache.shenyu.plugin.agent.gateway.tool.AgentHttpToolProvider; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolArgumentException; @@ -54,6 +57,8 @@ public final class AgentMcpDispatcher { private final AgentMcpResourceAdmission admission; + private final AgentMcpQuotaGovernor quotaGovernor; + private final AgentMcpResourceDispatcher resources; private final AgentResourceRegistry resourceRegistry; @@ -110,11 +115,28 @@ public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverN public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion, final AgentMcpRemoteCatalog remoteCatalog, final AgentResourceRegistry resourceRegistry, final AgentMcpResourceAdmission admission) { + this(registry, serverName, serverVersion, remoteCatalog, resourceRegistry, admission, null); + } + + /** + * Managed dispatcher with resource admission and distributed MCP business quotas. + * @param registry trusted local tool registry + * @param serverName server name + * @param serverVersion server version + * @param remoteCatalog optional remote catalog + * @param resourceRegistry explicitly registered local resources + * @param admission remote admission policy + * @param quotaGovernor optional distributed business quota governor + */ + public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion, + final AgentMcpRemoteCatalog remoteCatalog, final AgentResourceRegistry resourceRegistry, + final AgentMcpResourceAdmission admission, final AgentMcpQuotaGovernor quotaGovernor) { this.registry = Objects.requireNonNull(registry, "registry"); this.remoteCatalog = remoteCatalog; this.resourceRegistry = Objects.requireNonNull(resourceRegistry, "resourceRegistry"); this.resources = new AgentMcpResourceDispatcher(resourceRegistry); this.admission = Objects.requireNonNull(admission, "admission"); + this.quotaGovernor = quotaGovernor; if (Objects.requireNonNull(serverName, "serverName").isBlank() || Objects.requireNonNull(serverVersion, "serverVersion").isBlank()) { throw new IllegalArgumentException("Server identity must not be blank"); } @@ -147,7 +169,7 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier bound); + resourceRegistry, Objects.isNull(remoteCatalog) ? admission : remoteCatalog.admission(), quotaGovernor).dispatch(request, () -> bound); } if (Objects.nonNull(remoteCatalog)) { return remoteCatalog.withSnapshot(snapshot -> routeWithRemote(request, context, snapshot)) @@ -189,6 +211,16 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier routeWithRemote(final AgentMcpRequest request, final Ag final AgentMcpResultFilter filter = prepareResultFilter(request, context, name, definitions.get(name).get("outputSchema")); ObjectNode params = request.getParams(); JsonObject arguments = params.has("arguments") ? JsonParser.parseString(params.get("arguments").toString()).getAsJsonObject() : new JsonObject(); - return Mono.defer(() -> { - return admission.withRemote(remoteServer(name), context.getDeadline(), - Mono.fromRunnable(context::notifyAttempt).then(snapshot.invoke(name, arguments, context))); - }) + return withQuota(context, Mono.defer(() -> admission.withRemote(remoteServer(name), context.getDeadline(), + Mono.fromRunnable(context::notifyAttempt).then(snapshot.invoke(name, arguments, context))))) .switchIfEmpty(Mono.error(new IllegalStateException("Remote tool completed without a result"))) .map(value -> { ObjectNode result = value.deepCopy(); @@ -314,7 +344,7 @@ private Mono call(final AgentMcpRequest request, final AgentMcpExecu return registry.invoke(name, context.getAllowedTools(), () -> new AgentToolInvocation(context.getRequestId(), context.getSubject(), arguments, context.getRuleId(), context.getConfigurationVersion(), context.getDeadline(), capabilities), context::notifyAttempt, - execution -> admission.withLocal(context.getDeadline(), execution)) + execution -> admission.withLocal(context.getDeadline(), withQuota(context, execution))) .map(value -> { // Active field policies must not introduce an opaque metadata channel. ObjectNode result = filter.isActive() ? mapper.createObjectNode().put("resultType", "complete") : complete(); @@ -350,6 +380,14 @@ private String remoteServer(final String exposedName) { return separator > 0 ? exposedName.substring(0, separator) : exposedName; } + private Mono withQuota(final AgentMcpExecutionContext context, final Mono execution) { + if (Objects.isNull(quotaGovernor)) { + return execution; + } + return quotaGovernor.withQuota(context.getTenant().orElse("unknown"), context.getSubject(), + context.getRequestId(), context.getConfigurationVersion(), execution); + } + private AgentMcpResultFilter prepareResultFilter(final AgentMcpRequest request, final AgentMcpExecutionContext context, final String name, final JsonNode schema) { try { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota-release.lua b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota-release.lua new file mode 100644 index 000000000000..26a0bba456cf --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota-release.lua @@ -0,0 +1,25 @@ +-- +-- 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. +--/ + +-- Idempotently remove one owned MCP concurrency lease. +-- KEYS[1] concurrency lease set +-- ARGV[1] lease token +local removed = redis.call('ZREM', KEYS[1], ARGV[1]) +if removed == 1 then + return 1 +end +return 0 diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota.lua b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota.lua new file mode 100644 index 000000000000..55e3f5e1bca9 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota.lua @@ -0,0 +1,42 @@ +-- +-- 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. +--/ + +-- Atomic MCP invocation and concurrency admission. +-- KEYS[1] invocation window counter +-- KEYS[2] concurrency lease set +-- ARGV[1] invocation limit +-- ARGV[2] window start epoch second +-- ARGV[3] invocation window TTL seconds +-- ARGV[4] concurrency limit +-- ARGV[5] lease token +-- ARGV[6] lease expiry epoch second +-- ARGV[7] concurrency key TTL seconds +-- ARGV[8] current epoch second +-- Returns {allowed, invocationLimited, concurrencyLimited, lease} +local invocation = tonumber(redis.call('GET', KEYS[1]) or '0') +if invocation >= tonumber(ARGV[1]) then + return {0, 1, 0, ''} +end +redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', ARGV[8]) +local concurrency = redis.call('ZCARD', KEYS[2]) +if concurrency >= tonumber(ARGV[4]) then + return {0, 0, 1, ''} +end +redis.call('SET', KEYS[1], invocation + 1, 'EX', ARGV[3]) +redis.call('ZADD', KEYS[2], ARGV[6], ARGV[5]) +redis.call('EXPIRE', KEYS[2], ARGV[7]) +return {1, 0, 0, ARGV[5]} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernorTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernorTest.java new file mode 100644 index 000000000000..033da86fe35e --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernorTest.java @@ -0,0 +1,240 @@ +/* + * 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.plugin.agent.gateway.governance; + +import org.apache.shenyu.common.governance.AgentGovernanceDecision; +import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +final class AgentMcpQuotaGovernorTest { + + private final List decisions = new CopyOnWriteArrayList<>(); + + private final List audits = new CopyOnWriteArrayList<>(); + + @Test + void enforceDenyStopsExecutionWithoutRelease() { + RecordingStore store = new RecordingStore(new AgentMcpQuotaStore.Admission(false, true, false, "")); + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.ENFORCE, store, false); + StepVerifier.create(governor.withQuota("tenant", "subject", "request", 1, Mono.just("value"))) + .expectError(AgentMcpQuotaException.class) + .verify(Duration.ofSeconds(5)); + assertEquals(1, store.admissions); + assertEquals(1, store.releaseCount.getCount()); + assertEquals(AgentGovernanceDecision.Reason.MCP_INVOCATION_LIMIT, decisions.get(0).getReason()); + } + + @Test + void shadowDenyStillExecutesAndReleasesShadowLease() { + RecordingStore store = new RecordingStore(new AgentMcpQuotaStore.Admission(false, true, false, "")); + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.SHADOW, store, false, false); + StepVerifier.create(governor.withQuota("tenant", "subject", "request", 1, Mono.just("value"))) + .expectNext("value") + .verifyComplete(); + assertEquals(1, store.admissions); + assertTrue(awaitRelease(store.releaseCount)); + assertEquals(AgentGovernanceDecision.Result.WOULD_DENY, decisions.get(0).getResult()); + } + + @Test + void shadowWouldDenyUsesRequestAuditAndRuntimeMetricsWithoutDuplicatingAllows() { + RecordingStore store = new RecordingStore(new AgentMcpQuotaStore.Admission(false, true, false, "")); + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.SHADOW, store, false, true); + StepVerifier.create(governor.withQuota("tenant", "subject", "request-1", 1, Mono.just("value")) + .contextWrite(context -> context.put(AgentRequestContext.REACTOR_KEY, + new AgentRequestContext("request-1", "mcp", "selector", "rule") + .withIdentity("tenant", "subject")))) + .expectNext("value") + .verifyComplete(); + assertEquals(1, audits.size()); + assertEquals(AgentInvocationAuditEvent.Decision.ALLOWED, audits.get(0).getDecision()); + assertEquals("SHADOW_MCP_INVOCATION_LIMIT", audits.get(0).getReason()); + } + + @Test + void failOpenPolicyErrorAllowsTrafficWithoutPretendingToOwnLease() { + RecordingStore store = new RecordingStore(null); + store.fail = true; + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.ENFORCE, store, true); + StepVerifier.create(governor.withQuota("tenant", "subject", "request", 1, Mono.just("value"))) + .expectNext("value") + .verifyComplete(); + assertEquals(1, store.admissions); + assertEquals(1, store.releaseCount.getCount()); + assertEquals(AgentGovernanceDecision.Reason.POLICY_ERROR, decisions.get(0).getReason()); + assertEquals(AgentGovernanceDecision.Result.ALLOW, decisions.get(0).getResult()); + } + + @Test + void failClosedPolicyErrorRejectsTraffic() { + RecordingStore store = new RecordingStore(null); + store.fail = true; + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.ENFORCE, store, false); + StepVerifier.create(governor.withQuota("tenant", "subject", "request", 1, Mono.just("value"))) + .expectErrorSatisfies(error -> assertTrue(error instanceof AgentMcpQuotaException + && ((AgentMcpQuotaException) error).getDecision().getReason() == AgentGovernanceDecision.Reason.POLICY_ERROR)) + .verify(Duration.ofSeconds(5)); + assertEquals(1, store.releaseCount.getCount()); + assertEquals(1, decisions.size()); + assertEquals(AgentGovernanceDecision.Result.DENY, decisions.get(0).getResult()); + assertEquals(AgentGovernanceDecision.Reason.POLICY_ERROR, decisions.get(0).getReason()); + } + + @Test + void failClosedPolicyErrorRecordsAuditWithRequestContext() { + RecordingStore store = new RecordingStore(null); + store.fail = true; + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.ENFORCE, store, false, true); + StepVerifier.create(governor.withQuota("tenant", "subject", "request-1", 1, Mono.just("value")) + .contextWrite(context -> context.put(AgentRequestContext.REACTOR_KEY, + new AgentRequestContext("request-1", "mcp", "selector", "rule") + .withIdentity("tenant", "subject")))) + .expectError(AgentMcpQuotaException.class) + .verify(Duration.ofSeconds(5)); + assertEquals(1, audits.size()); + assertEquals(AgentInvocationAuditEvent.Decision.REJECTED, audits.get(0).getDecision()); + assertEquals("POLICY_ERROR", audits.get(0).getReason()); + } + + @Test + void cancellationReleasesConcurrencyButDoesNotRefundInvocation() { + RecordingStore store = new RecordingStore(new AgentMcpQuotaStore.Admission(true, false, false, "lease")); + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.ENFORCE, store, false); + CountDownLatch subscribed = new CountDownLatch(1); + reactor.core.Disposable subscription = governor.withQuota("tenant", "subject", "request", 1, + Mono.defer(() -> { + subscribed.countDown(); + return Mono.never(); + })).subscribe(); + assertTrue(awaitRelease(subscribed)); + subscription.dispose(); + assertTrue(awaitRelease(store.releaseCount)); + } + + @Test + void metricsFailureDoesNotAffectAdmission() { + RecordingStore store = new RecordingStore(new AgentMcpQuotaStore.Admission(true, false, false, "lease")); + AgentRuntimeMetrics broken = new AgentRuntimeMetrics() { + @Override + public void governanceDecision(final AgentGovernanceDecision decision) { + throw new IllegalStateException("expected"); + } + }; + AgentMcpQuotaGovernor governor = new AgentMcpQuotaGovernor( + AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, 2, Duration.ofSeconds(1), 2, + Duration.ofSeconds(1), false), store, broken, "test"); + StepVerifier.create(governor.withQuota("tenant", "subject", "request", 1, Mono.just("value"))) + .expectNext("value") + .verifyComplete(); + } + + @Test + void executionErrorStillReleasesLease() { + RecordingStore store = new RecordingStore(new AgentMcpQuotaStore.Admission(true, false, false, "lease")); + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.ENFORCE, store, false); + StepVerifier.create(governor.withQuota("tenant", "subject", "request", 1, + Mono.error(new IllegalStateException("tool failed")))) + .expectError(IllegalStateException.class) + .verify(Duration.ofSeconds(5)); + assertTrue(awaitRelease(store.releaseCount)); + } + + @Test + void releaseFailureDoesNotChangeSuccessfulToolResult() { + RecordingStore store = new RecordingStore(new AgentMcpQuotaStore.Admission(true, false, false, "lease")); + store.failRelease = true; + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.ENFORCE, store, false); + StepVerifier.create(governor.withQuota("tenant", "subject", "request", 1, Mono.just("value"))) + .expectNext("value") + .verifyComplete(); + assertEquals(2, store.releases); + } + + private AgentMcpQuotaGovernor governor(final AgentMcpQuotaConfig.Mode mode, + final AgentMcpQuotaStore store, final boolean failOpen, final boolean audited) { + AgentRuntimeMetrics metrics = new AgentRuntimeMetrics() { + @Override + public void governanceDecision(final AgentGovernanceDecision decision) { + decisions.add(decision); + } + }; + return new AgentMcpQuotaGovernor(AgentMcpQuotaConfig.of(mode, 1, Duration.ofSeconds(60), + 1, Duration.ofSeconds(60), failOpen), store, metrics, "test", audited ? audits::add : null); + } + + private AgentMcpQuotaGovernor governor(final AgentMcpQuotaConfig.Mode mode, + final AgentMcpQuotaStore store, final boolean failOpen) { + return governor(mode, store, failOpen, false); + } + + private static boolean awaitRelease(final CountDownLatch latch) { + try { + return latch.await(1, TimeUnit.SECONDS); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + return false; + } + } + + private static final class RecordingStore implements AgentMcpQuotaStore { + private final AgentMcpQuotaStore.Admission admission; + + private boolean fail; + + private boolean failRelease; + + private int releases; + + private int admissions; + + private final CountDownLatch releaseCount = new CountDownLatch(1); + + private RecordingStore(final AgentMcpQuotaStore.Admission admission) { + this.admission = admission; + } + + @Override + public Mono admit(final AgentMcpQuotaConfig policy, final String tenant, + final String subject, final String correlationId, final Instant now) { + admissions++; + return fail ? Mono.error(new IllegalStateException("redis unavailable")) : Mono.just(admission); + } + + @Override + public Mono release(final AgentMcpQuotaConfig policy, final String tenant, + final String subject, final String correlationId, final String lease) { + releaseCount.countDown(); + releases++; + return failRelease ? Mono.error(new IllegalStateException("release unavailable")) : Mono.just(true); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java new file mode 100644 index 000000000000..1261ebf74e6f --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java @@ -0,0 +1,226 @@ +/* + * 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.plugin.agent.gateway.governance; + +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.StringRedisSerializer; +import reactor.core.publisher.Flux; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +final class AgentMcpQuotaRedisStoreTest { + + private static final String HOST = System.getProperty("shenyu.agent.mcp-quota.redis.host", "127.0.0.1"); + + private static final int PORT = Integer.getInteger("shenyu.agent.mcp-quota.redis.port", 6379); + + private static boolean isRedisAvailable() { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(HOST, PORT), 500); + return true; + } catch (IOException error) { + return false; + } + } + + private static ReactiveRedisTemplate template() { + LettuceConnectionFactory factory = new LettuceConnectionFactory(new RedisStandaloneConfiguration(HOST, PORT)); + factory.afterPropertiesSet(); + RedisSerializationContext serializationContext = + RedisSerializationContext.newSerializationContext() + .key(StringRedisSerializer.UTF_8) + .value(StringRedisSerializer.UTF_8) + .hashKey(StringRedisSerializer.UTF_8) + .hashValue(StringRedisSerializer.UTF_8) + .build(); + return new ReactiveRedisTemplate<>(factory, serializationContext); + } + + @Test + void twoStoreInstancesCannotExceedSharedInvocationLimit() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + ReactiveRedisTemplate template = template(); + String tenant = tenant(); + AgentMcpQuotaConfig policy = policy(AgentMcpQuotaConfig.Mode.ENFORCE, 5, 100); + RedisAgentMcpQuotaStore first = new RedisAgentMcpQuotaStore(template); + RedisAgentMcpQuotaStore second = new RedisAgentMcpQuotaStore(template); + long allowed = Flux.range(0, 10) + .flatMap(index -> (index % 2 == 0 ? first : second) + .admit(policy, tenant, "subject", UUID.randomUUID().toString(), Instant.now())) + .filter(AgentMcpQuotaStore.Admission::allowed) + .count() + .block(Duration.ofSeconds(10)); + assertEquals(5, allowed); + } + + @Test + void concurrencyAdmissionReleaseAndIdempotenceAreAtomic() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + ReactiveRedisTemplate template = template(); + String tenant = tenant(); + String subject = subject(); + AgentMcpQuotaConfig policy = policy(AgentMcpQuotaConfig.Mode.ENFORCE, 100, 2); + RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template); + List admissions = Flux.range(0, 3) + .flatMap(index -> store.admit(policy, tenant, subject, UUID.randomUUID().toString(), Instant.now())) + .collectList() + .block(Duration.ofSeconds(10)); + assertEquals(2, admissions.stream().filter(AgentMcpQuotaStore.Admission::allowed).count()); + assertEquals(1, admissions.stream().filter(AgentMcpQuotaStore.Admission::concurrencyLimited).count()); + admissions = admissions.stream().filter(AgentMcpQuotaStore.Admission::allowed).toList(); + AgentMcpQuotaStore.Admission first = admissions.get(0); + AgentMcpQuotaStore.Admission second = admissions.get(1); + assertTrue(store.release(policy, tenant, subject, "request-1", first.lease()).block(Duration.ofSeconds(5))); + assertFalse(store.release(policy, tenant, subject, "request-2", first.lease()).block(Duration.ofSeconds(5))); + assertTrue(store.release(policy, tenant, subject, "request-2", second.lease()).block(Duration.ofSeconds(5))); + assertFalse(store.release(policy, tenant, subject, "request-2", second.lease()).block(Duration.ofSeconds(5))); + AgentMcpQuotaStore.Admission recovered = store.admit(policy, tenant, subject, + UUID.randomUUID().toString(), Instant.now()).block(Duration.ofSeconds(5)); + assertTrue(recovered.allowed()); + } + + @Test + void aLaterArrivalCannotReclaimAnUnexpiredLease() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + AgentMcpQuotaConfig policy = AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, + 100, Duration.ofSeconds(60), 1, Duration.ofSeconds(30), false); + RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template()); + String tenant = tenant(); + String subject = subject(); + Instant now = Instant.now(); + assertTrue(store.admit(policy, tenant, subject, "first", now).block(Duration.ofSeconds(5)).allowed()); + AgentMcpQuotaStore.Admission second = store.admit(policy, tenant, subject, "second", now.plusSeconds(1)) + .block(Duration.ofSeconds(5)); + assertFalse(second.allowed()); + assertTrue(second.concurrencyLimited()); + assertTrue(store.admit(policy, tenant, subject, "expired", now.plusSeconds(30)).block(Duration.ofSeconds(5)).allowed()); + } + + @Test + void expiredLeaseRecoversWithinConfiguredBound() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + ReactiveRedisTemplate template = template(); + String tenant = tenant(); + String subject = subject(); + AgentMcpQuotaConfig policy = AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, + 100, Duration.ofSeconds(60), 1, Duration.ofSeconds(1), false); + RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template); + assertTrue(store.admit(policy, tenant, subject, UUID.randomUUID().toString(), Instant.now()) + .block(Duration.ofSeconds(5)).allowed()); + AgentMcpQuotaStore.Admission denied = store.admit(policy, tenant, subject, + UUID.randomUUID().toString(), Instant.now()).block(Duration.ofSeconds(5)); + assertFalse(denied.allowed()); + assertTrue(denied.concurrencyLimited()); + AgentMcpQuotaStore.Admission afterExpiry = store.admit(policy, tenant, subject, + UUID.randomUUID().toString(), Instant.now().plusSeconds(2)).block(Duration.ofSeconds(5)); + assertTrue(afterExpiry.allowed()); + } + + @Test + void shadowStateDoesNotDebitEnforceState() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + ReactiveRedisTemplate template = template(); + String tenant = tenant(); + String subject = subject(); + AgentMcpQuotaConfig shadow = policy(AgentMcpQuotaConfig.Mode.SHADOW, 1, 100); + AgentMcpQuotaConfig enforce = policy(AgentMcpQuotaConfig.Mode.ENFORCE, 1, 100); + RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template); + AgentMcpQuotaStore.Admission firstShadow = store.admit(shadow, tenant, subject, + UUID.randomUUID().toString(), Instant.now()).block(Duration.ofSeconds(5)); + AgentMcpQuotaStore.Admission secondShadow = store.admit(shadow, tenant, subject, + UUID.randomUUID().toString(), Instant.now()).block(Duration.ofSeconds(5)); + assertTrue(firstShadow.allowed()); + assertFalse(secondShadow.allowed()); + AgentMcpQuotaStore.Admission enforceAdmission = store.admit(enforce, tenant, subject, + UUID.randomUUID().toString(), Instant.now()).block(Duration.ofSeconds(5)); + assertTrue(enforceAdmission.allowed()); + } + + @Test + void invocationQuotaUsesDeterministicFixedWindows() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + ReactiveRedisTemplate template = template(); + String tenant = tenant(); + String subject = subject(); + AgentMcpQuotaConfig policy = AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, + 1, Duration.ofSeconds(60), 100, Duration.ofSeconds(60), false); + RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template); + long stableWindow = Math.floorDiv(Instant.now().plusSeconds(60).getEpochSecond(), 60) * 60L; + assertTrue(store.admit(policy, tenant, subject, UUID.randomUUID().toString(), Instant.ofEpochSecond(stableWindow)) + .block(Duration.ofSeconds(5)).allowed()); + assertFalse(store.admit(policy, tenant, subject, UUID.randomUUID().toString(), Instant.ofEpochSecond(stableWindow + 1)) + .block(Duration.ofSeconds(5)).allowed()); + assertTrue(store.admit(policy, tenant, subject, UUID.randomUUID().toString(), Instant.ofEpochSecond(stableWindow + 60)) + .block(Duration.ofSeconds(5)).allowed()); + } + + @Test + void sameSubjectInDifferentTenantsUsesIsolatedInvocationCounters() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + ReactiveRedisTemplate template = template(); + String subject = subject(); + AgentMcpQuotaConfig policy = AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, + 1, Duration.ofSeconds(60), 100, Duration.ofSeconds(60), false); + RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template); + assertTrue(store.admit(policy, tenant(), subject, UUID.randomUUID().toString(), Instant.now()) + .block(Duration.ofSeconds(5)).allowed()); + assertTrue(store.admit(policy, tenant(), subject, UUID.randomUUID().toString(), Instant.now()) + .block(Duration.ofSeconds(5)).allowed()); + } + + @Test + void encodedDimensionsCannotCollideAcrossTenantAndSubjectBoundaries() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + ReactiveRedisTemplate template = template(); + AgentMcpQuotaConfig policy = policy(AgentMcpQuotaConfig.Mode.ENFORCE, 1, 100); + RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template); + assertTrue(store.admit(policy, "tenant", "subject:tool", UUID.randomUUID().toString(), Instant.now()) + .block(Duration.ofSeconds(5)).allowed()); + assertTrue(store.admit(policy, "tenant:subject", "tool", UUID.randomUUID().toString(), Instant.now()) + .block(Duration.ofSeconds(5)).allowed()); + } + + private static String tenant() { + return "quota-" + UUID.randomUUID(); + } + + private static String subject() { + return "subject-" + UUID.randomUUID(); + } + + private static AgentMcpQuotaConfig policy(final AgentMcpQuotaConfig.Mode mode, + final long invocationLimit, final int concurrencyLimit) { + return AgentMcpQuotaConfig.of(mode, invocationLimit, Duration.ofSeconds(60), + concurrencyLimit, Duration.ofSeconds(60), false); + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java index c7371ba00f03..d8239726c48f 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java @@ -17,15 +17,21 @@ package org.apache.shenyu.plugin.agent.gateway.protocol; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.JsonObject; import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaConfig; +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaGovernor; +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaStore; import com.google.gson.JsonParser; import org.apache.shenyu.plugin.agent.gateway.AgentGatewayConstants; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolExecutionException; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolInvocation; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolProvider; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.apache.shenyu.plugin.agent.gateway.resource.AgentResourceRegistry; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -38,10 +44,16 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.time.Instant; import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; @@ -453,8 +465,125 @@ void shouldAdmitLocalToolOnlyAfterPreExecutionValidation() { } } + @Test + void quotaDenialPreventsLocalExecutionAndMapsToQuotaProtocolFailure() { + AtomicInteger calls = new AtomicInteger(); + AgentMcpQuotaGovernor governor = quotaGovernor(false, + new AgentMcpQuotaStore.Admission(false, true, false, "")); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher( + new AgentToolRegistry(List.of(provider("order_status", input -> { + calls.incrementAndGet(); + return Mono.just(input.getArguments()); + }))), "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, + null, new AgentResourceRegistry(List.of()), AgentMcpResourceAdmission.NOOP, governor); + StepVerifier.create(dispatcher.dispatch(request("tools/call", "1", "order_status"), () -> context("A", Set.of("order_status")))) + .expectErrorSatisfies(error -> assertProtocol(error, 429, -32027, + "MCP invocation quota exceeded")).verify(); + assertEquals(0, calls.get()); + } + + @Test + void quotaAdmissionWrapsColdLocalExecutionAndReleasesOnEveryTerminalSignal() { + AtomicInteger calls = new AtomicInteger(); + List releases = new CopyOnWriteArrayList<>(); + CountDownLatch subscribed = new CountDownLatch(1); + AtomicBoolean cancelled = new AtomicBoolean(); + AgentMcpQuotaGovernor governor = new AgentMcpQuotaGovernor( + AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, 2, Duration.ofSeconds(60), + 2, Duration.ofSeconds(60), false), + recordingStore(new AgentMcpQuotaStore.Admission(true, false, false, "lease"), releases), + AgentRuntimeMetrics.NOOP, "test"); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher( + new AgentToolRegistry(List.of(provider("order_status", input -> { + calls.incrementAndGet(); + subscribed.countDown(); + return Mono.never().doOnCancel(() -> cancelled.set(true)); + }))), "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, + null, new AgentResourceRegistry(List.of()), AgentMcpResourceAdmission.NOOP, governor); + reactor.core.Disposable subscription = dispatcher.dispatch(request("tools/call", "1", "order_status"), + () -> context("A", Set.of("order_status"))).subscribe(); + assertTrue(await(subscribed)); + assertEquals(1, calls.get()); + subscription.dispose(); + assertTrue(cancelled.get()); + assertTrue(awaitRelease(releases)); + } + + @Test + void toolsListAndDiscoveryDoNotConsumeMcpQuota() { + AtomicInteger admissions = new AtomicInteger(); + AgentMcpQuotaGovernor governor = new AgentMcpQuotaGovernor( + AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, 2, Duration.ofSeconds(60), + 2, Duration.ofSeconds(60), false), + recordingStore(new AgentMcpQuotaStore.Admission(true, false, false, "lease"), new CopyOnWriteArrayList<>() { + @Override + public boolean add(final String value) { + admissions.incrementAndGet(); + return super.add(value); + } + }), AgentRuntimeMetrics.NOOP, "test"); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher( + new AgentToolRegistry(List.of(provider("order_status", input -> Mono.just(input.getArguments())))), + "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, + null, new AgentResourceRegistry(List.of()), AgentMcpResourceAdmission.NOOP, governor); + StepVerifier.create(dispatcher.dispatch(request("server/discover", "1", "order_status"), () -> context("A", Set.of()))) + .expectNextCount(1).verifyComplete(); + StepVerifier.create(dispatcher.dispatch(request("tools/list", "1", "order_status"), () -> context("A", Set.of("order_status")))) + .expectNextCount(1).verifyComplete(); + assertEquals(0, admissions.get()); + } + + @Test + void quotaPolicyOutageMapsFailClosedToServiceUnavailable() { + AgentMcpQuotaGovernor governor = new AgentMcpQuotaGovernor( + AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, 2, Duration.ofSeconds(60), + 2, Duration.ofSeconds(60), false), failingStore(), + AgentRuntimeMetrics.NOOP, "test"); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher( + new AgentToolRegistry(List.of(provider("order_status", input -> Mono.just(input.getArguments())))), + "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, + null, new AgentResourceRegistry(List.of()), AgentMcpResourceAdmission.NOOP, governor); + StepVerifier.create(dispatcher.dispatch(request("tools/call", "1", "order_status"), () -> context("A", Set.of("order_status")))) + .expectErrorSatisfies(error -> assertProtocol(error, 503, -32027, + "MCP quota policy is unavailable")).verify(); + } + + @Test + void quotaDenialPreventsRemoteExecution() { + AtomicInteger calls = new AtomicInteger(); + AgentMcpRemoteCatalog catalog = operation -> operation.apply(new AgentMcpRemoteCatalog.Snapshot() { + @Override + public Map definitions() { + ObjectNode definition = new ObjectMapper().createObjectNode() + .put("name", "remote.order_status").put("description", "Remote order"); + definition.putObject("inputSchema").put("type", "object"); + return Map.of("remote.order_status", definition); + } + + @Override + public Mono invoke(final String name, final JsonObject arguments, final AgentMcpExecutionContext context) { + calls.incrementAndGet(); + return Mono.just(new ObjectMapper().createObjectNode()); + } + }); + AgentMcpQuotaGovernor governor = quotaGovernor(false, + new AgentMcpQuotaStore.Admission(false, false, true, "")); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher(new AgentToolRegistry(List.of()), + "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, catalog, + new AgentResourceRegistry(List.of()), AgentMcpResourceAdmission.NOOP, governor); + StepVerifier.create(dispatcher.dispatch(request("tools/call", "1", "remote.order_status"), + () -> context("A", Set.of("remote.order_status"), Set.of("remote.order_status")))) + .expectErrorSatisfies(error -> assertProtocol(error, 429, -32027, + "MCP concurrency quota exceeded")).verify(); + assertEquals(0, calls.get()); + } + private AgentMcpExecutionContext context(final String subject, final Set grants) { - return new AgentMcpExecutionContext("internal-" + subject, subject, "rule", 1, Set.of("order_status"), grants); + return context(subject, Set.of("order_status"), grants); + } + + private AgentMcpExecutionContext context(final String subject, final Set ruleTools, final Set grants) { + return new AgentMcpExecutionContext("internal-" + subject, subject, "rule", 1, ruleTools, grants); } private AgentMcpDispatcher dispatcher(final AgentToolProvider... providers) { @@ -493,4 +622,65 @@ private AgentMcpRequest request(final String method, final String id, final Stri headers.set("Mcp-Name", name); return parser.parse(body.getBytes(StandardCharsets.UTF_8), headers, 262144); } + + private static AgentMcpQuotaGovernor quotaGovernor(final boolean failOpen, final AgentMcpQuotaStore.Admission admission) { + return new AgentMcpQuotaGovernor(AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, + 2, Duration.ofSeconds(60), 2, Duration.ofSeconds(60), failOpen), + Objects.isNull(admission) ? failingStore() : recordingStore(admission, new CopyOnWriteArrayList<>()), + AgentRuntimeMetrics.NOOP, "test"); + } + + private static AgentMcpQuotaStore recordingStore(final AgentMcpQuotaStore.Admission admission, final List releases) { + return new AgentMcpQuotaStore() { + @Override + public Mono admit(final AgentMcpQuotaConfig policy, final String tenant, + final String subject, final String correlationId, final Instant now) { + return Mono.just(admission); + } + + @Override + public Mono release(final AgentMcpQuotaConfig policy, final String tenant, + final String subject, final String correlationId, final String lease) { + releases.add(lease); + return Mono.just(true); + } + }; + } + + private static AgentMcpQuotaStore failingStore() { + return new AgentMcpQuotaStore() { + @Override + public Mono admit(final AgentMcpQuotaConfig policy, final String tenant, + final String subject, final String correlationId, final Instant now) { + return Mono.error(new IllegalStateException("quota backend unavailable")); + } + + @Override + public Mono release(final AgentMcpQuotaConfig policy, final String tenant, + final String subject, final String correlationId, final String lease) { + return Mono.just(false); + } + }; + } + + private static boolean await(final CountDownLatch latch) { + try { + return latch.await(1, TimeUnit.SECONDS); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + return false; + } + } + + private static boolean awaitRelease(final List releases) { + for (int index = 0; index < 20 && releases.isEmpty(); index++) { + try { + TimeUnit.MILLISECONDS.sleep(20); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + return false; + } + } + return !releases.isEmpty(); + } } diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/constant/LabelNames.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/constant/LabelNames.java index 6b72d0767c89..cc84921aa400 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/constant/LabelNames.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/constant/LabelNames.java @@ -36,6 +36,9 @@ public final class LabelNames { public static final String AUTHENTICATION_REJECTIONS_TOTAL = "shenyu_authentication_rejections_total"; + /** Bounded shadow/enforce policy decisions for Agent governance. */ + public static final String AGENT_GOVERNANCE_DECISIONS_TOTAL = "shenyu_agent_governance_decisions_total"; + /** Records accepted at the logging queue admission boundary, not backend deliveries. */ public static final String LOGGING_QUEUE_ACCEPTED_TOTAL = "shenyu_logging_queue_accepted_total"; diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java index 7573b331ddec..ddf288591c7c 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java @@ -17,8 +17,9 @@ package org.apache.shenyu.plugin.metrics.reporter; -import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; +import org.apache.shenyu.common.governance.AgentGovernanceDecision; import org.apache.shenyu.common.metrics.AiAttemptEvent; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.metrics.constant.LabelNames; import org.apache.shenyu.plugin.metrics.spi.MetricsRegister; @@ -84,6 +85,15 @@ public synchronized void authenticationRejected(final AuthenticationSource sourc } } + @Override + public synchronized void governanceDecision(final AgentGovernanceDecision decision) { + if (active) { + String[] values = {label(decision.getConsumer()), label(decision.getMode()), + label(decision.getResult()), label(decision.getReason())}; + register.counterIncrement(LabelNames.AGENT_GOVERNANCE_DECISIONS_TOTAL, values, 1); + } + } + private static String label(final Enum value) { return value.name().toLowerCase(Locale.ROOT); } diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java index a50f7923f1eb..99536ae22b4e 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java @@ -73,6 +73,15 @@ public static synchronized void register(final MetricsRegister metricsRegister) registerHistogram(metric.getName(), metric.getLabelNames(), metric.getDescription(), metric.getBuckets()); } } + MetricsReporter.registerCounter(LabelNames.AGENT_REQUESTS_TOTAL, new String[]{"traffic", "outcome", "reason"}, "Terminal Agent request subscriptions including pre-dispatch rejection"); + MetricsReporter.registerHistogram(LabelNames.AGENT_REQUEST_LATENCY, new String[]{"traffic", "outcome"}, "Agent request terminal latency millis"); + MetricsReporter.registerGauge(LabelNames.AGENT_REQUESTS_INFLIGHT, new String[]{"traffic"}, "Active Agent logical request subscriptions, not sessions"); + MetricsReporter.registerCounter(LabelNames.AGENT_AI_ATTEMPTS_TOTAL, new String[]{"kind", "outcome"}, "Actually completed AI upstream attempts"); + MetricsReporter.registerHistogram(LabelNames.AGENT_AI_ATTEMPT_LATENCY, new String[]{"kind", "outcome"}, "AI upstream attempt latency millis"); + MetricsReporter.registerCounter(LabelNames.AGENT_CATALOG_OBSERVATIONS_TOTAL, new String[]{"state"}, "Remote catalog availability observed at request lease acquisition"); + MetricsReporter.registerCounter(LabelNames.AUTHENTICATION_REJECTIONS_TOTAL, new String[]{"source", "reason"}, "Authentication plugin rejections before Agent routing is known"); + MetricsReporter.registerCounter(LabelNames.AGENT_GOVERNANCE_DECISIONS_TOTAL, new String[]{"consumer", "mode", "result", "reason"}, "Agent governance policy decisions"); + agentRuntimeMetrics = new AgentRuntimeMetricsReporter(metricsRegister); } /** diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/MetricsPluginTest.java b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/MetricsPluginTest.java index ec25b6fe868c..e8dad6c9ecb0 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/MetricsPluginTest.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/MetricsPluginTest.java @@ -21,6 +21,7 @@ import org.apache.shenyu.common.constant.Constants; import org.apache.shenyu.common.enums.PluginEnum; import org.apache.shenyu.common.enums.RpcTypeEnum; +import org.apache.shenyu.common.governance.AgentGovernanceDecision; import org.apache.shenyu.common.metrics.AgentMcpCallObserver; import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.common.metrics.AiAttemptEvent; @@ -196,6 +197,13 @@ void governanceMetricsUseTheExistingPrometheusRegistryWithoutIdentityLabels() { new String[]{"state"}, new String[]{"unavailable"})); Assertions.assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_CATALOG_OBSERVATIONS_TOTAL, new String[]{"state"}, new String[]{"available"})); + metrics.governanceDecision(AgentGovernanceDecision.builder( + AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.SHADOW) + .correlationId("request-private").result(AgentGovernanceDecision.Result.WOULD_DENY) + .reason(AgentGovernanceDecision.Reason.MCP_INVOCATION_LIMIT).build()); + Assertions.assertEquals(1.0, CollectorRegistry.defaultRegistry.getSampleValue(LabelNames.AGENT_GOVERNANCE_DECISIONS_TOTAL, + new String[]{"consumer", "mode", "result", "reason"}, + new String[]{"mcp_quota", "shadow", "would_deny", "mcp_invocation_limit"})); } finally { MetricsReporter.clean(); CollectorRegistry.defaultRegistry.clear(); diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java index 046d5b5610d9..4bd7dcd22dd8 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java @@ -23,7 +23,11 @@ import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; import org.apache.shenyu.common.dto.AgentGatewayAggregationConfig; import org.apache.shenyu.common.metrics.AgentMcpTerminalObserver; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.common.metrics.AiCallObserver; +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaConfig; +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaGovernor; +import org.apache.shenyu.plugin.agent.gateway.governance.RedisAgentMcpQuotaStore; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpCallTracer; import org.apache.shenyu.plugin.agent.gateway.AgentGatewayPlugin; import org.apache.shenyu.plugin.agent.gateway.AgentGatewayConstants; @@ -48,6 +52,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.core.env.Environment; +import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.apache.shenyu.plugin.agent.gateway.remote.ManagedRemoteMcpCatalog; import org.apache.shenyu.plugin.agent.gateway.remote.RemoteServiceCredentialResolver; @@ -66,6 +71,7 @@ */ @Configuration @ConditionalOnProperty(value = "shenyu.plugins.agent.gateway.enabled", havingValue = "true", matchIfMissing = false) +@EnableConfigurationProperties(AgentMcpQuotaProperties.class) public class AgentGatewayPluginConfiguration { private static final String JWT_SECURITY_RESOLVER_BEAN_NAME = "agentGatewayJwtSecurityResolver"; @@ -83,6 +89,7 @@ public class AgentGatewayPluginConfiguration { * @param admissions optional deployment-owned resource admission controller * @param environment deployment-controlled tracing opt-in * @param beanFactory application bean factory used to verify the conditional JWT resolver + * @param quota optional quota governor supplied by the opt-in configuration below * @return the plugin */ @Bean @@ -93,7 +100,8 @@ public ShenyuPlugin agentGatewayPlugin(final ObjectProvider p final ObjectProvider terminalObservers, final ObjectProvider aiObservers, final ObjectProvider auditors, - final Environment environment, final BeanFactory beanFactory) { + final Environment environment, final BeanFactory beanFactory, + final ObjectProvider quota) { AgentMcpCallTracer tracer = tracers.getIfAvailable(); if (environment.getProperty("shenyu.plugins.agent.gateway.tracing.enabled", Boolean.class, false) && java.util.Objects.isNull(tracer)) { throw new IllegalStateException("Enabled MCP tracing requires an application tracing bridge"); @@ -117,7 +125,8 @@ public ShenyuPlugin agentGatewayPlugin(final ObjectProvider p return createPlugin(providers, authorities, catalogs.getIfAvailable(), tracer, resources, admissions.getIfAvailable(), AgentInvocationAuditBridge.mcp(terminalObservers.getIfAvailable(), auditors.getIfAvailable()), AgentInvocationAuditBridge.ai(aiObservers.getIfAvailable(), auditors.getIfAvailable()), - environment.getProperty("shenyu.plugins.agent.gateway.security.llm.enabled", Boolean.class, false)); + environment.getProperty("shenyu.plugins.agent.gateway.security.llm.enabled", Boolean.class, false), + quota.getIfAvailable()); } private ShenyuPlugin createPlugin(final ObjectProvider providers, final List candidates, @@ -125,7 +134,7 @@ private ShenyuPlugin createPlugin(final ObjectProvider provid final ObjectProvider resources, final AgentMcpResourceAdmission.ResourceAdmissionController admission, final AgentMcpTerminalObserver terminalObserver, final AiCallObserver aiObserver, - final boolean llmIdentityEnabled) { + final boolean llmIdentityEnabled, final AgentMcpQuotaGovernor quotaGovernor) { AgentToolRegistry registry = new AgentToolRegistry(providers.orderedStream().toList()); AgentMcpSecurityResolver resolver = candidates.isEmpty() ? exchange -> Mono.empty() : candidates.get(0); if (llmIdentityEnabled && candidates.isEmpty()) { @@ -136,11 +145,33 @@ private ShenyuPlugin createPlugin(final ObjectProvider provid java.util.Objects.isNull(catalog) ? AgentMcpResourceAdmission.NOOP : catalog.admission()); AgentMcpDispatcher dispatcher = new AgentMcpDispatcher(registry, "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, catalog, resourceRegistry, - effectiveAdmission); + effectiveAdmission, quotaGovernor); return new AgentGatewayPlugin(new AgentMcpHttpHandler(dispatcher, resolver, tracer, terminalObserver), llmIdentityEnabled ? resolver : null, aiObserver); } + /** + * Opt-in distributed MCP admission. The application remains the sole owner of Redis + * connectivity and metrics/audit observers. + * + * @param properties deployment-owned immutable policy snapshot + * @param redis application-provided reactive Redis template + * @return quota governor attached only to actual tools/call execution + */ + @Bean + @ConditionalOnProperty(value = "shenyu.plugins.agent.gateway.mcp-quota.enabled", havingValue = "true") + AgentMcpQuotaGovernor agentMcpQuotaGovernor(final AgentMcpQuotaProperties properties, + final ObjectProvider> redis, + final ObjectProvider auditors) { + ReactiveRedisTemplate template = redis.getIfAvailable(); + if (java.util.Objects.isNull(template)) { + throw new IllegalStateException("Enabled MCP quotas require an application-provided ReactiveRedisTemplate"); + } + AgentMcpQuotaConfig config = properties.toConfig(); + return new AgentMcpQuotaGovernor(config, new RedisAgentMcpQuotaStore(template), + AgentRuntimeMetrics.NOOP, properties.trustedPolicyVersion(), auditors.getIfAvailable()); + } + /** * Create the agent gateway plugin data handler. * diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentMcpQuotaProperties.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentMcpQuotaProperties.java new file mode 100644 index 000000000000..e74430a5a522 --- /dev/null +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentMcpQuotaProperties.java @@ -0,0 +1,136 @@ +/* + * 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.springboot.starter.plugin.agent.gateway; + +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaConfig; +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.time.Duration; +import java.util.Objects; + +/** + * Deployment-owned distributed MCP quota policy. Redis connectivity and lifecycle + * are owned by the application; this namespace only describes admission behavior. + */ +@ConfigurationProperties(prefix = "shenyu.plugins.agent.gateway.mcp-quota", ignoreUnknownFields = false) +public class AgentMcpQuotaProperties { + + private boolean enabled; + + private Mode mode = Mode.SHADOW; + + private long invocationLimit = 1000; + + private Duration invocationWindow = Duration.ofMinutes(1); + + private int concurrencyLimit = 100; + + private Duration leaseTtl = Duration.ofMinutes(1); + + private boolean failOpen; + + private String policyVersion = "unknown"; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + + public Mode getMode() { + return mode; + } + + public void setMode(final Mode mode) { + this.mode = mode; + } + + public long getInvocationLimit() { + return invocationLimit; + } + + public void setInvocationLimit(final long invocationLimit) { + this.invocationLimit = invocationLimit; + } + + public Duration getInvocationWindow() { + return invocationWindow; + } + + public void setInvocationWindow(final Duration invocationWindow) { + this.invocationWindow = invocationWindow; + } + + public int getConcurrencyLimit() { + return concurrencyLimit; + } + + public void setConcurrencyLimit(final int concurrencyLimit) { + this.concurrencyLimit = concurrencyLimit; + } + + public Duration getLeaseTtl() { + return leaseTtl; + } + + public void setLeaseTtl(final Duration leaseTtl) { + this.leaseTtl = leaseTtl; + } + + public boolean isFailOpen() { + return failOpen; + } + + public void setFailOpen(final boolean failOpen) { + this.failOpen = failOpen; + } + + public String getPolicyVersion() { + return policyVersion; + } + + public void setPolicyVersion(final String policyVersion) { + this.policyVersion = policyVersion; + } + + /** + * Build the immutable admission policy after Spring's relaxed binding has populated it. + * + * @return validated quota policy + */ + public AgentMcpQuotaConfig toConfig() { + return AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.valueOf(mode.name()), invocationLimit, + invocationWindow, concurrencyLimit, leaseTtl, failOpen); + } + + public String trustedPolicyVersion() { + if (Objects.isNull(policyVersion) || policyVersion.isBlank() || policyVersion.length() > 128 + || !policyVersion.equals(policyVersion.strip()) + || policyVersion.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("policyVersion must be bounded nonblank text"); + } + return policyVersion; + } + + public enum Mode { + SHADOW, + ENFORCE; + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java index f22a18b43114..dc2a8505eb09 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java @@ -18,9 +18,12 @@ package org.apache.shenyu.springboot.starter.plugin.agent.gateway; import org.apache.shenyu.plugin.agent.gateway.AgentGatewayPlugin; +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaConfig; +import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaGovernor; import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpHttpHandler; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpCallTracer; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; import io.opentelemetry.api.OpenTelemetry; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -33,7 +36,6 @@ import org.apache.shenyu.plugin.agent.gateway.resource.AgentResourceContent; import org.apache.shenyu.common.dto.AgentGatewayMcpConfig; import org.apache.shenyu.common.dto.PluginData; -import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpDispatcher; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; import org.apache.shenyu.plugin.agent.gateway.remote.ManagedRemoteMcpCatalog; import com.google.gson.JsonObject; @@ -45,11 +47,13 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.test.util.ReflectionTestUtils; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import reactor.test.StepVerifier; +import java.time.Duration; import java.util.Set; import java.util.List; import java.util.ArrayList; @@ -194,6 +198,72 @@ void shouldAssemblePluginWhenEnabled() { }); } + @Test + void mcpQuotaIsOptInAndRequiresApplicationRedis() { + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true") + .run(context -> assertFalse(context.containsBean("agentMcpQuotaGovernor"))); + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", + "shenyu.plugins.agent.gateway.mcp-quota.enabled=true") + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void validMcpQuotaPolicyWiresGovernorIntoPlugin() { + ReactiveRedisTemplate redis = mock(ReactiveRedisTemplate.class); + contextRunner.withPropertyValues( + "shenyu.plugins.agent.gateway.enabled=true", + "shenyu.plugins.agent.gateway.mcp-quota.enabled=true", + "shenyu.plugins.agent.gateway.mcp-quota.mode=enforce", + "shenyu.plugins.agent.gateway.mcp-quota.invocation-limit=10", + "shenyu.plugins.agent.gateway.mcp-quota.invocation-window=30s", + "shenyu.plugins.agent.gateway.mcp-quota.concurrency-limit=3", + "shenyu.plugins.agent.gateway.mcp-quota.lease-ttl=45s", + "shenyu.plugins.agent.gateway.mcp-quota.fail-open=true", + "shenyu.plugins.agent.gateway.mcp-quota.policy-version=v1") + .withBean(ReactiveRedisTemplate.class, () -> redis) + .run(context -> { + AgentMcpQuotaGovernor governor = context.getBean(AgentMcpQuotaGovernor.class); + AgentMcpHttpHandler handler = (AgentMcpHttpHandler) ReflectionTestUtils.getField( + context.getBean(AgentGatewayPlugin.class), "mcpHandler"); + AgentMcpDispatcher dispatcher = (AgentMcpDispatcher) ReflectionTestUtils.getField(handler, "dispatcher"); + assertEquals(governor, ReflectionTestUtils.getField(dispatcher, "quotaGovernor")); + }); + } + + @Test + void invalidMcpQuotaBoundsFailStartup() { + ReactiveRedisTemplate redis = mock(ReactiveRedisTemplate.class); + contextRunner.withBean(ReactiveRedisTemplate.class, () -> redis) + .withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", + "shenyu.plugins.agent.gateway.mcp-quota.enabled=true", + "shenyu.plugins.agent.gateway.mcp-quota.invocation-limit=0") + .run(context -> assertNotNull(context.getStartupFailure())); + contextRunner.withBean(ReactiveRedisTemplate.class, () -> redis) + .withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", + "shenyu.plugins.agent.gateway.mcp-quota.enabled=true", + "shenyu.plugins.agent.gateway.mcp-quota.concurrency-limit=0") + .run(context -> assertNotNull(context.getStartupFailure())); + contextRunner.withBean(ReactiveRedisTemplate.class, () -> redis) + .withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", + "shenyu.plugins.agent.gateway.mcp-quota.enabled=true", + "shenyu.plugins.agent.gateway.mcp-quota.policy-version=" + "a".repeat(129)) + .run(context -> assertNotNull(context.getStartupFailure())); + } + + @Test + void mcpQuotaPropertiesValidateDefaultsAndModeBinding() { + AgentMcpQuotaProperties properties = new AgentMcpQuotaProperties(); + AgentMcpQuotaConfig config = properties.toConfig(); + assertEquals(AgentMcpQuotaConfig.Mode.SHADOW, config.getMode()); + assertEquals(1000, config.getInvocationLimit()); + assertEquals(Duration.ofMinutes(1), config.getInvocationWindow()); + assertEquals(100, config.getConcurrencyLimit()); + assertEquals(Duration.ofMinutes(1), config.getLeaseTtl()); + assertFalse(config.isFailOpen()); + properties.setMode(AgentMcpQuotaProperties.Mode.ENFORCE); + assertEquals(AgentMcpQuotaConfig.Mode.ENFORCE, properties.toConfig().getMode()); + } + @Test void shouldAssembleExplicitResourcesWithSeparatePermissions() { AgentResourceProvider provider = new AgentResourceProvider() { From 1ef59b0d98a62f9d75d97da4a8b53982f18d0aa3 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 5 Nov 2026 11:57:38 +0800 Subject: [PATCH 27/36] fix(ai-proxy): remove stale import from quota integration baseline --- .../starter/plugin/ai/proxy/AiProxyPluginConfiguration.java | 1 - 1 file changed, 1 deletion(-) diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java index 5879ba557129..b161b8bb154e 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java @@ -20,7 +20,6 @@ import org.apache.shenyu.common.audit.AgentInvocationAuditBridge; import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; -import io.netty.channel.ChannelOption; import org.apache.shenyu.common.metrics.AiCallObserver; import org.apache.shenyu.plugin.ai.proxy.enhanced.AiProxyPlugin; import org.apache.shenyu.plugin.ai.proxy.enhanced.conversion.AiProtocolConverter; From 6fa0abcfe46c7024bfc2dc19caee98ed4a18f596 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 5 Nov 2026 13:41:15 +0800 Subject: [PATCH 28/36] ci: rerun admission checks after intermittent admin failures From ab421f7f4bb219a495e371ed7e28f956541e453d Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 5 Nov 2026 14:02:39 +0800 Subject: [PATCH 29/36] test(admin): await recorded master selection failures --- .../admin/mode/cluster/service/ShenyuClusterServiceTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mode/cluster/service/ShenyuClusterServiceTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mode/cluster/service/ShenyuClusterServiceTest.java index f4edbb18398d..65957f16d6f5 100644 --- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/mode/cluster/service/ShenyuClusterServiceTest.java +++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/mode/cluster/service/ShenyuClusterServiceTest.java @@ -37,6 +37,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -234,7 +235,7 @@ public void testSelectMasterErrorCountTracking() throws Exception { clusterService.start("127.0.0.1", 9195, "/shenyu"); assertTrue(errorsOccurred.await(5, TimeUnit.SECONDS)); - assertTrue(clusterService.getSelectMasterErrorCount() >= 2); + await().atMost(AWAIT_MILLIS, TimeUnit.MILLISECONDS).untilAsserted(() -> assertTrue(clusterService.getSelectMasterErrorCount() >= 2)); clusterService.shutdown(); } From c3487f5070d2ba889f206a2fe7b4991195b5b3ab Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 5 Nov 2026 18:43:52 +0800 Subject: [PATCH 30/36] test(agent-gateway): clarify logical audit target propagation --- .../common/audit/AgentInvocationAuditBridgeTest.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java index c8dc0df61f61..d8505da26799 100644 --- a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentInvocationAuditBridgeTest.java @@ -33,6 +33,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -41,7 +42,8 @@ class AgentInvocationAuditBridgeTest { @Test void reusesTerminalIdempotenceAndKeepsAttemptIdentity() { List records = new CopyOnWriteArrayList<>(); - AiRequestObservation observation = new AiRequestObservation(AgentInvocationAuditBridge.ai(null, records::add), context("one")); + AgentRequestContext initial = context("one"); + AiRequestObservation observation = new AiRequestObservation(AgentInvocationAuditBridge.ai(null, records::add), initial); AiRequestObservation.Attempt primary = observation.startAttempt(observation.getContext().withTarget("primary", "chat", null), AiAttemptEvent.Kind.PRIMARY, "openai", "chat", false); primary.status(503); @@ -57,6 +59,11 @@ void reusesTerminalIdempotenceAndKeepsAttemptIdentity() { assertEquals(List.of(1, 2), records.stream().filter(event -> event.getAttempt().isPresent()).map(event -> event.getAttempt().orElseThrow()).toList()); assertEquals(1, records.stream().filter(event -> event.getRecordType() == AgentInvocationAuditEvent.RecordType.LOGICAL).count()); assertTrue(records.stream().allMatch(event -> event.getApiKeyId().orElseThrow().equals("key-id-one"))); + assertNull(initial.getTarget()); + assertEquals("primary", records.get(0).getTarget().orElseThrow()); + assertEquals("fallback", records.get(1).getTarget().orElseThrow()); + // startAttempt updates the logical owner while each attempt keeps its selected target. + assertEquals("fallback", observation.getContext().getTarget()); assertEquals("fallback", records.get(2).getTarget().orElseThrow()); } From 0b3fb8e7baeac5d3313f96293e9196251d1d09b6 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Fri, 6 Nov 2026 11:04:54 +0800 Subject: [PATCH 31/36] fix(agent-gateway): make MCP quota admission cluster-safe --- .github/workflows/agent-mcp-quota.yml | 63 ++++++++++++ docs/agent-gateway-mcp-quotas.md | 45 ++++++--- docs/agent-gateway-resource-admission.md | 17 ++++ docs/agent-governance-decision.md | 23 ++++- docs/agent-invocation-audit.md | 17 ++++ .../governance/AgentGovernanceDecision.java | 6 +- .../AgentGovernanceDecisionRouter.java | 6 +- .../governance/AgentGovernanceText.java | 52 ++++++++++ .../governance/AgentMcpQuotaConfig.java | 5 - .../governance/AgentMcpQuotaGovernor.java | 96 +++++++++++++++---- .../governance/AgentMcpQuotaStore.java | 6 +- .../governance/RedisAgentMcpQuotaStore.java | 29 +++--- .../gateway/protocol/AgentMcpDispatcher.java | 12 ++- .../protocol/AgentMcpResourceAdmission.java | 4 +- .../src/main/resources/mcp-quota-release.lua | 2 +- .../src/main/resources/mcp-quota.lua | 48 ++++++---- .../governance/AgentMcpQuotaGovernorTest.java | 25 +++++ .../AgentMcpQuotaRedisStoreTest.java | 54 ++++++++--- .../protocol/AgentMcpDispatcherTest.java | 58 ++++++++++- .../ai/proxy/enhanced/AiProxyPlugin.java | 5 - .../reporter/AgentRuntimeMetricsReporter.java | 6 +- .../gateway/AgentMcpQuotaProperties.java | 21 ++-- .../AgentGatewayPluginConfigurationTest.java | 2 +- 23 files changed, 480 insertions(+), 122 deletions(-) create mode 100644 .github/workflows/agent-mcp-quota.yml create mode 100644 shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceText.java diff --git a/.github/workflows/agent-mcp-quota.yml b/.github/workflows/agent-mcp-quota.yml new file mode 100644 index 000000000000..70b603ca3db6 --- /dev/null +++ b/.github/workflows/agent-mcp-quota.yml @@ -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. + +name: Agent MCP Redis quota + +on: + pull_request: + paths: + - 'shenyu-plugin/shenyu-plugin-agent-gateway/**' + - '.github/workflows/agent-mcp-quota.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + redis-quota: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + cache: maven + - name: Start Redis with cluster slot enforcement + run: | + docker run -d --name quota-redis -p 6379:6379 redis:7-alpine redis-server --cluster-enabled yes --cluster-config-file /tmp/nodes.conf + for attempt in $(seq 1 30); do + docker exec quota-redis redis-cli ping && break + sleep 1 + done + docker exec quota-redis redis-cli cluster addslotsrange 0 16383 + for attempt in $(seq 1 30); do + if docker exec quota-redis redis-cli cluster info | grep -q 'cluster_state:ok'; then exit 0; fi + sleep 1 + done + exit 1 + - name: Require real Redis quota regressions + run: >- + ./mvnw -B -ntp -pl shenyu-plugin/shenyu-plugin-agent-gateway -am test + -Dtest=AgentMcpQuotaRedisStoreTest,AgentMcpQuotaGovernorTest,AgentMcpDispatcherTest + -Dsurefire.failIfNoSpecifiedTests=false -DskipRemoteResources=true + -Dshenyu.agent.mcp-quota.redis.required=true + - name: Redis diagnostics + if: failure() + run: docker logs quota-redis + - name: Stop Redis + if: always() + run: docker rm -f quota-redis diff --git a/docs/agent-gateway-mcp-quotas.md b/docs/agent-gateway-mcp-quotas.md index 46cbeb2c5e1e..2c953f226d65 100644 --- a/docs/agent-gateway-mcp-quotas.md +++ b/docs/agent-gateway-mcp-quotas.md @@ -19,7 +19,7 @@ limitations under the License. Agent Gateway can enforce a shared invocation-count window and concurrency limit for actual MCP `tools/call` requests. The first policy dimensions are -trusted tenant and subject; local and federated tools use the same admission +trusted tenant and subject, each using `invocation-limit`. Local and federated tools use the same admission boundary. Tool discovery, resource reads, and other MCP methods do not consume these quotas. @@ -52,25 +52,31 @@ diagnostic metadata and does not shard Redis state. `shadow` evaluates and records isolated would-deny decisions but never rejects the call and never debits enforce state. `enforce` rejects at the actual tool -execution boundary. A denied local tool is never executed. +execution boundary. A denied tool is never executed. Missing or invalid tenant or +subject is an explicit identity rejection (403 / `-32027`), including in shadow +mode; unrelated callers never share an `unknown` tenant bucket. ## Redis semantics -Admission is one Lua operation. It atomically checks the invocation counter, +Admission is one Lua operation. Redis `TIME` controls fixed windows and lease +expiry; gateway clocks never select windows or reclaim live leases. +It atomically checks the tenant and subject invocation counters, removes expired concurrency leases, checks concurrency, debits the count, and adds a unique lease token. Redis returns one of invocation-limited, concurrency-limited, or admitted-with-lease; it never debits or acquires a lease for a rejected request. -Keys are scoped by mode, tenant, and subject: +All admission keys share one Redis Cluster hash tag derived from mode and +base64url-encoded tenant; subject components are encoded independently: -- `shenyu:agent:mcp-quota:invocation:{mode}:{tenant}:{subject}:{windowStart}`; -- `shenyu:agent:mcp-quota:concurrency:{mode}:{tenant}:{subject}`. +- `shenyu:agent:mcp-quota:invocation:{mode:encodedTenant}`; +- `shenyu:agent:mcp-quota:invocation:{mode:encodedTenant}:encodedSubject`; +- `shenyu:agent:mcp-quota:concurrency:{mode:encodedTenant}:encodedSubject`. -The invocation key expires one second after its fixed window. The concurrency -sorted set stores one member per in-flight lease and expires one second after -the configured lease TTL. Cardinality is therefore bounded by active tenant and -subject identities, one invocation key per active fixed window per identity, +Window hashes store the server-computed window and count and expire just after +that window. The concurrency sorted set stores one member per in-flight lease +and expires just after its lease TTL. Cardinality is bounded by active tenant and +subject identities, one active invocation hash per identity, and at most the configured concurrency count per identity. Completion, error, cancellation, or subscriber cancellation releases only the @@ -83,8 +89,11 @@ have occurred. There is no lease renewal in this first policy. A lease carries one immutable expiry and cannot be resurrected. If a gateway disappears, its lease is ignored and removed after at most the configured `lease-ttl`, plus the documented -one-second key-expiration buffer. Existing request deadlines remain the -execution-time boundary. +key-expiration buffer. Tool deadlines longer than `lease-ttl` are rejected as +policy errors before Redis admission. Set `lease-ttl` at least as high as the +largest tool timeout; enforced execution is also bounded by the lease TTL. +Local and remote capacity admission precede quota consumption, so overload +rejection never consumes an invocation. ## Outages and observability @@ -103,6 +112,18 @@ shenyu_agent_governance_decisions_total{consumer,mode,result,reason} Tenant, subject, tool name, endpoint, request id, and trace id are not metric labels. Non-allow decisions can also be emitted as metadata-only audit events through the application-provided audit observer. +Would-deny decisions are also counted in the governor's bounded, generation-owned +`AgentGovernanceShadowLedger`, available through `shadowSnapshot()`, separately +from enforce Redis state. + +## Redis regression checks + +The `Agent MCP Redis quota` workflow starts a real Redis node with Cluster slot +enforcement and assigns all slots to it. It requires the Redis tests to run +without skipped cases. Tests use independent connections, skewed gateway times, +actual Redis window/lease boundaries, tenant aggregate limits and tenant +isolation. This verifies script slot correctness; it does not simulate +multi-node Cluster failover. ## Non-goals diff --git a/docs/agent-gateway-resource-admission.md b/docs/agent-gateway-resource-admission.md index 95d7bbe8a828..0bb9a9a50517 100644 --- a/docs/agent-gateway-resource-admission.md +++ b/docs/agent-gateway-resource-admission.md @@ -1,3 +1,20 @@ + + # Agent Gateway resource admission Agent Gateway applies deterministic admission around every `tools/call` execution. Admission is deliberately not a retry or circuit-breaking layer: a call still executes at most once. diff --git a/docs/agent-governance-decision.md b/docs/agent-governance-decision.md index 8128030dde39..8d3d932ead91 100644 --- a/docs/agent-governance-decision.md +++ b/docs/agent-governance-decision.md @@ -1,3 +1,20 @@ + + # 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. @@ -22,4 +39,8 @@ Shadow/enforce comparison is explicit: `SAME_EFFECT`, `SHADOW_STRICTER`, or `ENF ## 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. +This document defines the shared vocabulary and bounded shadow state. The MCP +consumer and its Redis admission, execution-point wiring and decision audit are +described in [distributed MCP quotas](agent-gateway-mcp-quotas.md). +Token reservation, cost settlement and provider usage parsing remain separate +consumers and are not implemented by this contract. diff --git a/docs/agent-invocation-audit.md b/docs/agent-invocation-audit.md index 23ce5ba19a9c..daad45dc1090 100644 --- a/docs/agent-invocation-audit.md +++ b/docs/agent-invocation-audit.md @@ -1,3 +1,20 @@ + + # Agent invocation audit Agent Gateway and AI Proxy can emit metadata-only invocation audit events when `shenyu.plugins.agent.audit.enabled=true`. diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java index 2019a5597a8f..7f24cd6290b4 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java @@ -132,11 +132,7 @@ private static Result normalizeResult(final Result candidate, final Mode mode, f } private static String boundedText(final String value, final String name) { - if (Objects.isNull(value) || value.isBlank() || value.length() > 128 - || !value.equals(value.strip()) || value.chars().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException(name + " must be bounded nonblank text"); - } - return value; + return AgentGovernanceText.require(value, name, 128); } public enum Consumer { diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouter.java b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouter.java index dc9859637884..a78f2400bac8 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouter.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecisionRouter.java @@ -41,9 +41,9 @@ public AgentGovernanceDecisionRouter(final AgentGovernanceDecision.Consumer cons final String ledgerGeneration) { this.consumer = Objects.requireNonNull(consumer, "consumer"); this.mode = Objects.requireNonNull(mode, "mode"); - this.policyVersion = Objects.requireNonNull(policyVersion, "policyVersion"); - this.configurationVersion = Objects.requireNonNull(configurationVersion, "configurationVersion"); - this.ledgerGeneration = Objects.requireNonNull(ledgerGeneration, "ledgerGeneration"); + this.policyVersion = AgentGovernanceText.require(policyVersion, "policyVersion", 128); + this.configurationVersion = AgentGovernanceText.require(configurationVersion, "configurationVersion", 128); + this.ledgerGeneration = AgentGovernanceText.require(ledgerGeneration, "ledgerGeneration", 128); } public AgentGovernanceDecision allow(final String correlationId, final Instant effectiveTime) { diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceText.java b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceText.java new file mode 100644 index 000000000000..4d708dd9872c --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceText.java @@ -0,0 +1,52 @@ +/* + * 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.governance; + +import java.util.Objects; + +/** Shared exact-text validation; invalid identities are never silently normalized. */ +public final class AgentGovernanceText { + + private AgentGovernanceText() { + } + + /** + * Check text against a field-specific bound. + * @param value exact field value + * @param maximum maximum characters + * @return whether the field is valid + */ + public static boolean valid(final String value, final int maximum) { + return Objects.nonNull(value) && !value.isBlank() && value.length() <= maximum + && value.equals(value.strip()) && value.chars().noneMatch(Character::isISOControl); + } + + /** + * Require exact bounded text. + * @param value field value + * @param name safe static field name + * @param maximum maximum characters + * @return original valid value + */ + public static String require(final String value, final String name, final int maximum) { + if (!valid(value, maximum)) { + throw new IllegalArgumentException(name + " must be bounded nonblank text"); + } + return value; + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaConfig.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaConfig.java index 9bc3eb2b2c74..abe97a57e18d 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaConfig.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaConfig.java @@ -19,7 +19,6 @@ import java.time.Duration; import java.util.Objects; -import java.util.UUID; /** Immutable deployment-owned MCP quota policy. */ public final class AgentMcpQuotaConfig { @@ -81,10 +80,6 @@ public boolean isFailOpen() { return failOpen; } - public String newGeneration() { - return UUID.randomUUID().toString(); - } - private static Duration requireBounded(final Duration value, final Duration minimum, final Duration maximum, final String name) { if (Objects.isNull(value) || value.compareTo(minimum) < 0 || value.compareTo(maximum) > 0) { throw new IllegalArgumentException(name + " is outside its allowed range"); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernor.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernor.java index 794418d1e945..5a57b231f9f1 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernor.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernor.java @@ -18,6 +18,9 @@ package org.apache.shenyu.plugin.agent.gateway.governance; import org.apache.shenyu.common.governance.AgentGovernanceDecision; +import org.apache.shenyu.common.governance.AgentGovernanceShadowLedger; +import org.apache.shenyu.common.governance.AgentGovernanceDecisionRouter; +import org.apache.shenyu.common.governance.AgentGovernanceText; import org.apache.shenyu.common.audit.AgentGovernanceAuditAdapter; import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; import org.apache.shenyu.common.dto.AgentRequestContext; @@ -49,6 +52,8 @@ public final class AgentMcpQuotaGovernor { private final String ledgerGeneration; + private final AgentGovernanceShadowLedger shadowLedger; + public AgentMcpQuotaGovernor(final AgentMcpQuotaConfig config, final AgentMcpQuotaStore store, final AgentRuntimeMetrics metrics, final String policyVersion) { this(config, store, metrics, policyVersion, null); @@ -70,7 +75,8 @@ public AgentMcpQuotaGovernor(final AgentMcpQuotaConfig config, final AgentMcpQuo this.metrics = Objects.isNull(metrics) ? AgentRuntimeMetrics.NOOP : metrics; this.audit = audit; this.policyVersion = bounded(policyVersion, "policyVersion"); - this.ledgerGeneration = config.newGeneration(); + this.ledgerGeneration = UUID.randomUUID().toString(); + this.shadowLedger = new AgentGovernanceShadowLedger(ledgerGeneration, config.getConcurrencyLimit()); } /** Wrap an execution with atomic admission and idempotent lease release. @@ -85,18 +91,47 @@ public AgentMcpQuotaGovernor(final AgentMcpQuotaConfig config, final AgentMcpQuo */ public Mono withQuota(final String tenant, final String subject, final String correlationId, final long configurationVersion, final Mono execution) { + return withQuota(tenant, subject, correlationId, configurationVersion, null, execution); + } + + /** + * Admit only identities and deadlines that can be represented by this policy. + * @param execution result + * @param tenant trusted tenant + * @param subject trusted subject + * @param correlationId request identity + * @param configurationVersion rule generation + * @param deadline absolute tool deadline, if present + * @param execution actual deferred execution + * @return governed result + */ + public Mono withQuota(final String tenant, final String subject, final String correlationId, + final long configurationVersion, final Instant deadline, final Mono execution) { Objects.requireNonNull(execution, "execution"); - String normalizedTenant = bounded(tenant, "tenant"); - String normalizedSubject = bounded(subject, "subject"); String normalizedCorrelation = bounded(correlationId, "correlationId"); - Instant effectiveTime = Instant.now(); String configuration = Long.toString(configurationVersion); return Mono.deferContextual(context -> Mono.just(new GovernorContext(context))) .flatMap(governorContext -> { + Instant effectiveTime = Instant.now(); AgentRuntimeMetrics selectedMetrics = governorContext.metrics == AgentRuntimeMetrics.NOOP ? metrics : governorContext.metrics; AgentRequestContext requestContext = governorContext.requestContext; - return store.admit(config, normalizedTenant, normalizedSubject, normalizedCorrelation, effectiveTime) + if (!validIdentity(tenant) || !validIdentity(subject)) { + AgentGovernanceDecision rejected = router(configuration).mandatoryDeny(normalizedCorrelation, effectiveTime, + AgentGovernanceDecision.Reason.AUTHENTICATION_REJECTED); + report(rejected, selectedMetrics, requestContext); + return Mono.error(new AgentMcpQuotaException(rejected)); + } + if (Objects.nonNull(deadline) && deadline.isAfter(effectiveTime.plus(config.getLeaseTtl()))) { + AgentGovernanceDecision rejected = AgentGovernanceDecision.builder( + AgentGovernanceDecision.Consumer.MCP_QUOTA, AgentGovernanceDecision.Mode.ENFORCE) + .policyVersion(policyVersion).configurationVersion(configuration) + .result(AgentGovernanceDecision.Result.DENY).reason(AgentGovernanceDecision.Reason.POLICY_ERROR) + .correlationId(normalizedCorrelation).ledgerGeneration(ledgerGeneration).effectiveTime(effectiveTime).build(); + report(rejected, selectedMetrics, requestContext); + return Mono.error(new AgentMcpQuotaException(rejected)); + } + return store.admit(config, tenant, subject, normalizedCorrelation, effectiveTime) .map(admission -> Map.entry(admission, false)) .onErrorResume(error -> policyUnavailable(error, selectedMetrics, requestContext, normalizedCorrelation, configuration, effectiveTime)) @@ -104,10 +139,9 @@ public Mono withQuota(final String tenant, final String subject, final St boolean policyUnavailable = admission.getValue(); AgentGovernanceDecision decision = decision(admission.getKey(), policyUnavailable, normalizedCorrelation, configuration, effectiveTime); - AgentRuntimeMetrics.safely(() -> selectedMetrics.governanceDecision(decision)); - if (Objects.nonNull(requestContext) && Objects.nonNull(audit) - && decision.getReason() != AgentGovernanceDecision.Reason.ALLOWED) { - AgentRuntimeMetrics.safely(() -> audit.record(AgentGovernanceAuditAdapter.toEvent(requestContext, decision))); + report(decision, selectedMetrics, requestContext); + if (decision.getResult() == AgentGovernanceDecision.Result.WOULD_DENY) { + shadowLedger.observe(decision); } if (decision.deniesTraffic()) { return Mono.error(new AgentMcpQuotaException(decision)); @@ -116,14 +150,34 @@ public Mono withQuota(final String tenant, final String subject, final St return execution; } return Mono.usingWhen(Mono.just(admission.getKey()), - ignored -> execution, - ignored -> releaseOnce(normalizedTenant, normalizedSubject, normalizedCorrelation, admission.getKey().lease()), - (ignored, error) -> releaseOnce(normalizedTenant, normalizedSubject, normalizedCorrelation, admission.getKey().lease()), - ignored -> releaseOnce(normalizedTenant, normalizedSubject, normalizedCorrelation, admission.getKey().lease())); + ignored -> config.getMode() == AgentMcpQuotaConfig.Mode.ENFORCE ? execution.timeout(config.getLeaseTtl()) : execution, + ignored -> releaseOnce(tenant, subject, normalizedCorrelation, admission.getKey().lease()), + (ignored, error) -> releaseOnce(tenant, subject, normalizedCorrelation, admission.getKey().lease()), + ignored -> releaseOnce(tenant, subject, normalizedCorrelation, admission.getKey().lease())); }); }); } + /** + * Observe isolated shadow decisions without identity or unbounded labels. + * @return immutable bounded shadow snapshot + */ + public AgentGovernanceShadowLedger.AgentGovernanceShadowSnapshot shadowSnapshot() { + return shadowLedger.snapshot(); + } + + private void report(final AgentGovernanceDecision decision, final AgentRuntimeMetrics selectedMetrics, final AgentRequestContext requestContext) { + AgentRuntimeMetrics.safely(() -> selectedMetrics.governanceDecision(decision)); + if (Objects.nonNull(requestContext) && Objects.nonNull(audit) + && decision.getReason() != AgentGovernanceDecision.Reason.ALLOWED) { + AgentRuntimeMetrics.safely(() -> audit.record(AgentGovernanceAuditAdapter.toEvent(requestContext, decision))); + } + } + + private static boolean validIdentity(final String value) { + return AgentGovernanceText.valid(value, 256); + } + private Mono> policyUnavailable(final Throwable error, final AgentRuntimeMetrics selectedMetrics, final AgentRequestContext requestContext, @@ -163,6 +217,10 @@ private AgentGovernanceDecision decision(final AgentMcpQuotaStore.Admission admi ? AgentGovernanceDecision.Reason.MCP_INVOCATION_LIMIT : admission.concurrencyLimited() ? AgentGovernanceDecision.Reason.MCP_CONCURRENCY_LIMIT : AgentGovernanceDecision.Reason.ALLOWED; + if (!policyUnavailable) { + return admission.allowed() ? router(configurationVersion).allow(correlationId, effectiveTime) + : router(configurationVersion).deny(correlationId, effectiveTime, reason); + } AgentGovernanceDecision.Result result = policyUnavailable && config.isFailOpen() ? AgentGovernanceDecision.Result.ALLOW : admission.allowed() ? AgentGovernanceDecision.Result.ALLOW : config.getMode() == AgentMcpQuotaConfig.Mode.SHADOW @@ -175,12 +233,14 @@ private AgentGovernanceDecision decision(final AgentMcpQuotaStore.Admission admi .ledgerGeneration(ledgerGeneration).effectiveTime(effectiveTime).build(); } + private AgentGovernanceDecisionRouter router(final String configurationVersion) { + return new AgentGovernanceDecisionRouter(AgentGovernanceDecision.Consumer.MCP_QUOTA, + config.getMode() == AgentMcpQuotaConfig.Mode.SHADOW ? AgentGovernanceDecision.Mode.SHADOW : AgentGovernanceDecision.Mode.ENFORCE, + policyVersion, configurationVersion, ledgerGeneration); + } + private static String bounded(final String value, final String name) { - if (Objects.isNull(value) || value.isBlank() || value.length() > 256 - || !value.equals(value.strip()) || value.chars().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException(name + " must be bounded nonblank text"); - } - return value; + return AgentGovernanceText.require(value, name, 128); } private static final class GovernorContext { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaStore.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaStore.java index fd9265a3f798..e5726bc94923 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaStore.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaStore.java @@ -18,6 +18,7 @@ package org.apache.shenyu.plugin.agent.gateway.governance; import reactor.core.publisher.Mono; +import org.apache.shenyu.common.governance.AgentGovernanceText; import java.util.Objects; import java.time.Instant; @@ -65,9 +66,8 @@ record Admission(boolean allowed, boolean invocationLimited, boolean concurrency if (allowed && Objects.isNull(lease)) { throw new IllegalArgumentException("An admitted decision requires a lease"); } - if (allowed && (lease.isBlank() || lease.length() > 128 || !lease.equals(lease.strip()) - || lease.chars().anyMatch(Character::isISOControl))) { - throw new IllegalArgumentException("An admitted lease must be bounded nonblank text"); + if (allowed) { + AgentGovernanceText.require(lease, "lease", 128); } if (!allowed && !Objects.toString(lease, "").isEmpty()) { throw new IllegalArgumentException("A rejected decision must not retain a lease"); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/RedisAgentMcpQuotaStore.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/RedisAgentMcpQuotaStore.java index 7056d8b912e6..41cfe9f328f4 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/RedisAgentMcpQuotaStore.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/RedisAgentMcpQuotaStore.java @@ -46,20 +46,14 @@ public RedisAgentMcpQuotaStore(final ReactiveRedisTemplate redis public Mono admit(final AgentMcpQuotaConfig policy, final String tenant, final String subject, final String correlationId, final Instant now) { Objects.requireNonNull(now, "now"); - long windowSeconds = policy.getInvocationWindow().toSeconds(); - long windowStart = Math.floorDiv(now.getEpochSecond(), windowSeconds) - * policy.getInvocationWindow().toSeconds(); - long invocationTtl = windowStart + windowSeconds - now.getEpochSecond() + 1; - long leaseExpiry = now.plus(policy.getLeaseTtl()).getEpochSecond(); String lease = UUID.randomUUID().toString(); - String scope = (policy.getMode() == AgentMcpQuotaConfig.Mode.SHADOW ? "shadow" : "enforce") - + ":" + scopePart(tenant) + ":" + scopePart(subject); - String invocationKey = "shenyu:agent:mcp-quota:invocation:" + scope + ":" + windowStart; + String scope = scope(policy, tenant, subject); + String invocationKey = "shenyu:agent:mcp-quota:invocation:" + scope; + String tenantKey = "shenyu:agent:mcp-quota:invocation:" + tag(policy, tenant); String concurrencyKey = "shenyu:agent:mcp-quota:concurrency:" + scope; - return redis.execute(ADMIT, List.of(invocationKey, concurrencyKey), - List.of(Long.toString(policy.getInvocationLimit()), Long.toString(windowStart), - Long.toString(invocationTtl), Integer.toString(policy.getConcurrencyLimit()), - lease, Long.toString(leaseExpiry), Long.toString(policy.getLeaseTtl().toSeconds() + 1), Long.toString(now.getEpochSecond()))) + return redis.execute(ADMIT, List.of(invocationKey, concurrencyKey, tenantKey), + List.of(Long.toString(policy.getInvocationLimit()), Long.toString(policy.getInvocationWindow().toMillis()), + Integer.toString(policy.getConcurrencyLimit()), lease, Long.toString(policy.getLeaseTtl().toMillis()))) .next() .map(values -> new Admission(flag(values, 0), flag(values, 1), flag(values, 2), @@ -70,14 +64,21 @@ public Mono admit(final AgentMcpQuotaConfig policy, final String tena public Mono release(final AgentMcpQuotaConfig policy, final String tenant, final String subject, final String correlationId, final String lease) { Objects.requireNonNull(lease, "lease"); - String scope = (policy.getMode() == AgentMcpQuotaConfig.Mode.SHADOW ? "shadow" : "enforce") - + ":" + scopePart(tenant) + ":" + scopePart(subject); + String scope = scope(policy, tenant, subject); String concurrencyKey = "shenyu:agent:mcp-quota:concurrency:" + scope; return redis.execute(RELEASE, List.of(concurrencyKey), List.of(lease)) .next() .map(value -> Objects.equals("1", Objects.toString(value, null))); } + private static String scope(final AgentMcpQuotaConfig policy, final String tenant, final String subject) { + return tag(policy, tenant) + ":" + scopePart(subject); + } + + private static String tag(final AgentMcpQuotaConfig policy, final String tenant) { + return "{" + (policy.getMode() == AgentMcpQuotaConfig.Mode.SHADOW ? "shadow" : "enforce") + ":" + scopePart(tenant) + "}"; + } + private static String scopePart(final String value) { return Base64.getUrlEncoder().withoutPadding() .encodeToString(value.getBytes(StandardCharsets.UTF_8)); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java index 63d8a9807ade..6b085d0213bb 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java @@ -214,8 +214,10 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier routeWithRemote(final AgentMcpRequest request, final Ag final AgentMcpResultFilter filter = prepareResultFilter(request, context, name, definitions.get(name).get("outputSchema")); ObjectNode params = request.getParams(); JsonObject arguments = params.has("arguments") ? JsonParser.parseString(params.get("arguments").toString()).getAsJsonObject() : new JsonObject(); - return withQuota(context, Mono.defer(() -> admission.withRemote(remoteServer(name), context.getDeadline(), - Mono.fromRunnable(context::notifyAttempt).then(snapshot.invoke(name, arguments, context))))) + return admission.withRemote(remoteServer(name), context.getDeadline(), + withQuota(context, Mono.fromRunnable(context::notifyAttempt).then(Mono.defer(() -> snapshot.invoke(name, arguments, context))))) .switchIfEmpty(Mono.error(new IllegalStateException("Remote tool completed without a result"))) .map(value -> { ObjectNode result = value.deepCopy(); @@ -384,8 +386,8 @@ private Mono withQuota(final AgentMcpExecutionContext context, final Mono if (Objects.isNull(quotaGovernor)) { return execution; } - return quotaGovernor.withQuota(context.getTenant().orElse("unknown"), context.getSubject(), - context.getRequestId(), context.getConfigurationVersion(), execution); + return quotaGovernor.withQuota(context.getTenant().orElse(null), context.getSubject(), + context.getRequestId(), context.getConfigurationVersion(), context.getDeadline(), execution); } private AgentMcpResultFilter prepareResultFilter(final AgentMcpRequest request, final AgentMcpExecutionContext context, diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java index 5de88a82121b..8adb6a6c61f6 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java @@ -42,7 +42,7 @@ public Mono withRemote(final String server, final Instant deadline, final /** Bound one local-provider execution. * @param deadline absolute request deadline * @param action controlled execution -* @param result type + * @param result type * @return controlled result */ Mono withLocal(Instant deadline, Mono action); @@ -51,7 +51,7 @@ public Mono withRemote(final String server, final Instant deadline, final * @param server stable target name, never Agent input * @param deadline absolute request deadline * @param action controlled execution -* @param result type + * @param result type * @return controlled result */ Mono withRemote(String server, Instant deadline, Mono action); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota-release.lua b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota-release.lua index 26a0bba456cf..2d6efedcadd6 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota-release.lua +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota-release.lua @@ -13,7 +13,7 @@ -- 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. ---/ +-- -- Idempotently remove one owned MCP concurrency lease. -- KEYS[1] concurrency lease set diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota.lua b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota.lua index 55e3f5e1bca9..89207b00bb78 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota.lua +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota.lua @@ -13,30 +13,44 @@ -- 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. ---/ +-- -- Atomic MCP invocation and concurrency admission. --- KEYS[1] invocation window counter +-- All keys share the mode/tenant hash tag, including the tenant aggregate. +-- KEYS[1] subject window hash -- KEYS[2] concurrency lease set +-- KEYS[3] tenant window hash -- ARGV[1] invocation limit --- ARGV[2] window start epoch second --- ARGV[3] invocation window TTL seconds --- ARGV[4] concurrency limit --- ARGV[5] lease token --- ARGV[6] lease expiry epoch second --- ARGV[7] concurrency key TTL seconds --- ARGV[8] current epoch second +-- ARGV[2] window milliseconds +-- ARGV[3] subject concurrency limit +-- ARGV[4] lease token +-- ARGV[5] lease TTL milliseconds -- Returns {allowed, invocationLimited, concurrencyLimited, lease} -local invocation = tonumber(redis.call('GET', KEYS[1]) or '0') -if invocation >= tonumber(ARGV[1]) then +local clock = redis.call('TIME') +local now = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000) +local windowSize = tonumber(ARGV[2]) +local window = math.floor(now / windowSize) * windowSize +local function count(key) + if tonumber(redis.call('HGET', key, 'window')) ~= window then + return 0 + end + return tonumber(redis.call('HGET', key, 'count') or '0') +end +local subjectCount = count(KEYS[1]) +local tenantCount = count(KEYS[3]) +if subjectCount >= tonumber(ARGV[1]) or tenantCount >= tonumber(ARGV[1]) then return {0, 1, 0, ''} end -redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', ARGV[8]) +redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', now) local concurrency = redis.call('ZCARD', KEYS[2]) -if concurrency >= tonumber(ARGV[4]) then +if concurrency >= tonumber(ARGV[3]) then return {0, 0, 1, ''} end -redis.call('SET', KEYS[1], invocation + 1, 'EX', ARGV[3]) -redis.call('ZADD', KEYS[2], ARGV[6], ARGV[5]) -redis.call('EXPIRE', KEYS[2], ARGV[7]) -return {1, 0, 0, ARGV[5]} +local ttl = window + windowSize - now + 1 +redis.call('HSET', KEYS[1], 'window', window, 'count', subjectCount + 1) +redis.call('PEXPIRE', KEYS[1], ttl) +redis.call('HSET', KEYS[3], 'window', window, 'count', tenantCount + 1) +redis.call('PEXPIRE', KEYS[3], ttl) +redis.call('ZADD', KEYS[2], now + tonumber(ARGV[5]), ARGV[4]) +redis.call('PEXPIRE', KEYS[2], math.max(redis.call('PTTL', KEYS[2]), tonumber(ARGV[5]) + 1)) +return {1, 0, 0, ARGV[4]} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernorTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernorTest.java index 033da86fe35e..96d2a60ea676 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernorTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernorTest.java @@ -63,6 +63,7 @@ void shadowDenyStillExecutesAndReleasesShadowLease() { assertEquals(1, store.admissions); assertTrue(awaitRelease(store.releaseCount)); assertEquals(AgentGovernanceDecision.Result.WOULD_DENY, decisions.get(0).getResult()); + assertEquals(1, governor.shadowSnapshot().observedDenials()); } @Test @@ -94,6 +95,30 @@ void failOpenPolicyErrorAllowsTrafficWithoutPretendingToOwnLease() { assertEquals(AgentGovernanceDecision.Result.ALLOW, decisions.get(0).getResult()); } + @Test + void missingIdentityRejectsBeforeRedisEvenWhenFailOpenOrShadow() { + RecordingStore store = new RecordingStore(new AgentMcpQuotaStore.Admission(true, false, false, "lease")); + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.SHADOW, store, true); + for (String identity : java.util.Arrays.asList(null, "", " padded", "bad\nidentity")) { + StepVerifier.create(governor.withQuota(identity, "subject", "request", 1, Mono.just("value"))) + .expectErrorSatisfies(error -> assertEquals(AgentGovernanceDecision.Reason.AUTHENTICATION_REJECTED, + ((AgentMcpQuotaException) error).getDecision().getReason())).verify(); + StepVerifier.create(governor.withQuota("tenant", identity, "request", 1, Mono.just("value"))) + .expectError(AgentMcpQuotaException.class).verify(); + } + assertEquals(0, store.admissions); + } + + @Test + void deadlineCannotOutliveItsConcurrencyLeaseEvenWhenFailOpen() { + RecordingStore store = new RecordingStore(new AgentMcpQuotaStore.Admission(true, false, false, "lease")); + AgentMcpQuotaGovernor governor = governor(AgentMcpQuotaConfig.Mode.ENFORCE, store, true); + StepVerifier.create(governor.withQuota("tenant", "subject", "request", 1, Instant.now().plusSeconds(3600), Mono.just("value"))) + .expectErrorSatisfies(error -> assertEquals(AgentGovernanceDecision.Reason.POLICY_ERROR, + ((AgentMcpQuotaException) error).getDecision().getReason())).verify(); + assertEquals(0, store.admissions); + } + @Test void failClosedPolicyErrorRejectsTraffic() { RecordingStore store = new RecordingStore(null); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java index 1261ebf74e6f..a90142009c5f 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java @@ -19,6 +19,8 @@ import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.AfterEach; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.ReactiveRedisTemplate; @@ -33,7 +35,9 @@ import java.time.Instant; import java.util.List; import java.util.UUID; +import java.util.ArrayList; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -44,6 +48,8 @@ final class AgentMcpQuotaRedisStoreTest { private static final int PORT = Integer.getInteger("shenyu.agent.mcp-quota.redis.port", 6379); + private final List factories = new ArrayList<>(); + private static boolean isRedisAvailable() { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(HOST, PORT), 500); @@ -53,9 +59,22 @@ private static boolean isRedisAvailable() { } } - private static ReactiveRedisTemplate template() { + @BeforeAll + static void requiredRedisMustBeAvailable() { + if (Boolean.getBoolean("shenyu.agent.mcp-quota.redis.required")) { + assertTrue(isRedisAvailable(), "Required real Redis service is unavailable"); + } + } + + @AfterEach + void closeConnections() { + factories.forEach(LettuceConnectionFactory::destroy); + } + + private ReactiveRedisTemplate template() { LettuceConnectionFactory factory = new LettuceConnectionFactory(new RedisStandaloneConfiguration(HOST, PORT)); factory.afterPropertiesSet(); + factories.add(factory); RedisSerializationContext serializationContext = RedisSerializationContext.newSerializationContext() .key(StringRedisSerializer.UTF_8) @@ -73,10 +92,10 @@ void twoStoreInstancesCannotExceedSharedInvocationLimit() { String tenant = tenant(); AgentMcpQuotaConfig policy = policy(AgentMcpQuotaConfig.Mode.ENFORCE, 5, 100); RedisAgentMcpQuotaStore first = new RedisAgentMcpQuotaStore(template); - RedisAgentMcpQuotaStore second = new RedisAgentMcpQuotaStore(template); + RedisAgentMcpQuotaStore second = new RedisAgentMcpQuotaStore(template()); long allowed = Flux.range(0, 10) .flatMap(index -> (index % 2 == 0 ? first : second) - .admit(policy, tenant, "subject", UUID.randomUUID().toString(), Instant.now())) + .admit(policy, tenant, "subject", UUID.randomUUID().toString(), Instant.now().plusSeconds(index % 2 == 0 ? 3600 : -3600))) .filter(AgentMcpQuotaStore.Admission::allowed) .count() .block(Duration.ofSeconds(10)); @@ -123,7 +142,7 @@ void aLaterArrivalCannotReclaimAnUnexpiredLease() { .block(Duration.ofSeconds(5)); assertFalse(second.allowed()); assertTrue(second.concurrencyLimited()); - assertTrue(store.admit(policy, tenant, subject, "expired", now.plusSeconds(30)).block(Duration.ofSeconds(5)).allowed()); + assertFalse(store.admit(policy, tenant, subject, "skewed", now.plusSeconds(3600)).block(Duration.ofSeconds(5)).allowed()); } @Test @@ -141,9 +160,8 @@ void expiredLeaseRecoversWithinConfiguredBound() { UUID.randomUUID().toString(), Instant.now()).block(Duration.ofSeconds(5)); assertFalse(denied.allowed()); assertTrue(denied.concurrencyLimited()); - AgentMcpQuotaStore.Admission afterExpiry = store.admit(policy, tenant, subject, - UUID.randomUUID().toString(), Instant.now().plusSeconds(2)).block(Duration.ofSeconds(5)); - assertTrue(afterExpiry.allowed()); + await().atMost(Duration.ofSeconds(5)).until(() -> store.admit(policy, tenant, subject, + UUID.randomUUID().toString(), Instant.now().minusSeconds(3600)).block(Duration.ofSeconds(2)).allowed()); } @Test @@ -173,15 +191,26 @@ void invocationQuotaUsesDeterministicFixedWindows() { String tenant = tenant(); String subject = subject(); AgentMcpQuotaConfig policy = AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, - 1, Duration.ofSeconds(60), 100, Duration.ofSeconds(60), false); + 1, Duration.ofSeconds(1), 100, Duration.ofSeconds(60), false); RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template); long stableWindow = Math.floorDiv(Instant.now().plusSeconds(60).getEpochSecond(), 60) * 60L; assertTrue(store.admit(policy, tenant, subject, UUID.randomUUID().toString(), Instant.ofEpochSecond(stableWindow)) .block(Duration.ofSeconds(5)).allowed()); assertFalse(store.admit(policy, tenant, subject, UUID.randomUUID().toString(), Instant.ofEpochSecond(stableWindow + 1)) .block(Duration.ofSeconds(5)).allowed()); - assertTrue(store.admit(policy, tenant, subject, UUID.randomUUID().toString(), Instant.ofEpochSecond(stableWindow + 60)) - .block(Duration.ofSeconds(5)).allowed()); + await().atMost(Duration.ofSeconds(5)).until(() -> store.admit(policy, tenant, subject, UUID.randomUUID().toString(), + Instant.ofEpochSecond(stableWindow + 3600)).block(Duration.ofSeconds(2)).allowed()); + } + + @Test + void tenantAggregateCannotBeBypassedWithAnotherSubject() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template()); + String tenant = tenant(); + AgentMcpQuotaConfig policy = policy(AgentMcpQuotaConfig.Mode.ENFORCE, 1, 100); + assertTrue(store.admit(policy, tenant, "first", "one", Instant.now()).block(Duration.ofSeconds(5)).allowed()); + assertTrue(store.admit(policy, tenant, "second", "two", Instant.now().plusSeconds(3600)) + .block(Duration.ofSeconds(5)).invocationLimited()); } @Test @@ -204,9 +233,10 @@ void encodedDimensionsCannotCollideAcrossTenantAndSubjectBoundaries() { ReactiveRedisTemplate template = template(); AgentMcpQuotaConfig policy = policy(AgentMcpQuotaConfig.Mode.ENFORCE, 1, 100); RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template); - assertTrue(store.admit(policy, "tenant", "subject:tool", UUID.randomUUID().toString(), Instant.now()) + String prefix = tenant(); + assertTrue(store.admit(policy, prefix, "subject:tool", UUID.randomUUID().toString(), Instant.now()) .block(Duration.ofSeconds(5)).allowed()); - assertTrue(store.admit(policy, "tenant:subject", "tool", UUID.randomUUID().toString(), Instant.now()) + assertTrue(store.admit(policy, prefix + ":subject", "tool", UUID.randomUUID().toString(), Instant.now()) .block(Duration.ofSeconds(5)).allowed()); } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java index d8239726c48f..8ac754fa61ee 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java @@ -578,12 +578,68 @@ public Mono invoke(final String name, final JsonObject arguments, fi assertEquals(0, calls.get()); } + @Test + void remoteCapacityRejectionDoesNotConsumeInvocationQuota() throws InterruptedException { + AtomicInteger admissions = new AtomicInteger(); + AgentMcpQuotaStore store = new AgentMcpQuotaStore() { + @Override + public Mono admit(final AgentMcpQuotaConfig policy, final String tenant, final String subject, + final String correlationId, final Instant now) { + admissions.incrementAndGet(); + return Mono.just(new Admission(true, false, false, "lease")); + } + + @Override + public Mono release(final AgentMcpQuotaConfig policy, final String tenant, final String subject, + final String correlationId, final String lease) { + return Mono.just(true); + } + }; + AgentMcpRemoteCatalog catalog = operation -> operation.apply(new AgentMcpRemoteCatalog.Snapshot() { + @Override + public Map definitions() { + ObjectNode definition = new ObjectMapper().createObjectNode().put("name", "remote.lookup"); + definition.putObject("inputSchema").put("type", "object"); + return Map.of("remote.lookup", definition); + } + + @Override + public Mono invoke(final String name, final JsonObject arguments, final AgentMcpExecutionContext context) { + return Mono.error(new AssertionError("Rejected work must not start")); + } + }); + try (AgentMcpResourceAdmission.ResourceAdmissionController admission = AgentMcpResourceAdmission.create( + new org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig(1, 0, 1, 0, 1, 0))) { + CountDownLatch acquired = new CountDownLatch(1); + reactor.core.Disposable holder = admission.withRemote("remote", Instant.now().plusSeconds(5), + Mono.defer(() -> { + acquired.countDown(); + return Mono.never(); + })).subscribe(); + try { + assertTrue(acquired.await(5, TimeUnit.SECONDS)); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher(new AgentToolRegistry(List.of()), "fixture", "1", catalog, + new AgentResourceRegistry(List.of()), admission, + new AgentMcpQuotaGovernor(AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, + 10, Duration.ofSeconds(60), 10, Duration.ofSeconds(60), false), store, AgentRuntimeMetrics.NOOP, "test")); + StepVerifier.create(dispatcher.dispatch(request("tools/call", "1", "remote.lookup"), + () -> context("owner", Set.of("remote.lookup"), Set.of("remote.lookup")))) + .expectErrorSatisfies(error -> assertEquals(429, ((AgentMcpProtocolException) error).getHttpStatus())).verify(); + assertEquals(0, admissions.get()); + } finally { + holder.dispose(); + } + } + } + private AgentMcpExecutionContext context(final String subject, final Set grants) { return context(subject, Set.of("order_status"), grants); } private AgentMcpExecutionContext context(final String subject, final Set ruleTools, final Set grants) { - return new AgentMcpExecutionContext("internal-" + subject, subject, "rule", 1, ruleTools, grants); + return new AgentMcpExecutionContext("internal-" + subject, subject, "rule", 1, ruleTools, grants, + Instant.now().plusSeconds(10), org.apache.shenyu.common.dto.AgentGatewayResultFilterConfig.empty(), + org.apache.shenyu.common.dto.AgentGatewayHttpToolConfig.empty(), null, "tenant"); } private AgentMcpDispatcher dispatcher(final AgentToolProvider... providers) { diff --git a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java index eb1963799fb1..4f9029fc6284 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPlugin.java @@ -132,11 +132,6 @@ private Mono executeRequest(final ServerWebExchange exchange, final Select AiCommonConfig config = aiProxyConfigService.resolvePrimaryConfig(handle); if (Objects.nonNull(realApiKey)) { config.setApiKey(realApiKey); - ProxyApiKeyData mapping = AiProxyApiKeyCache.getInstance() - .getValidatedMapping(selector.getId(), exchange.getRequest().getHeaders().getFirst(Constants.X_API_KEY)); - if (Objects.nonNull(mapping)) { - observation.updateContext(observation.getContext().withApiKeyId(mapping.getId())); - } } return DataBufferUtils.join(exchange.getRequest().getBody(), MAX_REQUEST_BODY_SIZE_BYTES) .switchIfEmpty(Mono.error(new ShenyuException("AI request body must not be empty"))) diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java index ddf288591c7c..e298c20b5e2d 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/AgentRuntimeMetricsReporter.java @@ -18,6 +18,7 @@ package org.apache.shenyu.plugin.metrics.reporter; import org.apache.shenyu.common.governance.AgentGovernanceDecision; +import org.apache.shenyu.common.governance.AgentGovernanceContractLabels; import org.apache.shenyu.common.metrics.AiAttemptEvent; import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.metrics.constant.LabelNames; @@ -88,8 +89,9 @@ public synchronized void authenticationRejected(final AuthenticationSource sourc @Override public synchronized void governanceDecision(final AgentGovernanceDecision decision) { if (active) { - String[] values = {label(decision.getConsumer()), label(decision.getMode()), - label(decision.getResult()), label(decision.getReason())}; + AgentGovernanceContractLabels labels = AgentGovernanceContractLabels.from(decision); + String[] values = {labels.getConsumer().toLowerCase(Locale.ROOT), labels.getMode().toLowerCase(Locale.ROOT), + labels.getResult().toLowerCase(Locale.ROOT), labels.getReason().toLowerCase(Locale.ROOT)}; register.counterIncrement(LabelNames.AGENT_GOVERNANCE_DECISIONS_TOTAL, values, 1); } } diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentMcpQuotaProperties.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentMcpQuotaProperties.java index e74430a5a522..72c331f2cd25 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentMcpQuotaProperties.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentMcpQuotaProperties.java @@ -18,10 +18,10 @@ package org.apache.shenyu.springboot.starter.plugin.agent.gateway; import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaConfig; +import org.apache.shenyu.common.governance.AgentGovernanceText; import org.springframework.boot.context.properties.ConfigurationProperties; import java.time.Duration; -import java.util.Objects; /** * Deployment-owned distributed MCP quota policy. Redis connectivity and lifecycle @@ -32,7 +32,7 @@ public class AgentMcpQuotaProperties { private boolean enabled; - private Mode mode = Mode.SHADOW; + private AgentMcpQuotaConfig.Mode mode = AgentMcpQuotaConfig.Mode.SHADOW; private long invocationLimit = 1000; @@ -54,11 +54,11 @@ public void setEnabled(final boolean enabled) { this.enabled = enabled; } - public Mode getMode() { + public AgentMcpQuotaConfig.Mode getMode() { return mode; } - public void setMode(final Mode mode) { + public void setMode(final AgentMcpQuotaConfig.Mode mode) { this.mode = mode; } @@ -116,21 +116,12 @@ public void setPolicyVersion(final String policyVersion) { * @return validated quota policy */ public AgentMcpQuotaConfig toConfig() { - return AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.valueOf(mode.name()), invocationLimit, + return AgentMcpQuotaConfig.of(mode, invocationLimit, invocationWindow, concurrencyLimit, leaseTtl, failOpen); } public String trustedPolicyVersion() { - if (Objects.isNull(policyVersion) || policyVersion.isBlank() || policyVersion.length() > 128 - || !policyVersion.equals(policyVersion.strip()) - || policyVersion.chars().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException("policyVersion must be bounded nonblank text"); - } - return policyVersion; + return AgentGovernanceText.require(policyVersion, "policyVersion", 128); } - public enum Mode { - SHADOW, - ENFORCE; - } } diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java index dc2a8505eb09..fbd77c294f38 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/test/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfigurationTest.java @@ -260,7 +260,7 @@ void mcpQuotaPropertiesValidateDefaultsAndModeBinding() { assertEquals(100, config.getConcurrencyLimit()); assertEquals(Duration.ofMinutes(1), config.getLeaseTtl()); assertFalse(config.isFailOpen()); - properties.setMode(AgentMcpQuotaProperties.Mode.ENFORCE); + properties.setMode(AgentMcpQuotaConfig.Mode.ENFORCE); assertEquals(AgentMcpQuotaConfig.Mode.ENFORCE, properties.toConfig().getMode()); } From 2c4288da18630caad9c2c975806eb05a1db711e3 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 9 Nov 2026 13:30:22 +0800 Subject: [PATCH 32/36] ci: retrigger checks for MCP resource admission From 1a6ded2545c636e5373b021a305ba3f3c04d2fb9 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Mon, 9 Nov 2026 14:02:52 +0800 Subject: [PATCH 33/36] ci: retry checks after Kubernetes download timeouts From 0e49f78a704c51a58c677db4f76450501049eac7 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Thu, 12 Nov 2026 14:05:02 +0800 Subject: [PATCH 34/36] test(agent-gateway): cover Redis quota failure and lease recovery --- .../AgentMcpQuotaRedisStoreTest.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java index a90142009c5f..b1fa26d29aee 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java @@ -17,6 +17,10 @@ package org.apache.shenyu.plugin.agent.gateway.governance; +import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; +import org.apache.shenyu.common.dto.AgentRequestContext; +import org.apache.shenyu.common.governance.AgentGovernanceDecision; +import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeAll; @@ -27,15 +31,20 @@ import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.StringRedisSerializer; import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.UUID; import java.util.ArrayList; +import java.util.Base64; +import java.util.concurrent.atomic.AtomicBoolean; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -164,6 +173,71 @@ void expiredLeaseRecoversWithinConfiguredBound() { UUID.randomUUID().toString(), Instant.now().minusSeconds(3600)).block(Duration.ofSeconds(2)).allowed()); } + @Test + void realRedisPolicyFailureRejectsBeforeToolExecutionAndRecordsAudit() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + ReactiveRedisTemplate template = template(); + String tenant = tenant(); + String subject = subject(); + String tag = "{enforce:" + Base64.getUrlEncoder().withoutPadding().encodeToString(tenant.getBytes(StandardCharsets.UTF_8)) + "}"; + String tenantKey = "shenyu:agent:mcp-quota:invocation:" + tag; + String concurrencyKey = "shenyu:agent:mcp-quota:concurrency:" + tag + ":" + + Base64.getUrlEncoder().withoutPadding().encodeToString(subject.getBytes(StandardCharsets.UTF_8)); + List decisions = new ArrayList<>(); + List audits = new ArrayList<>(); + AgentRuntimeMetrics metrics = new AgentRuntimeMetrics() { + @Override + public void governanceDecision(final AgentGovernanceDecision decision) { + decisions.add(decision); + } + }; + AgentMcpQuotaGovernor governor = new AgentMcpQuotaGovernor(policy(AgentMcpQuotaConfig.Mode.ENFORCE, 100, 1), + new RedisAgentMcpQuotaStore(template), metrics, "test", audits::add); + AtomicBoolean executed = new AtomicBoolean(); + try { + assertTrue(template.opsForValue().set(tenantKey, "wrong-redis-type", Duration.ofSeconds(10)).block(Duration.ofSeconds(5))); + StepVerifier.create(governor.withQuota(tenant, subject, "policy-error", 1, Mono.fromSupplier(() -> { + executed.set(true); + return "unexpected"; + })).contextWrite(context -> context.put(AgentRequestContext.REACTOR_KEY, + new AgentRequestContext("policy-error", "mcp", "selector", "rule").withIdentity(tenant, subject)))) + .expectErrorSatisfies(error -> { + assertTrue(error instanceof AgentMcpQuotaException); + AgentGovernanceDecision decision = ((AgentMcpQuotaException) error).getDecision(); + assertEquals(AgentGovernanceDecision.Result.DENY, decision.getResult()); + assertEquals(AgentGovernanceDecision.Reason.POLICY_ERROR, decision.getReason()); + }).verify(Duration.ofSeconds(5)); + assertFalse(executed.get()); + assertEquals(1, decisions.size()); + assertEquals(1, audits.size()); + assertEquals(AgentInvocationAuditEvent.Decision.REJECTED, audits.get(0).getDecision()); + assertEquals("POLICY_ERROR", audits.get(0).getReason()); + assertFalse(template.hasKey(concurrencyKey).block(Duration.ofSeconds(5))); + } finally { + template.delete(tenantKey).block(Duration.ofSeconds(5)); + } + } + + @Test + void governorRecoversAfterAnAbandonedRedisLeaseExpires() { + Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); + ReactiveRedisTemplate template = template(); + RedisAgentMcpQuotaStore store = new RedisAgentMcpQuotaStore(template); + AgentMcpQuotaConfig policy = AgentMcpQuotaConfig.of(AgentMcpQuotaConfig.Mode.ENFORCE, + 100, Duration.ofSeconds(60), 1, Duration.ofSeconds(1), false); + AgentMcpQuotaGovernor governor = new AgentMcpQuotaGovernor(policy, store, AgentRuntimeMetrics.NOOP, "test"); + String tenant = tenant(); + String subject = subject(); + assertTrue(store.admit(policy, tenant, subject, "abandoned", Instant.now()).block(Duration.ofSeconds(5)).allowed()); + StepVerifier.create(governor.withQuota(tenant, subject, "before-expiry", 1, Mono.just("unexpected"))) + .expectErrorSatisfies(error -> assertEquals(AgentGovernanceDecision.Reason.MCP_CONCURRENCY_LIMIT, + ((AgentMcpQuotaException) error).getDecision().getReason())) + .verify(Duration.ofSeconds(5)); + await().atMost(Duration.ofSeconds(5)).until(() -> governor.withQuota(tenant, subject, "after-expiry", 1, Mono.just(true)) + .onErrorResume(AgentMcpQuotaException.class, error -> Mono.just(false)).block(Duration.ofSeconds(2))); + assertTrue(store.admit(policy, tenant, subject, "after-release", Instant.now()).block(Duration.ofSeconds(5)).allowed()); + } + @Test void shadowStateDoesNotDebitEnforceState() { Assumptions.assumeTrue(isRedisAvailable(), "Start Redis to run distributed quota tests"); From 973e74901137d6c16efa11ae91b68e6d55fe05ea Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Fri, 20 Nov 2026 14:23:58 +0800 Subject: [PATCH 35/36] fix(audit): separate governance decisions from invocation terminals --- docs/agent-governance-decision.md | 2 +- docs/agent-invocation-audit.md | 4 +++- .../audit/AgentGovernanceAuditAdapter.java | 11 +++++----- .../audit/AgentInvocationAuditEvent.java | 16 ++++++++++++-- .../AgentGovernanceAuditAdapterTest.java | 21 ++++++++++++++++--- .../AgentInvocationAuditCollectorTest.java | 16 ++++++++++++++ 6 files changed, 58 insertions(+), 12 deletions(-) diff --git a/docs/agent-governance-decision.md b/docs/agent-governance-decision.md index 8d3d932ead91..5d3445542847 100644 --- a/docs/agent-governance-decision.md +++ b/docs/agent-governance-decision.md @@ -35,7 +35,7 @@ Shadow reservations have a bounded TTL. Expiry only releases that reservation's 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. +`AgentGovernanceContractLabels` is the metric boundary and exposes only consumer, mode, result and reason. `AgentGovernanceAuditAdapter` emits schema-version-3 `GOVERNANCE` records, not logical or attempt terminal results. Their outcome is the policy result (`ALLOW`, `WOULD_DENY`, or `DENY`), and their timestamp is the decision's effective time. Shadow would-deny retains an `ALLOWED` traffic decision with a `SHADOW_*` reason; enforce deny uses `REJECTED`. Policy allowance never asserts that tool execution succeeded. Version-1 `LOGICAL`/`ATTEMPT` records remain unchanged; version 2 is reserved for the separate usage-enrichment contract. The existing terminal owner emits the sole logical outcome. Consumers must route by schema version and record type and exclude governance observations from call counts and failure ratios. ## Non-goals diff --git a/docs/agent-invocation-audit.md b/docs/agent-invocation-audit.md index daad45dc1090..266425581d3a 100644 --- a/docs/agent-invocation-audit.md +++ b/docs/agent-invocation-audit.md @@ -21,7 +21,9 @@ Agent Gateway and AI Proxy can emit metadata-only invocation audit events when ` ## 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. +Logical and attempt events have 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. + +Schema version `3` adds non-terminal `GOVERNANCE` observations; version 2 is reserved for the separate usage-enrichment contract. Their outcome is a policy result (`ALLOW`, `WOULD_DENY`, `DENY`), not execution success or failure. They share the request id for correlation but must not be counted as logical calls, attempts, or billable usage. Existing version-1 terminal records and their single owner remain unchanged. Consumers that do not support version 3 must skip these records rather than treating every non-attempt as a terminal result. 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. diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java index e012a0277bdf..e8a08c00d5bb 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.java @@ -24,7 +24,7 @@ /** * Adapts a governance decision into the existing metadata-only audit contract. - * Shadow would-deny remains an allowed invocation in the audit terminal outcome. + * Policy results are non-terminal observations, never execution outcomes. */ public final class AgentGovernanceAuditAdapter { @@ -35,7 +35,7 @@ public static AgentInvocationAuditEvent toEvent(final AgentRequestContext contex Objects.requireNonNull(context, "context"); Objects.requireNonNull(decision, "decision"); boolean denied = decision.deniesTraffic(); - return AgentInvocationAuditEvent.logical() + return AgentInvocationAuditEvent.governance() .requestId(context.getRequestId()) .tenant(context.getTenant()).subject(context.getSubject()).apiKeyId(context.getApiKeyId()) .selectorId(context.getSelectorId()).ruleId(context.getRuleId()) @@ -43,9 +43,10 @@ public static AgentInvocationAuditEvent toEvent(final AgentRequestContext contex .policyVersion(decision.getPolicyVersion()) .decision(denied ? AgentInvocationAuditEvent.Decision.REJECTED : AgentInvocationAuditEvent.Decision.ALLOWED) .target(context.getTarget()) - .outcome(denied ? "REJECTED" : "SUCCESS") - .reason(denied || decision.getMode() != AgentGovernanceDecision.Mode.SHADOW - ? decision.getReason().name() : "SHADOW_" + decision.getReason().name()) + .outcome(decision.getResult().name()) + .reason(decision.getMode() == AgentGovernanceDecision.Mode.SHADOW + ? "SHADOW_" + decision.getReason().name() : decision.getReason().name()) + .timestamp(decision.getEffectiveTime()) .build(); } } diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditEvent.java b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditEvent.java index 12578a330884..fa28a97755b1 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditEvent.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentInvocationAuditEvent.java @@ -31,6 +31,9 @@ public final class AgentInvocationAuditEvent { */ public static final int SCHEMA_VERSION = 1; + /** Governance record version; version 2 is reserved for usage-enriched terminal records. */ + public static final int GOVERNANCE_SCHEMA_VERSION = 3; + private final RecordType recordType; private final String requestId; @@ -99,6 +102,14 @@ public static Builder attempt(final int attempt) { return new Builder(RecordType.ATTEMPT).attempt(attempt); } + /** + * Create a policy observation, not a logical or attempt terminal result. + * @return governance metadata builder + */ + public static Builder governance() { + return new Builder(RecordType.GOVERNANCE); + } + public RecordType getRecordType() { return recordType; } @@ -120,7 +131,7 @@ public Optional getApiKeyId() { } public int getSchemaVersion() { - return SCHEMA_VERSION; + return recordType == RecordType.GOVERNANCE ? GOVERNANCE_SCHEMA_VERSION : SCHEMA_VERSION; } public Optional getSelectorId() { @@ -188,7 +199,8 @@ static String nullableText(final String value, final String name) { public enum RecordType { LOGICAL, - ATTEMPT + ATTEMPT, + GOVERNANCE } public enum Decision { diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java index 1edd25d73cd7..cfd53386902d 100644 --- a/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.java @@ -36,7 +36,9 @@ void shadowWouldDenyRemainsAllowedInAudit() { AgentGovernanceDecision.Mode.SHADOW, AgentGovernanceDecision.Result.WOULD_DENY, AgentGovernanceDecision.Reason.MCP_INVOCATION_LIMIT)); assertEquals(AgentInvocationAuditEvent.Decision.ALLOWED, event.getDecision()); - assertEquals("SUCCESS", event.getOutcome()); + assertEquals("GOVERNANCE", event.getRecordType().name()); + assertEquals("WOULD_DENY", event.getOutcome()); + assertEquals(3, event.getSchemaVersion()); assertEquals("SHADOW_MCP_INVOCATION_LIMIT", event.getReason()); } @@ -48,7 +50,8 @@ void enforceDenyIsAuditedAsRejection() { AgentGovernanceDecision.Mode.ENFORCE, AgentGovernanceDecision.Result.DENY, AgentGovernanceDecision.Reason.COST_BUDGET_EXCEEDED)); assertEquals(AgentInvocationAuditEvent.Decision.REJECTED, event.getDecision()); - assertEquals("REJECTED", event.getOutcome()); + assertEquals("GOVERNANCE", event.getRecordType().name()); + assertEquals("DENY", event.getOutcome()); assertEquals("COST_BUDGET_EXCEEDED", event.getReason()); } @@ -59,10 +62,22 @@ void failOpenEnforcePolicyErrorRemainsAnAllowedAudit() { AgentGovernanceDecision.Mode.ENFORCE, AgentGovernanceDecision.Result.ALLOW, AgentGovernanceDecision.Reason.POLICY_ERROR)); assertEquals(AgentInvocationAuditEvent.Decision.ALLOWED, event.getDecision()); - assertEquals("SUCCESS", event.getOutcome()); + assertEquals("GOVERNANCE", event.getRecordType().name()); + assertEquals("ALLOW", event.getOutcome()); assertEquals("POLICY_ERROR", event.getReason()); } + @Test + void enforceAllowDoesNotInventShadowOrExecutionSuccess() { + AgentInvocationAuditEvent event = AgentGovernanceAuditAdapter.toEvent( + new AgentRequestContext("request-1", "mcp", "selector", "rule"), decision( + AgentGovernanceDecision.Mode.ENFORCE, AgentGovernanceDecision.Result.ALLOW, + AgentGovernanceDecision.Reason.ALLOWED)); + assertEquals("GOVERNANCE", event.getRecordType().name()); + assertEquals("ALLOW", event.getOutcome()); + assertEquals("ALLOWED", event.getReason()); + } + private AgentGovernanceDecision decision(final AgentGovernanceDecision.Mode mode, final AgentGovernanceDecision.Result result, final AgentGovernanceDecision.Reason reason) { diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/test/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollectorTest.java b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/test/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollectorTest.java index 4f4d2c1e185c..43eebcc675c7 100644 --- a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/test/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollectorTest.java +++ b/shenyu-spring-boot-starter/shenyu-spring-boot-starter-agent-audit/src/test/java/org/apache/shenyu/springboot/starter/agent/audit/AgentInvocationAuditCollectorTest.java @@ -81,6 +81,22 @@ void deliversOffRequestThreadThroughExistingCollector() throws Exception { assertTrue(LoggingQueueMetrics.registered().stream().noneMatch(metric -> metric.getCollector().equals(AgentInvocationAuditCollector.class.getName()))); } + @Test + void governanceAndTerminalRecordsRemainDistinctInTheSameCollector() throws Exception { + List delivered = new CopyOnWriteArrayList<>(); + try (AgentInvocationAuditCollector collector = new AgentInvocationAuditCollector(8, delivered::addAll)) { + collector.start(); + collector.record(AgentInvocationAuditEvent.governance().requestId("one").outcome("WOULD_DENY").build()); + collector.record(AgentInvocationAuditEvent.logical().requestId("one").outcome("SERVER_ERROR").build()); + await().atMost(Duration.ofSeconds(5)).until(() -> delivered.size() == 2); + assertEquals(1, delivered.stream().filter(event -> event.getRecordType() == AgentInvocationAuditEvent.RecordType.LOGICAL).count()); + assertEquals(3, delivered.get(0).getSchemaVersion()); + assertEquals("WOULD_DENY", delivered.get(0).getOutcome()); + assertEquals(1, delivered.get(1).getSchemaVersion()); + assertEquals("SERVER_ERROR", delivered.get(1).getOutcome()); + } + } + @Test void slowSinkDoesNotBlockAdmissionAndOverflowUsesExistingMetrics() throws Exception { CountDownLatch entered = new CountDownLatch(1); From 5ed95a2823911966b7c171c94b4bc29a043bd834 Mon Sep 17 00:00:00 2001 From: BobSong-dev Date: Fri, 20 Nov 2026 14:30:24 +0800 Subject: [PATCH 36/36] test(agent-gateway): enforce one terminal audit with MCP quotas --- docs/agent-gateway-mcp-quotas.md | 4 ++ .../protocol/AgentMcpDispatcherTest.java | 68 +++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/docs/agent-gateway-mcp-quotas.md b/docs/agent-gateway-mcp-quotas.md index 2c953f226d65..62057ece5225 100644 --- a/docs/agent-gateway-mcp-quotas.md +++ b/docs/agent-gateway-mcp-quotas.md @@ -112,6 +112,10 @@ shenyu_agent_governance_decisions_total{consumer,mode,result,reason} Tenant, subject, tool name, endpoint, request id, and trace id are not metric labels. Non-allow decisions can also be emitted as metadata-only audit events through the application-provided audit observer. +These are schema-version-3 `GOVERNANCE` observations, not invocation terminals. +Their outcomes are `ALLOW`, `WOULD_DENY`, or `DENY`; the HTTP handler still emits +one logical terminal result, plus an attempt only when the tool actually executes. +Audit consumers must exclude governance records from call counts and failure ratios. Would-deny decisions are also counted in the governor's bounded, generation-owned `AgentGovernanceShadowLedger`, available through `shadowSnapshot()`, separately from enforce Redis state. diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java index 8ac754fa61ee..7faf54dcb548 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java @@ -20,7 +20,12 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.JsonObject; +import org.apache.shenyu.common.audit.AgentInvocationAuditBridge; +import org.apache.shenyu.common.audit.AgentInvocationAuditEvent; import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; +import org.apache.shenyu.common.dto.AgentGatewayMcpConfig; +import org.apache.shenyu.plugin.agent.gateway.AgentTrafficContext; +import org.apache.shenyu.plugin.agent.gateway.security.AgentMcpIdentity; import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaConfig; import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaGovernor; import org.apache.shenyu.plugin.agent.gateway.governance.AgentMcpQuotaStore; @@ -35,7 +40,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.awaitility.Awaitility; import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; @@ -482,6 +491,65 @@ void quotaDenialPreventsLocalExecutionAndMapsToQuotaProtocolFailure() { assertEquals(0, calls.get()); } + @ParameterizedTest + @ValueSource(strings = {"success", "error", "cancel", "deny", "fail-open", "backend-deny"}) + void quotaDecisionIsNotALogicalTerminalInTheHttpAuditSink(final String scenario) { + List records = new CopyOnWriteArrayList<>(); + AtomicInteger calls = new AtomicInteger(); + boolean rejected = "deny".equals(scenario) || "backend-deny".equals(scenario); + boolean backendFailure = "fail-open".equals(scenario) || "backend-deny".equals(scenario); + AgentMcpQuotaGovernor governor = new AgentMcpQuotaGovernor( + AgentMcpQuotaConfig.of(rejected || backendFailure ? AgentMcpQuotaConfig.Mode.ENFORCE : AgentMcpQuotaConfig.Mode.SHADOW, + 2, Duration.ofSeconds(60), 2, Duration.ofSeconds(60), "fail-open".equals(scenario)), + backendFailure ? failingStore() : recordingStore(new AgentMcpQuotaStore.Admission(false, true, false, ""), new CopyOnWriteArrayList<>()), + AgentRuntimeMetrics.NOOP, "test", records::add); + AgentToolProvider tool = provider("order_status", input -> { + calls.incrementAndGet(); + if ("cancel".equals(scenario)) { + return Mono.never(); + } + return "success".equals(scenario) ? Mono.just(new JsonObject()) : Mono.error(new IllegalStateException("fixture failure")); + }); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher(new AgentToolRegistry(List.of(tool)), "fixture", "1", + null, new AgentResourceRegistry(List.of()), AgentMcpResourceAdmission.NOOP, governor); + AgentMcpHttpHandler handler = new AgentMcpHttpHandler(dispatcher, + ignored -> Mono.just(new AgentMcpIdentity("tenant", "subject", Set.of("order_status"), Set.of())), null, + AgentInvocationAuditBridge.mcp(null, records::add)); + AgentGatewayMcpConfig config = AgentGatewayMcpConfig.parse(JsonParser.parseString( + "{\"allowedTools\":[\"order_status\"],\"responseMode\":\"json\",\"timeoutMs\":5000}").getAsJsonObject(), true); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/mcp") + .contentType(MediaType.APPLICATION_JSON).header("Accept", "application/json, text/event-stream") + .header("MCP-Protocol-Version", "2026-07-28").header("Mcp-Method", "tools/call").header("Mcp-Name", "order_status") + .body("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"order_status\",\"_meta\":{" + + "\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}}}")); + Mono handling = handler.handle(exchange, config, new AgentTrafficContext("request", "mcp", "selector", "rule"), 1); + if ("cancel".equals(scenario)) { + reactor.core.Disposable subscription = handling.subscribe(); + Awaitility.await().atMost(Duration.ofSeconds(5)).until(() -> calls.get() == 1); + subscription.dispose(); + } else { + handling.block(Duration.ofSeconds(5)); + } + Awaitility.await().atMost(Duration.ofSeconds(5)).until(() -> records.size() == (rejected ? 2 : 3)); + List terminal = records.stream() + .filter(event -> event.getRecordType() == AgentInvocationAuditEvent.RecordType.LOGICAL).toList(); + assertEquals(1, terminal.size(), records.toString()); + assertEquals("GOVERNANCE", records.get(0).getRecordType().name()); + assertEquals(3, records.get(0).getSchemaVersion()); + assertEquals(rejected ? "DENY" : backendFailure ? "ALLOW" : "WOULD_DENY", records.get(0).getOutcome()); + assertTrue(records.get(0).getHttpStatus().isEmpty()); + assertTrue(records.stream().allMatch(event -> "request".equals(event.getRequestId()))); + assertEquals(rejected ? 0 : 1, calls.get()); + assertEquals(rejected ? 0 : 1, records.stream().filter(event -> event.getRecordType() == AgentInvocationAuditEvent.RecordType.ATTEMPT).count()); + assertEquals(1, terminal.get(0).getSchemaVersion()); + assertEquals("success".equals(scenario) ? "SUCCESS" : "cancel".equals(scenario) ? "CANCELLED" + : "deny".equals(scenario) ? "REJECTED" : "SERVER_ERROR", terminal.get(0).getOutcome()); + if (!"cancel".equals(scenario)) { + assertEquals("success".equals(scenario) ? 200 : "deny".equals(scenario) ? 429 + : "backend-deny".equals(scenario) ? 503 : 500, terminal.get(0).getHttpStatus().orElseThrow()); + } + } + @Test void quotaAdmissionWrapsColdLocalExecutionAndReleasesOnEveryTerminalSignal() { AtomicInteger calls = new AtomicInteger();