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 new file mode 100644 index 000000000000..62057ece5225 --- /dev/null +++ b/docs/agent-gateway-mcp-quotas.md @@ -0,0 +1,137 @@ + + +# 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, 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. + +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 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. 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. + +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:encodedTenant}`; +- `shenyu:agent:mcp-quota:invocation:{mode:encodedTenant}:encodedSubject`; +- `shenyu:agent:mcp-quota:concurrency:{mode:encodedTenant}:encodedSubject`. + +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 +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 +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 + +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. +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. + +## 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 + +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/docs/agent-gateway-resource-admission.md b/docs/agent-gateway-resource-admission.md new file mode 100644 index 000000000000..0bb9a9a50517 --- /dev/null +++ b/docs/agent-gateway-resource-admission.md @@ -0,0 +1,60 @@ + + +# 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. +- 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. + +## 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/docs/agent-governance-decision.md b/docs/agent-governance-decision.md new file mode 100644 index 000000000000..5d3445542847 --- /dev/null +++ b/docs/agent-governance-decision.md @@ -0,0 +1,46 @@ + + +# 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` 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 + +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..266425581d3a 100644 --- a/docs/agent-invocation-audit.md +++ b/docs/agent-invocation-audit.md @@ -1,10 +1,29 @@ + + # 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. +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 new file mode 100644 index 000000000000..e8a08c00d5bb --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapter.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.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. + * Policy results are non-terminal observations, never execution outcomes. + */ +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.governance() + .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(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/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..3fdd26e2dc32 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,18 @@ 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); + } + boolean hasAggregation = root.has("aggregation"); + Set pluginFields = new HashSet<>(hasAggregation ? Set.of("aggregation") : Set.of()); + if (root.has("admission")) { + pluginFields.add("admission"); + } + fields(root, pluginFields); + if (!hasAggregation) { + return new AgentGatewayAggregationConfig("empty", List.of(), + AgentGatewayAdmissionConfig.parse(root.get("admission"))); } - fields(root, Set.of("aggregation")); JsonNode aggregation = root.get("aggregation"); fields(aggregation, Set.of("revision", "servers")); if (!aggregation.path("servers").isArray()) { @@ -78,7 +89,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/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..7f24cd6290b4 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/governance/AgentGovernanceDecision.java @@ -0,0 +1,232 @@ +/* + * 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 && 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"); + } + 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) { + return AgentGovernanceText.require(value, name, 128); + } + + 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..a78f2400bac8 --- /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 = 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) { + 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/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-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/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 new file mode 100644 index 000000000000..cfd53386902d --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/audit/AgentGovernanceAuditAdapterTest.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.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("GOVERNANCE", event.getRecordType().name()); + assertEquals("WOULD_DENY", event.getOutcome()); + assertEquals(3, event.getSchemaVersion()); + 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("GOVERNANCE", event.getRecordType().name()); + assertEquals("DENY", event.getOutcome()); + 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("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) { + 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/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()); } 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..10472f4f641f 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,35 @@ 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 parsesAdmissionWithoutRemoteAggregation() { + String source = "{\"admission\":{\"globalInFlight\":8,\"globalQueued\":4,\"localInFlight\":1," + + "\"localQueued\":0,\"remoteInFlight\":2,\"remoteQueued\":2}}"; + AgentGatewayAggregationConfig config = AgentGatewayAggregationConfig.parsePluginConfig(source); + assertTrue(config.servers().isEmpty()); + assertEquals(1, config.admission().localInFlight()); + } + + @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-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(); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml b/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml index ab93136a3bf9..4d6445e25497 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml @@ -34,6 +34,12 @@ META-INF/shenyu/agent-gateway-version.properties + + src/main/resources + + META-INF/shenyu/agent-gateway-version.properties + + @@ -73,6 +79,10 @@ org.springframework.boot spring-boot-starter-webflux + + org.springframework.data + spring-data-redis + org.springframework.boot spring-boot-starter-test @@ -83,5 +93,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/AgentGatewayPlugin.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java index dc65e11edd4c..3fd967de2cc5 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 @@ -17,6 +17,8 @@ package org.apache.shenyu.plugin.agent.gateway; +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.AgentRequestContext; @@ -43,10 +45,12 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ResponseStatusException; import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; import java.util.Objects; import java.util.List; import java.util.UUID; +import java.util.concurrent.TimeUnit; /** * Establishes an isolated request context, dispatching matched MCP rules locally @@ -172,14 +176,14 @@ private Mono reject(final ServerWebExchange exchange, final String reason, 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) { + Object callback = exchange.getAttribute(AgentInvocationAuditObserver.EXCHANGE_ATTRIBUTE); + if (callback instanceof AgentInvocationAuditObserver audit) { try { - audit.record(org.apache.shenyu.common.audit.AgentInvocationAuditEvent.logical().requestId(requestId) + audit.record(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()); + .decision(AgentInvocationAuditEvent.Decision.REJECTED) + .outcome(signal == SignalType.CANCEL ? "CANCELLED" : "SERVER_ERROR").reason("INVALID_CONFIGURATION") + .httpStatus(500).elapsedMillis(TimeUnit.NANOSECONDS.toMillis(Math.max(0, System.nanoTime() - started))).build()); } catch (RuntimeException ignored) { // Do not expose the rejected configuration or alter its response. } 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..abe97a57e18d --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaConfig.java @@ -0,0 +1,94 @@ +/* + * 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; + +/** 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; + } + + 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..5a57b231f9f1 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernor.java @@ -0,0 +1,258 @@ +/* + * 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.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; +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; + + private final AgentGovernanceShadowLedger shadowLedger; + + 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 = UUID.randomUUID().toString(); + this.shadowLedger = new AgentGovernanceShadowLedger(ledgerGeneration, config.getConcurrencyLimit()); + } + + /** 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) { + 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 normalizedCorrelation = bounded(correlationId, "correlationId"); + 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; + 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)) + .flatMap(admission -> { + boolean policyUnavailable = admission.getValue(); + AgentGovernanceDecision decision = decision(admission.getKey(), policyUnavailable, + normalizedCorrelation, configuration, effectiveTime); + report(decision, selectedMetrics, requestContext); + if (decision.getResult() == AgentGovernanceDecision.Result.WOULD_DENY) { + shadowLedger.observe(decision); + } + if (decision.deniesTraffic()) { + return Mono.error(new AgentMcpQuotaException(decision)); + } + if (policyUnavailable) { + return execution; + } + return Mono.usingWhen(Mono.just(admission.getKey()), + 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, + 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; + 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 + ? 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 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) { + return AgentGovernanceText.require(value, name, 128); + } + + 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..e5726bc94923 --- /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 org.apache.shenyu.common.governance.AgentGovernanceText; + +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) { + 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 new file mode 100644 index 000000000000..41cfe9f328f4 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/governance/RedisAgentMcpQuotaStore.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.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"); + String lease = UUID.randomUUID().toString(); + 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, 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), + 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 = 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)); + } + + 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 449a8d7ebe6e..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 @@ -25,17 +25,21 @@ 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; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolCapabilityException; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolDefinition; 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.AgentToolRegistry; -import org.apache.shenyu.plugin.agent.gateway.resource.AgentResourceRegistry; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolProvider; -import org.apache.shenyu.plugin.agent.gateway.tool.AgentHttpToolProvider; import reactor.core.publisher.Mono; +import java.util.List; import java.util.Map; import java.net.http.HttpTimeoutException; import java.util.concurrent.TimeoutException; @@ -51,6 +55,10 @@ public final class AgentMcpDispatcher { private final AgentMcpRemoteCatalog remoteCatalog; + private final AgentMcpResourceAdmission admission; + + private final AgentMcpQuotaGovernor quotaGovernor; + private final AgentMcpResourceDispatcher resources; private final AgentResourceRegistry resourceRegistry; @@ -66,15 +74,69 @@ 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, new AgentResourceRegistry(java.util.List.of())); + this(registry, serverName, serverVersion, remoteCatalog, AgentMcpResourceAdmission.NOOP); + } + + /** + * Managed dispatcher with bounded remote resource admission. + * @param registry trusted local tool registry + * @param serverName server name + * @param serverVersion server version + * @param remoteCatalog optional remote catalog + * @param admission remote admission policy + */ + public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion, + final AgentMcpRemoteCatalog remoteCatalog, final AgentMcpResourceAdmission admission) { + this(registry, serverName, serverVersion, remoteCatalog, new AgentResourceRegistry(List.of()), admission); } + /** + * Managed dispatcher with local resources. + * @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 + */ public AgentMcpDispatcher(final AgentToolRegistry registry, final String serverName, final String serverVersion, final AgentMcpRemoteCatalog remoteCatalog, final AgentResourceRegistry resourceRegistry) { + this(registry, serverName, serverVersion, remoteCatalog, resourceRegistry, AgentMcpResourceAdmission.NOOP); + } + + /** + * Managed dispatcher with local resources and bounded remote resource admission. + * @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 + */ + 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"); - resources = new AgentMcpResourceDispatcher(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"); } @@ -106,7 +168,8 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier bound); + return new AgentMcpDispatcher(captured, serverName, serverVersion, remoteCatalog, + resourceRegistry, Objects.isNull(remoteCatalog) ? admission : remoteCatalog.admission(), quotaGovernor).dispatch(request, () -> bound); } if (Objects.nonNull(remoteCatalog)) { return remoteCatalog.withSnapshot(snapshot -> routeWithRemote(request, context, snapshot)) @@ -141,6 +204,25 @@ 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(() -> { - context.notifyAttempt(); - return 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(); @@ -265,7 +345,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(), 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(); @@ -296,6 +377,19 @@ 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 Mono withQuota(final AgentMcpExecutionContext context, final Mono execution) { + if (Objects.isNull(quotaGovernor)) { + return 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, 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/AgentMcpExecutionContext.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java index b7f17bf64308..627075dc3c8a 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 @@ -78,7 +78,7 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi final Set ruleTools, final Set securityGrants, final Instant deadline, final AgentGatewayResultFilterConfig resultFilters) { this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters, - Set.of(), Set.of(), AgentGatewayHttpToolConfig.empty(), null, null); + Set.of(), Set.of(), AgentGatewayHttpToolConfig.empty(), null, null, null); } public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion, @@ -86,14 +86,14 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi final AgentGatewayResultFilterConfig resultFilters, final Set ruleResources, final Set resourceGrants) { this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters, - ruleResources, resourceGrants, AgentGatewayHttpToolConfig.empty(), null, null); + ruleResources, resourceGrants, AgentGatewayHttpToolConfig.empty(), null, null, 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(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters, - Set.of(), Set.of(), AgentGatewayHttpToolConfig.empty(), null, tenant); + Set.of(), Set.of(), AgentGatewayHttpToolConfig.empty(), null, tenant, null); } public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion, @@ -101,7 +101,7 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi final AgentGatewayResultFilterConfig resultFilters, final Set ruleResources, final Set resourceGrants, final String tenant) { this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters, - ruleResources, resourceGrants, AgentGatewayHttpToolConfig.empty(), null, tenant); + ruleResources, resourceGrants, AgentGatewayHttpToolConfig.empty(), null, tenant, null); } public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion, @@ -109,7 +109,7 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi final AgentGatewayResultFilterConfig resultFilters, final AgentGatewayHttpToolConfig httpTools, final AgentHttpToolInvoker httpInvoker) { this(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters, - Set.of(), Set.of(), httpTools, httpInvoker, null); + Set.of(), Set.of(), httpTools, httpInvoker, null, null); } public AgentMcpExecutionContext(final String requestId, final String subject, final String ruleId, final long configurationVersion, @@ -120,6 +120,29 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi Set.of(), Set.of(), httpTools, httpInvoker, tenant, null); } + /** + * Request-local context with HTTP tools and one terminal attempt callback. + * @param requestId trusted request identity + * @param subject trusted authenticated subject + * @param ruleId matched rule identity + * @param configurationVersion rule snapshot generation + * @param ruleTools configured tool allow-list + * @param securityGrants identity tool grants + * @param deadline request deadline + * @param resultFilters configured result filters + * @param httpTools request-owned HTTP tool definitions + * @param httpInvoker internal gateway HTTP executor + * @param tenant trusted tenant identity + * @param attemptListener internal attempt callback + */ + 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(requestId, subject, ruleId, configurationVersion, ruleTools, securityGrants, deadline, resultFilters, + Set.of(), Set.of(), httpTools, httpInvoker, tenant, attemptListener); + } + 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 Set ruleResources, @@ -129,6 +152,23 @@ public AgentMcpExecutionContext(final String requestId, final String subject, fi ruleResources, resourceGrants, httpTools, httpInvoker, tenant, null); } + /** + * Fully populated request-local context. + * @param requestId trusted request identity + * @param subject trusted authenticated subject + * @param ruleId matched rule identity + * @param configurationVersion rule snapshot generation + * @param ruleTools configured tool allow-list + * @param securityGrants identity tool grants + * @param deadline request deadline + * @param resultFilters configured result filters + * @param ruleResources configured resource allow-list + * @param resourceGrants identity resource grants + * @param httpTools request-owned HTTP tool definitions + * @param httpInvoker internal gateway HTTP executor + * @param tenant trusted tenant identity + * @param attemptListener internal attempt callback + */ 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 Set ruleResources, 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 11a5503e540c..a612504e3a0c 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 @@ -138,19 +138,21 @@ public Mono handle(final ServerWebExchange exchange, final AgentGatewayMcp } observation.parsed(request); return dispatcher.dispatch(request, () -> new AgentMcpExecutionContext(traffic.getRequestId(), - identity.getSubject(), traffic.getRuleId(), configurationVersion, config.getAllowedTools(), - identity.getToolGrants(), deadline, config.getResultFilters(), config.getAllowedResources(), - identity.getResourceGrants(), config.getHttpTools(), httpInvoker, - identity.getTenant().orElse(null), () -> { - if (Objects.nonNull(terminal)) { - terminal.attempted(); - } - })) + identity.getSubject(), traffic.getRuleId(), configurationVersion, config.getAllowedTools(), + identity.getToolGrants(), deadline, config.getResultFilters(), config.getAllowedResources(), + identity.getResourceGrants(), config.getHttpTools(), httpInvoker, + 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, - traffic.toRequestContext(configurationVersion).withIdentity(identity.getTenant().orElse(null), identity.getSubject()) - .withTarget("tools/call".equals(request.getMethod()) ? request.getParams().path("name").textValue() : null, + 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 -> { 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 c1ecb20f5676..701a09acc064 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,13 @@ 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..afba59351169 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.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.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.util.List; +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); + } + + /** + * 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) { + Objects.requireNonNull(replacement, "replacement"); + if (replacement.delegate.closed()) { + replacement.delegate.close(); + return; + } + try { + current.updateLimits(replacement.delegate); + } finally { + replacement.delegate.close(); + } + } + + @Override + public void close() { + AgentResourceAdmission active; + synchronized (this) { + active = current; + } + active.close(); + } + + /** + * Read the currently active limits without creating another controller. + * @return immutable trusted limits + */ + public AgentGatewayAdmissionConfig config() { + return current.config(); + } + + /** + * Read the live states of the active controller. + * @return immutable controller snapshots + */ + public List snapshot() { + return current.snapshot(); + } + } +} 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..4a73fb33ab17 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmission.java @@ -0,0 +1,416 @@ +/* + * 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 volatile AgentGatewayAdmissionConfig config; + + private final Scope global; + + private final Scope local; + + 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", promotionLock, config.globalInFlight(), config.globalQueued()); + local = new Scope("local", promotionLock, 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(Mono.defer(() -> Instant.now().isBefore(deadline) ? action : Mono.error(AgentAdmissionException.deadline()))) + .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"); + } + synchronized (remotes) { + for (Scope scope : remotes) { + if (scope.name.equals(name)) { + return scope; + } + } + Scope scope = new Scope(name, promotionLock, 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)); + remoteScopes().forEach(scope -> result.add(scope.snapshot(AgentAdmissionMetrics.Scope.REMOTE))); + return result; + } + + private List remoteScopes() { + synchronized (remotes) { + return List.copyOf(remotes); + } + } + + /** + * Current trusted limits. + * @return immutable admission configuration + */ + 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 (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())); + } + // Completion can synchronously release a promoted request: retain the + // same promotionLock -> scope lock order used by release and close. + global.promote(); + local.promote(); + remoteScopes().forEach(Scope::promote); + } + } + + /** + * Whether this controller has already been closed. + * @return terminal close state + */ + public boolean closed() { + return closed; + } + + /** Stop new work and cancel queued waiters; terminal executions still release once. */ + public void close() { + synchronized (promotionLock) { + closed = true; + registration.close(); + global.close(); + local.close(); + remoteScopes().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 int inFlightLimit; + + private int queueLimit; + + private final AtomicLong rejected = new AtomicLong(); + + private final Object lock = new Object(); + + private final Object promotionLock; + + private final Deque waiting = new ArrayDeque<>(); + + private int inFlight; + + private int queued; + + private boolean closed; + + 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; + } + + AcquireResult acquire(final Instant deadline) { + synchronized (lock) { + if (closed) { + rejected.incrementAndGet(); + return AcquireResult.reject(AgentAdmissionException.closed()); + } + if (!Instant.now().isBefore(deadline)) { + rejected.incrementAndGet(); + return AcquireResult.reject(AgentAdmissionException.deadline()); + } + if (inFlight < inFlightLimit) { + inFlight++; + return AcquireResult.admitted(new Wait(this, null)); + } + if (queued >= queueLimit) { + rejected.incrementAndGet(); + return AcquireResult.reject(AgentAdmissionException.overloaded()); + } + Waiter waiter = new Waiter(deadline); + waiting.addLast(waiter); + queued++; + return AcquireResult.admitted(new Wait(this, waiter)); + } + } + + void release(final Wait 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); + } + } + } + } + + private void completeActive(final Wait wait) { + synchronized (lock) { + inFlight--; + promote(); + } + } + + private void promote() { + 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(); + } + } + } + + + 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()); + } + } + + void installLimits(final int inFlightLimit, final int queueLimit) { + synchronized (lock) { + this.inFlightLimit = inFlightLimit; + this.queueLimit = queueLimit; + } + } + } + + 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 af8006823efe..1870f04597e7 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,6 +23,7 @@ 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.config.contract.ConfigurationContractRegistry; import org.apache.shenyu.common.config.contract.ConfigurationScope; import org.apache.shenyu.common.config.contract.ConfigurationValidation; @@ -32,6 +33,7 @@ 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; @@ -69,6 +71,8 @@ public final class ManagedRemoteMcpCatalog implements AgentMcpRemoteCatalog, Aut private final RemoteServiceCredentialResolver credentials; + private final AgentMcpResourceAdmission.ResourceAdmissionController admission; + private final Scheduler scheduler = Schedulers.newBoundedElastic(1, 16, "agent-mcp-config"); private final Sinks.Many updates = Sinks.many().unicast().onBackpressureBuffer(new ArrayBlockingQueue<>(16)); @@ -90,15 +94,39 @@ 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, false); + this(allowedEndpoints, localNames, credentials, AgentMcpResourceAdmission.create(AgentGatewayAdmissionConfig.parse(null)), false); + } + + /** + * 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 AgentMcpResourceAdmission.ResourceAdmissionController admission) { + this(allowedEndpoints, localNames, credentials, admission, false); } - public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames, final RemoteServiceCredentialResolver credentials, - final boolean resourcesEnabled) { + /** + * Managed remote catalog with a shared resource admission controller. + * @param allowedEndpoints trusted allowedEndpoints value + * @param localNames trusted localNames value + * @param credentials trusted credentials value + * @param admission shared trusted admission controller + * @param resourcesEnabled whether remote resources are enabled + */ + public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames, + final RemoteServiceCredentialResolver credentials, + final AgentMcpResourceAdmission.ResourceAdmissionController admission, + final boolean resourcesEnabled) { lifecycle = new RemoteCatalogLifecycle(3, resourcesEnabled); this.allowedEndpoints = Set.copyOf(allowedEndpoints); this.localNames = Set.copyOf(localNames); this.credentials = Objects.requireNonNull(credentials, "credentials"); + this.admission = Objects.requireNonNull(admission, "admission"); 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)); @@ -176,7 +204,12 @@ 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())); + } + }); }); } @@ -197,6 +230,19 @@ public Mono withSnapshot(final Function> }); } + @Override + public AgentMcpResourceAdmission admission() { + return admission; + } + + /** + * Current validated admission limits. + * @return immutable trusted configuration + */ + public AgentGatewayAdmissionConfig admissionConfig() { + return admission.config(); + } + /** * Secret-free lifecycle diagnostics for management and verification. * @return immutable diagnostic values @@ -205,6 +251,10 @@ public Map diagnostics() { Diagnostics state = diagnosticsState(); Map result = new LinkedHashMap<>(state.lifecycle().toMap()); result.put("lastFailure", state.lastFailure()); + AgentGatewayAdmissionConfig config = admission.config(); + result.put("admission", Map.of("globalInFlight", config.globalInFlight(), "globalQueued", config.globalQueued(), + "localInFlight", config.localInFlight(), "localQueued", config.localQueued(), + "remoteInFlight", config.remoteInFlight(), "remoteQueued", config.remoteQueued())); return Map.copyOf(result); } @@ -230,6 +280,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..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 @@ -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 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, + 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)) { @@ -167,8 +184,10 @@ public Mono invoke(final String name, final Set allowedTools } catch (IllegalArgumentException error) { throw new AgentToolArgumentException(error); } - onAttempt.run(); - return 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/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..2d6efedcadd6 --- /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..89207b00bb78 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/resources/mcp-quota.lua @@ -0,0 +1,56 @@ +-- +-- 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. +-- 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 milliseconds +-- ARGV[3] subject concurrency limit +-- ARGV[4] lease token +-- ARGV[5] lease TTL milliseconds +-- Returns {allowed, invocationLimited, concurrencyLimited, lease} +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', now) +local concurrency = redis.call('ZCARD', KEYS[2]) +if concurrency >= tonumber(ARGV[3]) then + return {0, 0, 1, ''} +end +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 new file mode 100644 index 000000000000..96d2a60ea676 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaGovernorTest.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.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()); + assertEquals(1, governor.shadowSnapshot().observedDenials()); + } + + @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 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); + 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..b1fa26d29aee --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/governance/AgentMcpQuotaRedisStoreTest.java @@ -0,0 +1,330 @@ +/* + * 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.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; +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; +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; +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 final List factories = new ArrayList<>(); + + private static boolean isRedisAvailable() { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(HOST, PORT), 500); + return true; + } catch (IOException error) { + return false; + } + } + + @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) + .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().plusSeconds(index % 2 == 0 ? 3600 : -3600))) + .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()); + assertFalse(store.admit(policy, tenant, subject, "skewed", now.plusSeconds(3600)).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()); + await().atMost(Duration.ofSeconds(5)).until(() -> store.admit(policy, tenant, subject, + 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"); + 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(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()); + 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 + 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); + String prefix = tenant(); + assertTrue(store.admit(policy, prefix, "subject:tool", UUID.randomUUID().toString(), Instant.now()) + .block(Duration.ofSeconds(5)).allowed()); + assertTrue(store.admit(policy, prefix + ":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 96835df22a18..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 @@ -17,18 +17,34 @@ 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.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; 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; +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; @@ -37,10 +53,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; @@ -429,8 +451,263 @@ 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(); + } + } + + @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()); + } + + @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(); + 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()); + } + + @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 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, + 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) { @@ -469,4 +746,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-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/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..e1c336b8cdc1 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentResourceAdmissionTest.java @@ -0,0 +1,559 @@ +/* + * 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 org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +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.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; + +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 replacingControllerKeepsSharedAccountingAndAppliesNewLimits() { + 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(), "replacement metrics must stay retired"); + } finally { + first.close(); + } + } + + @Test + void everyReplacementUpdatesActiveControllerAndFinalCloseRemovesMetrics() throws Exception { + AgentMcpResourceAdmission.ResourceAdmissionController controller = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(1, 1, 1, 1, 1, 1)); + try { + controller.replace(AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(2, 1, 1, 1, 1, 1))); + controller.replace(AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(3, 1, 1, 1, 1, 1))); + Sinks.Empty first = Sinks.empty(); + Sinks.Empty second = Sinks.empty(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + final Future one = executor.submit(() -> StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), first.asMono())).expectComplete().verify()); + final Future two = executor.submit(() -> StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), second.asMono())).expectComplete().verify()); + awaitActive(controller, AgentAdmissionMetrics.Scope.GLOBAL, 2); + first.tryEmitEmpty(); + second.tryEmitEmpty(); + one.get(5, TimeUnit.SECONDS); + two.get(5, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(2), Mono.just("third"))).expectNext("third").verifyComplete(); + } finally { + controller.close(); + } + assertTrue(AgentAdmissionMetrics.snapshots().stream() + .filter(snapshot -> snapshot.scope() == AgentAdmissionMetrics.Scope.GLOBAL) + .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 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 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 = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(2, 1, 1, 1, 1, 1)); + AgentMcpResourceAdmission.ResourceAdmissionController stale = + AgentMcpResourceAdmission.create(new AgentGatewayAdmissionConfig(3, 1, 1, 1, 1, 1)); + try { + stale.close(); + active.replace(stale); + assertEquals(2, active.snapshot().stream() + .filter(snapshot -> snapshot.scope() == AgentAdmissionMetrics.Scope.GLOBAL) + .findFirst().orElseThrow().inFlightLimit()); + } finally { + active.close(); + } + assertTrue(AgentAdmissionMetrics.snapshots().stream() + .filter(snapshot -> snapshot.scope() == AgentAdmissionMetrics.Scope.GLOBAL) + .noneMatch(snapshot -> snapshot.inFlightLimit() == 3), + "a closed redundant replacement must stay unregistered"); + } + + @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)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void expiredDeadlineNeverExecutesWithFreeOrFullCapacity(final boolean remote) { + controller = new AgentResourceAdmission(new AgentGatewayAdmissionConfig(1, 0, 1, 0, 1, 0)); + AtomicInteger calls = new AtomicInteger(); + Instant expired = Instant.now().minusSeconds(1); + Mono rejected = remote ? controller.withRemote("orders", expired, Mono.fromCallable(calls::incrementAndGet)) + : controller.withLocal(expired, Mono.fromCallable(calls::incrementAndGet)); + StepVerifier.create(rejected).expectErrorMatches(error -> error instanceof AgentResourceAdmission.AgentAdmissionException + && ((AgentResourceAdmission.AgentAdmissionException) error).isTimeout()).verify(Duration.ofSeconds(2)); + assertEquals(0, calls.get()); + assertTrue(controller.snapshot().stream().allMatch(state -> state.inFlight() == 0 && state.queued() == 0)); + + Sinks.Empty active = Sinks.empty(); + reactor.core.Disposable running = controller.withLocal(Instant.now().plusSeconds(30), active.asMono()).subscribe(); + try { + StepVerifier.create(rejected).expectErrorMatches(error -> error instanceof AgentResourceAdmission.AgentAdmissionException + && ((AgentResourceAdmission.AgentAdmissionException) error).isTimeout()).verify(Duration.ofSeconds(2)); + assertEquals(0, calls.get()); + } finally { + running.dispose(); + } + StepVerifier.create(controller.withLocal(Instant.now().plusSeconds(30), Mono.just("ok"))).expectNext("ok").verifyComplete(); + assertTrue(controller.snapshot().stream().allMatch(state -> state.inFlight() == 0 && state.queued() == 0)); + } + + @ParameterizedTest + @ValueSource(strings = {"global", "local", "remote"}) + void reloadPromotionAndActiveCompletionUseConsistentLockOrder(final String scope) throws Exception { + boolean global = "global".equals(scope); + boolean remote = "remote".equals(scope); + AgentMcpResourceAdmission.ResourceAdmissionController admission = AgentMcpResourceAdmission.create( + new AgentGatewayAdmissionConfig(global ? 1 : 4, 4, 1, 4, 1, 4)); + ExecutorService executor = Executors.newFixedThreadPool(2, task -> { + Thread thread = new Thread(task, "admission-reload-regression"); + thread.setDaemon(true); + return thread; + }); + Sinks.Empty active = Sinks.empty(); + CountDownLatch promoted = new CountDownLatch(1); + CountDownLatch continuePromotion = new CountDownLatch(1); + AtomicReference failure = new AtomicReference<>(); + AtomicReference completionThread = new AtomicReference<>(); + Instant deadline = Instant.now().plusSeconds(30); + boolean completed = false; + try { + (remote ? admission.withRemote("orders", deadline, active.asMono()) : admission.withLocal(deadline, active.asMono())) + .subscribe(ignored -> { }, failure::set); + Mono action = Mono.fromRunnable(() -> { + promoted.countDown(); + try { + assertTrue(continuePromotion.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(error); + } + }); + (remote ? admission.withRemote("orders", deadline, action) : admission.withLocal(deadline, action)) + .subscribe(ignored -> { }, failure::set); + AgentAdmissionMetrics.Scope queuedScope = global ? AgentAdmissionMetrics.Scope.GLOBAL + : remote ? AgentAdmissionMetrics.Scope.REMOTE : AgentAdmissionMetrics.Scope.LOCAL; + awaitQueued(admission, queuedScope, 1); + final Future reload = executor.submit(() -> admission.replace(AgentMcpResourceAdmission.create( + new AgentGatewayAdmissionConfig(4, 4, 4, 4, 4, 4)))); + assertTrue(promoted.await(5, TimeUnit.SECONDS)); + final Future completion = executor.submit(() -> { + completionThread.set(Thread.currentThread()); + active.tryEmitEmpty(); + }); + org.awaitility.Awaitility.await().atMost(Duration.ofSeconds(5)).until(() -> Objects.nonNull(completionThread.get()) + && completionThread.get().getState() == Thread.State.BLOCKED); + continuePromotion.countDown(); + reload.get(5, TimeUnit.SECONDS); + completion.get(5, TimeUnit.SECONDS); + assertNull(failure.get()); + assertTrue(admission.snapshot().stream().allMatch(state -> state.inFlight() == 0 && state.queued() == 0)); + completed = true; + } finally { + continuePromotion.countDown(); + executor.shutdownNow(); + if (completed) { + admission.close(); + } + } + } + + 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 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) { + return; + } + TimeUnit.MILLISECONDS.sleep(10); + } + assertTrue(false, "admission waiter was not queued"); + } + + 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 (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"); + } + + 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)); + } +} 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 5379ca0f7d4a..a6c3171e6abb 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 @@ -23,6 +23,7 @@ import org.apache.shenyu.common.dto.PluginData; import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpRemoteCatalog; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.junit.jupiter.api.Test; @@ -140,6 +141,29 @@ void newerFencedEventClearsOnlyTheSupersededFailureDiagnostic() throws Exception } } + @Test + void validConfigurationReplacesAdmissionLimitsAfterCredentialResolution() throws InterruptedException { + AgentMcpResourceAdmission.ResourceAdmissionController admission = AgentMcpResourceAdmission.create( + new org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig(128, 64, 32, 16, 8, 16)); + 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"), admission, false); + try { + assertEquals(128, catalog.admissionConfig().globalInFlight()); + catalog.accept(event(true, configWithAdmission(16, 8, 4))); + admission.replace(AgentMcpResourceAdmission.create( + new org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig(16, 32, 16, 8, 8, 4))); + await(() -> catalog.diagnosticsState().lifecycle().currentVersion() > 1L); + assertEquals(16, catalog.admissionConfig().globalInFlight()); + assertEquals(8, catalog.admissionConfig().remoteInFlight()); + assertEquals(4, catalog.admissionConfig().remoteQueued()); + assertEquals(16, admission.snapshot().stream() + .filter(state -> state.scope() == org.apache.shenyu.common.metrics.AgentAdmissionMetrics.Scope.GLOBAL) + .findFirst().orElseThrow().inFlightLimit()); + } finally { + catalog.close(); + } + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void withdrawnDuringSuccessfulCredentialResolutionDoesNotStartRemoteHandshake(final boolean emptyConfiguration) throws Exception { @@ -319,6 +343,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/RemoteResourceNetworkTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteResourceNetworkTest.java index b873e570d71f..70544a9aa882 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteResourceNetworkTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteResourceNetworkTest.java @@ -25,6 +25,7 @@ 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.AgentMcpRequestParser; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; import org.apache.shenyu.plugin.agent.gateway.resource.AgentResourceNamespace; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolRegistry; import org.junit.jupiter.api.Test; @@ -129,7 +130,9 @@ void cancellingAnActualHttpReadDoesNotCancelItsPeer() throws Exception { private ManagedRemoteMcpCatalog catalog(final Fixture first, final Fixture second, final boolean resources) { return new ManagedRemoteMcpCatalog(Set.of(first.endpoint(), second.endpoint()), Set.of(), - target -> new RemoteServerBinding.Credential(target, "resources-test-service"), resources); + target -> new RemoteServerBinding.Credential(target, "resources-test-service"), + AgentMcpResourceAdmission.create(new org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig( + 128, 64, 32, 16, 8, 16)), resources); } private String config(final Fixture first, final Fixture second) { 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-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<>(); 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 1490f477ae39..e853924283f3 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 @@ -139,12 +139,14 @@ private Mono executeRequest(final ServerWebExchange exchange, final Select final String realApiKey; if (Objects.nonNull(handle) && "true".equalsIgnoreCase(handle.getProxyEnabled())) { String proxyKey = exchange.getRequest().getHeaders().getFirst(Constants.X_API_KEY); - realApiKey = Objects.isNull(proxyKey) || proxyKey.isEmpty() ? null - : AiProxyApiKeyCache.getInstance().getRealApiKey(selector.getId(), proxyKey); + ProxyApiKeyData mapping = Objects.isNull(proxyKey) || proxyKey.isEmpty() ? null + : AiProxyApiKeyCache.getInstance().getValidatedMapping(selector.getId(), proxyKey); + realApiKey = Objects.isNull(mapping) ? null : mapping.getRealApiKey(); if (Objects.isNull(realApiKey)) { exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); return exchange.getResponse().setComplete(); } + observation.updateContext(observation.getContext().withApiKeyId(mapping.getId())); } else { realApiKey = null; } 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 d80cafd34e67..d21fd580306f 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 @@ -78,9 +78,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.apache.shenyu.plugin.ai.proxy.enhanced.AiProxyTestUtils.protocolRouteResolver; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.apache.shenyu.plugin.ai.proxy.enhanced.AiProxyTestUtils.protocolRouteResolver; import static org.junit.jupiter.api.Assertions.assertTrue; /** 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/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/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..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 @@ -17,8 +17,10 @@ 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.governance.AgentGovernanceContractLabels; 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 +86,16 @@ public synchronized void authenticationRejected(final AuthenticationSource sourc } } + @Override + public synchronized void governanceDecision(final AgentGovernanceDecision decision) { + if (active) { + 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); + } + } + 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 096bf972a3c1..3638ac922b2c 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,7 @@ public static synchronized void register(final MetricsRegister metricsRegister) 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); for (CanaryMetric metric : CanaryMetric.values()) { if (Objects.isNull(metric.getBuckets())) { 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-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-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 7ff3e5855cb6..09c7e0d20e75 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 @@ -36,8 +36,11 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; public class KeyAuthPlugin extends AbstractShenyuPlugin { @@ -80,7 +83,7 @@ private Mono rejected(final ServerWebExchange exchange, final Object error final RuleData rule, final String reason) { return Mono.defer(() -> { long started = System.nanoTime(); - String requestId = java.util.UUID.randomUUID().toString(); + String requestId = UUID.randomUUID().toString(); return WebFluxResultUtils.result(exchange, error).doFinally(signal -> { Object sink = exchange.getAttribute(AgentInvocationAuditObserver.EXCHANGE_ATTRIBUTE); if (sink instanceof AgentInvocationAuditObserver audit) { @@ -88,9 +91,9 @@ private Mono rejected(final ServerWebExchange exchange, final Object error 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) + .outcome(signal == 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()); + .elapsedMillis(TimeUnit.NANOSECONDS.toMillis(Math.max(0, System.nanoTime() - started))).build()); } catch (RuntimeException ignored) { // Rejection and its response must not depend on diagnostic delivery. } 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); 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 new file mode 100644 index 000000000000..b617fb33b623 --- /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/AgentGatewayAdmissionControllerService.java @@ -0,0 +1,43 @@ +/* + * 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.AgentGatewayAdmissionConfig; +import org.apache.shenyu.common.dto.AgentGatewayAggregationConfig; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; + +/** Applies trusted global/local limits independently of optional remote discovery. */ +public final class AgentGatewayAdmissionControllerService { + + private final AgentMcpResourceAdmission.ResourceAdmissionController controller; + + AgentGatewayAdmissionControllerService(final AgentMcpResourceAdmission.ResourceAdmissionController controller) { + this.controller = controller; + } + + /** + * Validate limits and atomically update the active controller's accounting state. + * @param source complete trusted plugin configuration + * @return immutable active limits + */ + public AgentGatewayAdmissionConfig update(final String source) { + AgentGatewayAdmissionConfig config = AgentGatewayAggregationConfig.parsePluginConfig(source).admission(); + controller.replace(AgentMcpResourceAdmission.create(config)); + return config; + } +} 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 c400152c4172..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 @@ -20,8 +20,14 @@ import io.opentelemetry.api.OpenTelemetry; import org.apache.shenyu.common.audit.AgentInvocationAuditBridge; import org.apache.shenyu.common.audit.AgentInvocationAuditObserver; +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; @@ -29,6 +35,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; @@ -45,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; @@ -63,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"; @@ -77,18 +86,22 @@ public class AgentGatewayPluginConfiguration { * @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 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 public ShenyuPlugin agentGatewayPlugin(final ObjectProvider providers, final ObjectProvider resolvers, final ObjectProvider catalogs, final ObjectProvider resources, final ObjectProvider tracers, + final ObjectProvider admissions, 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"); @@ -109,37 +122,101 @@ 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, resources, + 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, final AgentMcpRemoteCatalog catalog, final AgentMcpCallTracer tracer, - final ObjectProvider resources, final AgentMcpTerminalObserver terminalObserver, - final AiCallObserver aiObserver, final boolean llmIdentityEnabled) { + final ObjectProvider resources, + final AgentMcpResourceAdmission.ResourceAdmissionController admission, + final AgentMcpTerminalObserver terminalObserver, final AiCallObserver aiObserver, + 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()) { throw new IllegalStateException("Enabled LLM identity mapping requires an authoritative security resolver"); } AgentResourceRegistry resourceRegistry = new AgentResourceRegistry(resources.orderedStream().toList()); - return new AgentGatewayPlugin(new AgentMcpHttpHandler(new AgentMcpDispatcher(registry, "shenyu-agent-gateway", - AgentGatewayConstants.MCP_SERVER_VERSION, catalog, resourceRegistry), resolver, tracer, terminalObserver), + AgentMcpResourceAdmission effectiveAdmission = java.util.Objects.requireNonNullElse(admission, + java.util.Objects.isNull(catalog) ? AgentMcpResourceAdmission.NOOP : catalog.admission()); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher(registry, "shenyu-agent-gateway", + AgentGatewayConstants.MCP_SERVER_VERSION, catalog, resourceRegistry, + 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. * * @param catalogs optional data-sync managed remote catalog + * @param admissions application-owned admission update service * @return the data handler */ @Bean - public PluginDataHandler agentGatewayPluginDataHandler(final ObjectProvider catalogs) { + public PluginDataHandler agentGatewayPluginDataHandler(final ObjectProvider catalogs, + final ObjectProvider admissions) { + AgentGatewayAdmissionControllerService admission = admissions.getIfAvailable(); ManagedRemoteMcpCatalog catalog = catalogs.getIfAvailable(); - return new AgentGatewayPluginDataHandler(java.util.Objects.isNull(catalog) ? ignored -> { } : catalog::accept); + return new AgentGatewayPluginDataHandler(plugin -> { + 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); + } + }); + } + + /** + * Own local and global resource limits independently of optional remote discovery. + * @param environment deployment-controlled initial admission configuration + * @return closeable admission controller + */ + @Bean(destroyMethod = "close") + @ConditionalOnMissingBean(AgentMcpResourceAdmission.ResourceAdmissionController.class) + public AgentMcpResourceAdmission.ResourceAdmissionController agentGatewayResourceAdmission(final Environment environment) { + AgentGatewayAdmissionConfig initial = AgentGatewayAggregationConfig.parsePluginConfig( + environment.getProperty("shenyu.plugins.agent.gateway.admission.config", "{}")).admission(); + return AgentMcpResourceAdmission.create(initial); + } + + /** + * Publish trusted admission updates to the independently owned controller. + * @param controller the sole active resource controller + * @return application-wide controller service + */ + @Bean + public AgentGatewayAdmissionControllerService agentGatewayAdmissionControllerService( + final AgentMcpResourceAdmission.ResourceAdmissionController controller) { + return new AgentGatewayAdmissionControllerService(controller); } /** @@ -147,18 +224,21 @@ public PluginDataHandler agentGatewayPluginDataHandler(final ObjectProvider tools, - final ObjectProvider credentials) { + final ObjectProvider credentials, + final AgentMcpResourceAdmission.ResourceAdmissionController admission) { String endpoints = environment.getRequiredProperty("shenyu.plugins.agent.gateway.aggregation.allowed-endpoints"); Set allowed = Arrays.stream(endpoints.split(",")).map(String::trim).map(URI::create).collect(Collectors.toUnmodifiableSet()); RemoteServiceCredentialResolver resolver = credentials.getIfAvailable(() -> new FileRemoteServiceCredentialResolver( Path.of(environment.getRequiredProperty("shenyu.plugins.agent.gateway.aggregation.credentials-directory")))); - return new ManagedRemoteMcpCatalog(allowed, tools.orderedStream().map(AgentToolProvider::getName).collect(Collectors.toUnmodifiableSet()), resolver, + return new ManagedRemoteMcpCatalog(allowed, + tools.orderedStream().map(AgentToolProvider::getName).collect(Collectors.toUnmodifiableSet()), resolver, admission, environment.getProperty("shenyu.plugins.agent.gateway.aggregation.resources-enabled", Boolean.class, false)); } 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..72c331f2cd25 --- /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,127 @@ +/* + * 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.apache.shenyu.common.governance.AgentGovernanceText; +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.time.Duration; + +/** + * 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 AgentMcpQuotaConfig.Mode mode = AgentMcpQuotaConfig.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 AgentMcpQuotaConfig.Mode getMode() { + return mode; + } + + public void setMode(final AgentMcpQuotaConfig.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(mode, invocationLimit, + invocationWindow, concurrencyLimit, leaseTtl, failOpen); + } + + public String trustedPolicyVersion() { + return AgentGovernanceText.require(policyVersion, "policyVersion", 128); + } + +} 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 dfcb9474f0a3..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 @@ -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; @@ -32,28 +35,44 @@ import org.apache.shenyu.plugin.agent.gateway.resource.AgentResourceInvocation; 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.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; +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; +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.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; 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 { @@ -179,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(AgentMcpQuotaConfig.Mode.ENFORCE); + assertEquals(AgentMcpQuotaConfig.Mode.ENFORCE, properties.toConfig().getMode()); + } + @Test void shouldAssembleExplicitResourcesWithSeparatePermissions() { AgentResourceProvider provider = new AgentResourceProvider() { @@ -242,6 +327,138 @@ void shouldWireExplicitToolAndTrustedSecurityAdapter() { }); } + @Test + void localOnlyGatewayUsesAndReloadsIndependentAdmission() throws Exception { + Sinks.Empty activeTool = Sinks.empty(); + AtomicInteger calls = new AtomicInteger(); + final AgentToolProvider tool = new AgentToolProvider() { + @Override + public String getName() { + return "read"; + } + + @Override + public String getDescription() { + return "Read a resource"; + } + + @Override + public JsonObject getInputSchema() { + return JsonParser.parseString("{\"type\":\"object\"}").getAsJsonObject(); + } + + @Override + public void validate(final JsonObject arguments) { + } + + @Override + public Mono invoke(final org.apache.shenyu.plugin.agent.gateway.tool.AgentToolInvocation invocation) { + return Mono.defer(() -> { + calls.incrementAndGet(); + return activeTool.asMono().map(ignored -> new JsonObject()); + }); + } + }; + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true") + .withBean(AgentToolProvider.class, () -> tool) + .withBean(AgentMcpSecurityResolver.class, () -> exchange -> Mono.just(new AgentMcpIdentity("tenant", Set.of("read")))) + .run(context -> { + final AgentMcpResourceAdmission.ResourceAdmissionController admission = + context.getBean(AgentMcpResourceAdmission.ResourceAdmissionController.class); + assertEquals(32, admission.snapshot().stream() + .filter(snapshot -> snapshot.scope() == org.apache.shenyu.common.metrics.AgentAdmissionMetrics.Scope.LOCAL) + .findFirst().orElseThrow().inFlightLimit()); + context.getBean(PluginDataHandler.class).handlerPlugin(pluginData("{\"admission\":{" + + "\"globalInFlight\":8,\"globalQueued\":4,\"localInFlight\":1,\"localQueued\":0," + + "\"remoteInFlight\":2,\"remoteQueued\":2}}")); + assertEquals(1, admission.snapshot().stream() + .filter(snapshot -> snapshot.scope() == org.apache.shenyu.common.metrics.AgentAdmissionMetrics.Scope.LOCAL) + .findFirst().orElseThrow().inFlightLimit()); + AgentMcpHttpHandler handler = (AgentMcpHttpHandler) ReflectionTestUtils.getField(context.getBean(AgentGatewayPlugin.class), "mcpHandler"); + AgentMcpDispatcher dispatcher = (AgentMcpDispatcher) ReflectionTestUtils.getField(handler, "dispatcher"); + assertEquals(admission, ReflectionTestUtils.getField(dispatcher, "admission")); + AgentGatewayMcpConfig config = AgentGatewayMcpConfig.parse(JsonParser.parseString("{\"allowedTools\":[\"read\"]}"), true); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + MockServerWebExchange firstExchange = exchange(); + 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)) + .verifyComplete(); + assertEquals(429, rejectedExchange.getResponse().getStatusCode().value()); + assertTrue(rejectedExchange.getResponse().getBodyAsString().block().contains("-32026")); + assertEquals(1, calls.get()); + activeTool.tryEmitEmpty(); + first.get(5, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + }); + } + + private static void awaitLocalInFlight(final AgentMcpResourceAdmission.ResourceAdmissionController admission, final int expected) + throws InterruptedException { + for (int i = 0; i < 200; i++) { + if (admission.snapshot().stream() + .anyMatch(snapshot -> snapshot.scope() == org.apache.shenyu.common.metrics.AgentAdmissionMetrics.Scope.LOCAL + && snapshot.inFlight() == expected)) { + return; + } + TimeUnit.MILLISECONDS.sleep(10); + } + throw new AssertionError("local admission execution was not acquired"); + } + + private PluginData pluginData(final String config) { + PluginData plugin = new PluginData(); + plugin.setEnabled(true); + plugin.setConfig(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") 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 index eb26acc1cc0e..5a2a7a805287 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/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 @@ -34,6 +34,7 @@ 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.protocol.AgentMcpResourceAdmission; 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; @@ -221,7 +222,8 @@ private Fixture(final boolean sse) throws Exception { 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")); + catalog = new ManagedRemoteMcpCatalog(Set.of(endpoint), Set.of(), target -> new RemoteServerBinding.Credential(target, "fixed-service-token"), + AgentMcpResourceAdmission.create(new org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig(128, 64, 32, 16, 8, 16)), false); 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,