diff --git a/docs/agent-gateway-controlled-mcp-https.md b/docs/agent-gateway-controlled-mcp-https.md new file mode 100644 index 000000000000..465d3808b87c --- /dev/null +++ b/docs/agent-gateway-controlled-mcp-https.md @@ -0,0 +1,44 @@ +# Controlled MCP HTTPS routes + +Agent Gateway remote MCP targets remain deployment-controlled. Fixed-IP HTTPS keeps +its historical behavior. A DNS hostname may be used only when deployment properties +also approve the exact hostname, port, path, and IPv4 address that the transport may +connect to. + +## Deployment configuration + +Set `shenyu.plugins.agent.gateway.aggregation.allowed-routes` to comma-separated +`endpoint=approvedIPv4` entries, for example: + +```properties +shenyu.plugins.agent.gateway.aggregation.allowed-routes=https://mcp.example.com:443/mcp=203.0.113.10,https://192.0.2.20:8443/mcp= +``` + +Existing fixed-IP deployments may continue to use the historical comma-separated +`allowed-endpoints` property. At least one approved fixed endpoint or controlled +route is required when aggregation is enabled. + +An empty address is valid only for a fixed-IP endpoint. A hostname without an address +is rejected. Admin plugin configuration still selects a configured endpoint and its +target-bound credential; it cannot add routes, alter approved addresses, or expand TLS +policy. + +## Connection and credential semantics + +- The transport uses the original HTTPS hostname for DNS-independent route identity, + SNI, and certificate hostname validation, but connects to the approved IPv4 address. + This prevents an implicit JVM DNS lookup from bypassing route policy. +- Each target and credential version receives its own bounded pooled client. A + configuration refresh retires the old generation immediately for new requests, while + an already acquired in-flight generation remains bound to its prior credential and + client. Its client is closed after the last lease is released. +- Redirects, cookies, authentication caching, connection state, and proxy use remain + disabled. Untrusted certificates, hostname mismatches, missing routes, and changed + destinations fail closed. +- Route or credential replacement does not roll back a remote side effect performed by + an in-flight request. Emergency revocation stops new requests and closes the old + client after its leases drain. + +Dynamic DNS refresh, service discovery refresh, IPv6, delegated OAuth, and enterprise +proxies remain outside this contract. Coordinate dynamic resolution with the remote +directory refresh work rather than adding a second discovery system here. diff --git a/docs/agent-gateway-resource-admission.md b/docs/agent-gateway-resource-admission.md new file mode 100644 index 000000000000..95d7bbe8a828 --- /dev/null +++ b/docs/agent-gateway-resource-admission.md @@ -0,0 +1,43 @@ +# 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/pom.xml b/pom.xml index 230113de8d1a..fb4d0ca2e9da 100644 --- a/pom.xml +++ b/pom.xml @@ -801,6 +801,11 @@ caffeine ${caffeine.version} + + org.apache.httpcomponents + httpasyncclient + ${httpasyncclient.version} + com.netflix.eureka 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..c66b9cbd64bd 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"); @@ -97,10 +109,25 @@ private static void fields(final JsonNode node, final Set expected) { } /** - * Validate the agreed fixed-IP transport boundary at both Admin and gateway. + * Validate a fixed IP or an explicitly controlled HTTPS hostname at Admin and gateway. * @param endpoint exact configured endpoint, never an Agent-supplied URL */ public static void validateEndpoint(final URI endpoint) { + if (Objects.isNull(endpoint) || Objects.isNull(endpoint.getHost())) { + throw new IllegalArgumentException("Invalid MCP Server endpoint"); + } + if (endpoint.getHost().matches("(?:0|[1-9][0-9]{0,2})(?:\\.(?:0|[1-9][0-9]{0,2})){3}")) { + validateFixedEndpoint(endpoint); + return; + } + validateHttpsHostnameEndpoint(endpoint); + } + + /** + * Validate the historical fixed-IP transport boundary. + * @param endpoint exact configured endpoint, never an Agent-supplied URL + */ + public static void validateFixedEndpoint(final URI endpoint) { if (Objects.isNull(endpoint) || Objects.isNull(endpoint.getHost()) || !literalIpv4(endpoint.getHost()) || !("https".equals(endpoint.getScheme()) || "http".equals(endpoint.getScheme()) && "127.0.0.1".equals(endpoint.getHost())) || endpoint.getPort() < 1 || endpoint.getPort() > 65535 || Objects.nonNull(endpoint.getRawUserInfo()) @@ -108,6 +135,32 @@ public static void validateEndpoint(final URI endpoint) { || !endpoint.normalize().equals(endpoint) || !endpoint.getRawPath().matches("/(?:[A-Za-z0-9._~-]+/)*[A-Za-z0-9._~-]+")) { throw new IllegalArgumentException("Invalid fixed-IP MCP Server endpoint"); } + validatePath(endpoint); + } + + /** + * Validate an HTTPS hostname target without resolving or approving its address. + * @param endpoint exact configured endpoint, never an Agent-supplied URL + */ + public static void validateHttpsHostnameEndpoint(final URI endpoint) { + validateHttpsHostnameShape(endpoint); + } + + private static void validateHttpsHostnameShape(final URI endpoint) { + if (Objects.isNull(endpoint) || Objects.isNull(endpoint.getHost()) || !endpoint.getHost().matches("(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.){0,5}[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?") + || endpoint.getHost().length() > 253 || !"https".equals(endpoint.getScheme()) + || endpoint.getPort() < 1 || endpoint.getPort() > 65535 || Objects.nonNull(endpoint.getRawUserInfo()) + || Objects.nonNull(endpoint.getRawQuery()) || Objects.nonNull(endpoint.getRawFragment()) + || !endpoint.normalize().equals(endpoint)) { + throw new IllegalArgumentException("Invalid controlled HTTPS hostname endpoint"); + } + validatePath(endpoint); + } + + private static void validatePath(final URI endpoint) { + if (Objects.isNull(endpoint.getRawPath()) || !endpoint.getRawPath().matches("/(?:[A-Za-z0-9._~-]+/)*[A-Za-z0-9._~-]+")) { + throw new IllegalArgumentException("Invalid MCP Server endpoint path"); + } for (String part : endpoint.getRawPath().split("/")) { if (Set.of(".", "..").contains(part)) { throw new IllegalArgumentException("Ambiguous MCP endpoint"); diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java new file mode 100644 index 000000000000..4c87eccb4bf7 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/metrics/AgentAdmissionMetrics.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.shenyu.common.metrics; + +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** Live payload-free admission snapshots, without tool, subject, tenant, or endpoint labels. */ +public final class AgentAdmissionMetrics implements AutoCloseable { + + private static final Set SOURCES = ConcurrentHashMap.newKeySet(); + + private final Supplier> source; + + private AgentAdmissionMetrics(final Supplier> source) { + this.source = source; + } + + /** + * Register one controller after startup; the controller owns this registration. + * @param source in-memory snapshot supplier + * @return registration removed by close + */ + public static AgentAdmissionMetrics register(final Supplier> source) { + AgentAdmissionMetrics value = new AgentAdmissionMetrics(source); + SOURCES.add(value); + return value; + } + + /** Aggregate all live controller states. + * @return immutable snapshots + */ + public static List snapshots() { + return SOURCES.stream().flatMap(registration -> { + try { + return registration.source.get().stream(); + } catch (RuntimeException ignored) { + return java.util.stream.Stream.empty(); + } + }).toList(); + } + + @Override + public void close() { + SOURCES.remove(this); + } + + /** One bounded scope; names never carry request or target identity. */ + public record Snapshot(Scope scope, int inFlight, int queued, int inFlightLimit, int queueLimit, long rejected) { + } + + /** Fixed admission scopes, safe as metric labels. */ + public enum Scope { + GLOBAL, LOCAL, REMOTE + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/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..4f1d01c4db06 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 @@ -33,6 +33,12 @@ void emptyConfigurationIsExplicitLocalOnly(final String source) { assertTrue(AgentGatewayAggregationConfig.parsePluginConfig(source).servers().isEmpty()); } + @Test + void acceptsControlledHttpsHostnameEndpointShape() { + String server = "{\"name\":\"orders\",\"endpoint\":\"https://example.com:443/mcp\",\"credentialRef\":\"service/orders\",\"credentialVersion\":\"v1\"}"; + assertEquals("https://example.com:443/mcp", AgentGatewayAggregationConfig.parsePluginConfig(wrap(server)).servers().get(0).endpoint().toString()); + } + @ParameterizedTest @ValueSource(strings = {"[]", "null", "{\"unknown\":1}", "{\"aggregation\":null}", "{\"aggregation\":{\"revision\":\"v1\"}}", "{\"aggregation\":{\"revision\":\"v1\",\"servers\":{}}}", @@ -54,10 +60,39 @@ 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", - "https://example.com:443/mcp", "http://192.0.2.10:8080/mcp", "https://0.0.0.0:443/mcp", "https://255.255.255.255:443/mcp"}) + "http://example.com:443/mcp", "http://192.0.2.10:8080/mcp", "https://0.0.0.0:443/mcp", "https://255.255.255.255:443/mcp"}) void rejectsAmbiguousEndpoints(final String endpoint) { String server = "{\"name\":\"orders\",\"endpoint\":\"" + endpoint + "\",\"credentialRef\":\"service/orders\",\"credentialVersion\":\"v1\"}"; assertThrows(IllegalArgumentException.class, () -> AgentGatewayAggregationConfig.parsePluginConfig(wrap(server))); diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml b/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml index ab93136a3bf9..601a1f7ffa2a 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/pom.xml @@ -50,6 +50,10 @@ ${project.version} test + + org.apache.httpcomponents + httpasyncclient + io.modelcontextprotocol.sdk mcp-core 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..69baa4a49cac 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,18 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.shenyu.common.dto.AgentGatewayHttpToolConfig; +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 +52,8 @@ public final class AgentMcpDispatcher { private final AgentMcpRemoteCatalog remoteCatalog; + private final AgentMcpResourceAdmission admission; + private final AgentMcpResourceDispatcher resources; private final AgentResourceRegistry resourceRegistry; @@ -66,15 +69,52 @@ 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 = 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"); if (Objects.requireNonNull(serverName, "serverName").isBlank() || Objects.requireNonNull(serverVersion, "serverVersion").isBlank()) { throw new IllegalArgumentException("Server identity must not be blank"); } @@ -106,7 +146,8 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier bound); + return new AgentMcpDispatcher(captured, serverName, serverVersion, remoteCatalog, + resourceRegistry, Objects.isNull(remoteCatalog) ? admission : remoteCatalog.admission()).dispatch(request, () -> bound); } if (Objects.nonNull(remoteCatalog)) { return remoteCatalog.withSnapshot(snapshot -> routeWithRemote(request, context, snapshot)) @@ -141,6 +182,13 @@ public Mono dispatch(final AgentMcpRequest request, final Supplier routeWithRemote(final AgentMcpRequest request, final Ag ObjectNode params = request.getParams(); JsonObject arguments = params.has("arguments") ? JsonParser.parseString(params.get("arguments").toString()).getAsJsonObject() : new JsonObject(); return Mono.defer(() -> { - context.notifyAttempt(); - return snapshot.invoke(name, arguments, context); + return admission.withRemote(remoteServer(name), context.getDeadline(), + Mono.fromRunnable(context::notifyAttempt).then(snapshot.invoke(name, arguments, context))); }) .switchIfEmpty(Mono.error(new IllegalStateException("Remote tool completed without a result"))) .map(value -> { @@ -265,7 +313,8 @@ private Mono call(final AgentMcpRequest request, final AgentMcpExecu JsonObject capabilities = request.getClientCapabilities(); return registry.invoke(name, context.getAllowedTools(), () -> new AgentToolInvocation(context.getRequestId(), context.getSubject(), arguments, - context.getRuleId(), context.getConfigurationVersion(), context.getDeadline(), capabilities), context::notifyAttempt) + context.getRuleId(), context.getConfigurationVersion(), context.getDeadline(), capabilities), context::notifyAttempt, + execution -> admission.withLocal(context.getDeadline(), execution)) .map(value -> { // Active field policies must not introduce an opaque metadata channel. ObjectNode result = filter.isActive() ? mapper.createObjectNode().put("resultType", "complete") : complete(); @@ -296,6 +345,11 @@ private ObjectNode toolFailure(final AgentMcpRequest request, final String messa return response(request, filterResult(request, filter, result)); } + private String remoteServer(final String exposedName) { + int separator = exposedName.indexOf('.'); + return separator > 0 ? exposedName.substring(0, separator) : exposedName; + } + private AgentMcpResultFilter prepareResultFilter(final AgentMcpRequest request, final AgentMcpExecutionContext context, final String name, final JsonNode schema) { try { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/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..873ff05c25f5 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpRemoteCatalog.java @@ -36,6 +36,14 @@ public interface AgentMcpRemoteCatalog { */ Mono withSnapshot(Function> operation); + /** Return the closeable request-admission controller owned by this catalog. + * @return controller implementation + */ + default AgentMcpResourceAdmission admission() { + return AgentMcpResourceAdmission.NOOP; + } + + /** Distinguishes an unavailable catalog from unexpected gateway failures. */ final class CatalogUnavailableException extends IllegalStateException { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java new file mode 100644 index 000000000000..5de88a82121b --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpResourceAdmission.java @@ -0,0 +1,133 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.shenyu.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.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 java.util.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/ApacheRemoteHttpResponse.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteHttpResponse.java new file mode 100644 index 000000000000..7f39fd1b4c39 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteHttpResponse.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.plugin.agent.gateway.remote; + +import org.apache.http.Header; +import org.apache.http.HttpResponse; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** Immutable HTTP response adapter used by the target-owned Apache transport. */ +final class ApacheRemoteHttpResponse { + + private final int status; + + private final Map> headers; + + private final ByteArrayOutputStream body; + + private ApacheRemoteHttpResponse(final int status, final Map> headers, final ByteArrayOutputStream body) { + this.status = status; + this.headers = Map.copyOf(headers); + this.body = body; + } + + static ApacheRemoteHttpResponse from(final HttpResponse response, final ByteArrayOutputStream body) { + Map> values = new java.util.TreeMap<>(String.CASE_INSENSITIVE_ORDER); + for (Header header : response.getAllHeaders()) { + values.computeIfAbsent(header.getName().toLowerCase(Locale.ROOT), ignored -> new java.util.ArrayList<>()).add(header.getValue()); + } + return new ApacheRemoteHttpResponse(response.getStatusLine().getStatusCode(), values, body); + } + + int status() { + return status; + } + + Map> headers() { + return headers; + } + + byte[] body() { + return body.toByteArray(); + } + +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteMcpTransport.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteMcpTransport.java new file mode 100644 index 000000000000..3880a28fd2ce --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ApacheRemoteMcpTransport.java @@ -0,0 +1,376 @@ +/* + * 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 org.apache.http.conn.routing.HttpRoute; +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.client.RedirectStrategy; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.concurrent.FutureCallback; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.nio.IOControl; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; +import org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionFactory; +import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; +import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; +import org.apache.http.impl.nio.reactor.IOReactorConfig; +import org.apache.http.nio.conn.SchemeIOSessionStrategy; +import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; +import org.apache.http.nio.protocol.BasicAsyncRequestProducer; +import org.apache.http.nio.protocol.HttpAsyncRequestProducer; +import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; +import org.apache.http.nio.reactor.ConnectingIOReactor; +import org.apache.http.nio.reactor.IOReactorException; +import org.apache.http.protocol.HttpContext; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; + +import javax.net.ssl.SSLContext; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.Objects; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +/** + * One exclusively owned, bounded pooled transport per target and credential generation. + * The connection manager maps the approved hostname only to its approved IPv4 address; + * TLS and SNI continue to use the original HttpHost hostname. + */ +final class ApacheRemoteMcpTransport implements AutoCloseable { + + private static final int MAX_POOL = 8; + + private final ConnectingIOReactor reactor; + + private final PoolingNHttpClientConnectionManager connections; + + private final CloseableHttpAsyncClient client; + + private ApacheRemoteMcpTransport(final ConnectingIOReactor reactor, final PoolingNHttpClientConnectionManager connections, + final CloseableHttpAsyncClient client) { + this.reactor = reactor; + this.connections = connections; + this.client = client; + } + + static ApacheRemoteMcpTransport create(final RemoteTransportRoute route, final SSLContext testContext) { + SSLContext context; + try { + context = Objects.isNull(testContext) ? SSLContext.getDefault() : testContext; + } catch (java.security.NoSuchAlgorithmException error) { + throw new IllegalStateException("Remote MCP TLS initialization failed"); + } + try { + IOReactorConfig reactorConfig = IOReactorConfig.custom() + .setIoThreadCount(1) + .setConnectTimeout(2000) + .setTcpNoDelay(true) + .setSoKeepAlive(true) + .setSndBufSize(8192) + .setRcvBufSize(8192) + .build(); + ConnectingIOReactor reactor = new DefaultConnectingIOReactor(reactorConfig, task -> { + Thread thread = new Thread(task, "shenyu-agent-mcp-transport"); + thread.setDaemon(true); + return thread; + }); + Registry strategies = RegistryBuilder.create() + .register("https", new SSLIOSessionStrategy(context)) + .register("http", NoopIOSessionStrategy.INSTANCE) + .build(); + PoolingNHttpClientConnectionManager connections = new PoolingNHttpClientConnectionManager( + reactor, ManagedNHttpClientConnectionFactory.INSTANCE, strategies, new FixedAddressResolver(route), 30, TimeUnit.SECONDS); + connections.setMaxTotal(MAX_POOL); + connections.setDefaultMaxPerRoute(MAX_POOL); + CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create() + .setConnectionManager(connections) + .setMaxConnTotal(MAX_POOL) + .setMaxConnPerRoute(MAX_POOL) + .setConnectionTimeToLive(30, TimeUnit.SECONDS) + .setRedirectStrategy(new NeverRedirectStrategy()) + .disableConnectionState() + .disableCookieManagement() + .disableAuthCaching() + .build(); + client.start(); + return new ApacheRemoteMcpTransport(reactor, connections, client); + } catch (IOReactorException error) { + throw new IllegalStateException("Remote MCP transport initialization failed"); + } + } + + AsyncRequestHandle execute(final HttpHost target, final HttpRequest request, + final long deadlineMillis) { + int timeout = deadlineMillis > Integer.MAX_VALUE ? Integer.MAX_VALUE : Math.max(1, (int) deadlineMillis); + RequestConfig config = RequestConfig.custom() + .setRedirectsEnabled(false) + .setConnectionRequestTimeout(timeout) + .setConnectTimeout(timeout) + .setSocketTimeout(timeout) + .build(); + HttpRequest configured = request instanceof ConfigurableRequest configurable + ? configurable.withConfig(config) + : request; + HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(target, configured); + Sinks.One completion = Sinks.one(); + Future owned = client.execute(producer, new BoundedResponseConsumer(), new FutureCallback() { + @Override + public void completed(final ApacheRemoteHttpResponse result) { + completion.tryEmitValue(result); + } + + @Override + public void failed(final Exception error) { + completion.tryEmitError(error); + } + + @Override + public void cancelled() { + completion.tryEmitError(new IllegalStateException("Remote MCP request cancelled")); + } + }); + return new AsyncRequestHandle<>(owned, completion); + } + + @Override + public void close() throws IOException { + try { + client.close(); + } finally { + connections.shutdown(); + reactor.shutdown(); + } + } + + /** Bind the approved route and port while retaining the original target hostname. */ + private static final class FixedAddressResolver implements org.apache.http.nio.pool.SocketAddressResolver { + + private final RemoteTransportRoute route; + + private FixedAddressResolver(final RemoteTransportRoute route) { + this.route = route; + } + + @Override + public SocketAddress resolveLocalAddress(final HttpRoute key) { + return null; + } + + @Override + public SocketAddress resolveRemoteAddress(final HttpRoute key) { + HttpHost target = key.getTargetHost(); + if (!route.endpoint().getHost().equalsIgnoreCase(target.getHostName()) || route.endpoint().getPort() != target.getPort()) { + throw new IllegalStateException("Unauthorized remote MCP route"); + } + return new InetSocketAddress(route.address(), route.endpoint().getPort()); + } + } + + /** Bridge the client future to the already subscribed Reactor signal without blocking callers. */ + static final class AsyncRequestHandle implements Future { + + private final Future owned; + + private final Sinks.One completion; + + /** Bridge a completion-stage-like future for isolated tests and production callbacks. */ + & java.util.concurrent.CompletionStage> AsyncRequestHandle(final F owned) { + this(owned, Sinks.one()); + owned.whenComplete((value, error) -> { + if (Objects.nonNull(error)) { + completion.tryEmitError(error); + } else { + completion.tryEmitValue(value); + } + }); + } + + private AsyncRequestHandle(final Future owned, final Sinks.One completion) { + this.owned = owned; + this.completion = completion; + } + + Mono signal() { + return completion.asMono(); + } + + @Override + public boolean cancel(final boolean mayInterruptIfRunning) { + return owned.cancel(mayInterruptIfRunning); + } + + @Override + public boolean isCancelled() { + return owned.isCancelled(); + } + + @Override + public boolean isDone() { + return owned.isDone(); + } + + @Override + public T get() { + return block(); + } + + @Override + public T get(final long timeout, final TimeUnit unit) throws InterruptedException, java.util.concurrent.TimeoutException { + T value = completion.asMono().block(java.time.Duration.ofMillis(unit.toMillis(timeout))); + if (Objects.isNull(value)) { + throw new java.util.concurrent.TimeoutException(); + } + return value; + } + + private T block() { + return completion.asMono().block(); + } + } + + /** Redirect execution is intentionally disabled by returning no redirect request. */ + private static final class NeverRedirectStrategy implements RedirectStrategy { + @Override + public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) { + return false; + } + + @Override + public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) { + return null; + } + } + + /** Exposes per-request timeouts to HttpAsyncClient's Configurable contract. */ + static final class ConfigurableRequest extends org.apache.http.message.BasicHttpEntityEnclosingRequest + implements org.apache.http.client.methods.Configurable { + + private RequestConfig config; + + ConfigurableRequest(final String method, final String uri) { + super(method, uri); + } + + ConfigurableRequest withConfig(final RequestConfig value) { + this.config = value; + return this; + } + + @Override + public RequestConfig getConfig() { + return config; + } + } + + /** Bounded response consumer retaining only headers and at most 8 KiB of body. */ + private static final class BoundedResponseConsumer implements HttpAsyncResponseConsumer { + + private static final int LIMIT = 8192; + + private final ByteArrayOutputStream body = new ByteArrayOutputStream(); + + private volatile boolean completed; + + private volatile ApacheRemoteHttpResponse response; + + private volatile Exception failure; + + private volatile boolean cancelled; + + @Override + public void responseReceived(final HttpResponse response) { + this.response = ApacheRemoteHttpResponse.from(response, body); + } + + @Override + public void consumeContent(final org.apache.http.nio.ContentDecoder decoder, final IOControl ioControl) throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(4096); + int count; + while ((count = decoder.read(buffer)) > 0) { + if (body.size() + count > LIMIT) { + throw new IOException("Response byte limit"); + } + buffer.flip(); + body.write(buffer.array(), 0, count); + buffer.clear(); + } + } + + @Override + public void responseCompleted(final HttpContext context) { + completed = true; + } + + @Override + public void failed(final Exception exception) { + failure = exception; + } + + @Override + public void close() throws IOException { + // The owned stream is only a bounded in-memory adapter. + } + + @Override + public boolean cancel() { + cancelled = true; + return true; + } + + @Override + public ApacheRemoteHttpResponse getResult() { + return completed && Objects.isNull(failure) && !cancelled ? response : null; + } + + @Override + public Exception getException() { + return failure; + } + + @Override + public boolean isDone() { + return completed || Objects.nonNull(failure) || cancelled; + } + + } + + /** Plain-HTTP strategy retained only for the historical loopback fixed-IP contract. */ + private enum NoopIOSessionStrategy implements SchemeIOSessionStrategy { + INSTANCE; + + @Override + public org.apache.http.nio.reactor.IOSession upgrade(final org.apache.http.HttpHost host, + final org.apache.http.nio.reactor.IOSession iosession) { + return iosession; + } + + @Override + public boolean isLayeringRequired() { + return false; + } + } +} 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..89db4ff87671 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; @@ -63,12 +65,16 @@ public final class ManagedRemoteMcpCatalog implements AgentMcpRemoteCatalog, Aut private final RemoteCatalogLifecycle lifecycle; - private final Set allowedEndpoints; + private final RemoteTransportRouteSet routes; private final Set localNames; private final RemoteServiceCredentialResolver credentials; + private final javax.net.ssl.SSLContext verificationTlsContext; + + 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)); @@ -84,22 +90,52 @@ public final class ManagedRemoteMcpCatalog implements AgentMcpRemoteCatalog, Aut private volatile boolean closed; /** - * Managed Remote Mcp Catalog. - * @param allowedEndpoints trusted allowedEndpoints value - * @param localNames trusted localNames value - * @param credentials trusted credentials value + * Managed catalog compatibility constructor for fixed-IP deployments. + * @param allowedEndpoints trusted fixed-IP endpoints + * @param localNames local tool names + * @param credentials fixed service credential resolver */ 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); } - public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames, final RemoteServiceCredentialResolver credentials, - final boolean resourcesEnabled) { + /** + * Managed catalog with a shared admission controller. + * @param allowedEndpoints trusted fixed-IP endpoints + * @param localNames local tool names + * @param credentials fixed service credential resolver + * @param admission shared controller + */ + public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set localNames, + final RemoteServiceCredentialResolver credentials, + final AgentMcpResourceAdmission.ResourceAdmissionController admission) { + this(allowedEndpoints, localNames, credentials, admission, false); + } + + /** + * Managed catalog with shared admission and resource lifecycle configuration. + * @param allowedEndpoints trusted fixed-IP endpoints + * @param localNames local tool names + * @param credentials fixed service credential resolver + * @param admission shared 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) { + this(fixedRoutes(allowedEndpoints), localNames, credentials, admission, resourcesEnabled, null); + } + + private ManagedRemoteMcpCatalog(final Set allowedRoutes, final Set localNames, + final RemoteServiceCredentialResolver credentials, + final AgentMcpResourceAdmission.ResourceAdmissionController admission, + final boolean resourcesEnabled, final javax.net.ssl.SSLContext verificationTlsContext) { lifecycle = new RemoteCatalogLifecycle(3, resourcesEnabled); - this.allowedEndpoints = Set.copyOf(allowedEndpoints); + this.routes = RemoteTransportRouteSet.parse(allowedRoutes); this.localNames = Set.copyOf(localNames); this.credentials = Objects.requireNonNull(credentials, "credentials"); - this.allowedEndpoints.forEach(RemoteTransportPolicy::endpoint); + this.admission = Objects.requireNonNull(admission, "admission"); + this.verificationTlsContext = verificationTlsContext; // The single owned subscription belongs to the control-plane lifecycle, never a request. lifecycle.refresh(List.of()).block(Duration.ofSeconds(6)); worker = updates.asFlux().publishOn(scheduler, 1).concatMap(this::applyUpdate, 1).subscribe(); @@ -113,11 +149,65 @@ public ManagedRemoteMcpCatalog(final Set allowedEndpoints, final Set allowedRoutes, final Set localNames, + final RemoteServiceCredentialResolver credentials) { + return forRoutes(allowedRoutes, localNames, credentials, false); + } + + /** + * Create a route-aware managed catalog with default admission. + * @param allowedRoutes trusted routes + * @param localNames local tool names + * @param credentials fixed service credential resolver + * @param resourcesEnabled whether remote resources are enabled + * @return route-aware catalog + */ + public static ManagedRemoteMcpCatalog forRoutes(final Set allowedRoutes, final Set localNames, + final RemoteServiceCredentialResolver credentials, final boolean resourcesEnabled) { + return forRoutes(allowedRoutes, localNames, credentials, AgentMcpResourceAdmission.create(AgentGatewayAdmissionConfig.parse(null)), resourcesEnabled); + } + + /** + * Create a route-aware managed catalog sharing the gateway admission controller. + * @param allowedRoutes trusted routes + * @param localNames local tool names + * @param credentials fixed service credential resolver + * @param admission shared controller + * @param resourcesEnabled whether remote resources are enabled + * @return route-aware catalog + */ + public static ManagedRemoteMcpCatalog forRoutes(final Set allowedRoutes, final Set localNames, + final RemoteServiceCredentialResolver credentials, + final AgentMcpResourceAdmission.ResourceAdmissionController admission, final boolean resourcesEnabled) { + return new ManagedRemoteMcpCatalog(allowedRoutes, localNames, credentials, admission, resourcesEnabled, null); + } + + static ManagedRemoteMcpCatalog forRoutesWithVerificationTlsContext(final Set allowedRoutes, final Set localNames, + final RemoteServiceCredentialResolver credentials, + final javax.net.ssl.SSLContext verificationTlsContext) { + return new ManagedRemoteMcpCatalog(allowedRoutes, localNames, credentials, + AgentMcpResourceAdmission.create(AgentGatewayAdmissionConfig.parse(null)), false, verificationTlsContext); + } + + private static Set fixedRoutes(final Set allowedEndpoints) { + return allowedEndpoints.stream().map(endpoint -> endpoint + "=").collect(java.util.stream.Collectors.toUnmodifiableSet()); + } + private Mono applyUpdate(final ControlUpdate update) { return Mono.defer(() -> { if (update.sequence() != revision.get()) { return Mono.empty(); } + if (!update.enabled()) { + return lifecycle.closeIdle().thenReturn(0L); + } return reload(update.source(), () -> !closed && update.sequence() == revision.get()).doOnSuccess(version -> { recordFailure(update.sequence(), ""); }).onErrorResume(error -> { @@ -146,7 +236,7 @@ public synchronized void accept(final PluginData plugin) { lastFailure = "ConfigurationByteLimit"; return; } - Sinks.EmitResult result = updates.tryEmitNext(new ControlUpdate(sequence, source)); + Sinks.EmitResult result = updates.tryEmitNext(new ControlUpdate(sequence, source, enabled)); if (result.isFailure() && !closed) { lifecycle.withdraw(); lastFailure = "ConfigurationQueueRejected"; @@ -174,9 +264,15 @@ private Mono reload(final String source, final BooleanSupplier stillCurren List targets = new ArrayList<>(); for (AgentGatewayAggregationConfig.Server server : config.servers()) { RemoteServerBinding.Config reference = new RemoteServerBinding.Config(server.name(), server.endpoint(), server.credentialRef(), server.credentialVersion()); - targets.add(RemoteServerBinding.resolve(reference, allowedEndpoints, credentials::resolve).lifecycleConfig()); + RemoteServerBinding binding = RemoteServerBinding.resolve(reference, routes, credentials::resolve); + targets.add(binding.lifecycleConfig(routes.route(server.endpoint()), verificationTlsContext)); } - 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 +293,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 +314,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 +343,7 @@ public Mono closeAsync() { return Mono.defer(() -> { closed = true; catalogMetrics.close(); + admission.close(); worker.dispose(); scheduler.dispose(); return lifecycle.closeGracefully(); @@ -245,7 +359,7 @@ public void close() { public record Diagnostics(RemoteCatalogLifecycle.Diagnostics lifecycle, long revision, String lastFailure) { } - private record ControlUpdate(long sequence, String source) { + private record ControlUpdate(long sequence, String source, boolean enabled) { } private static final class CatalogSnapshot implements Snapshot { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java index 9b8a7fa41edb..8f1337de4359 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteCatalogLifecycle.java @@ -342,7 +342,7 @@ private Mono release(final Generation generation) { }); } - private Mono closeIdle() { + Mono closeIdle() { List> tasks = new ArrayList<>(); synchronized (lock) { for (Generation generation : generations) { diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteServerBinding.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteServerBinding.java index 3588a10a1cf8..0c5c37575c36 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteServerBinding.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteServerBinding.java @@ -22,7 +22,6 @@ import java.net.URI; import java.util.Objects; -import java.util.Set; import java.util.function.Function; /** Immutable target and independently resolved credential binding. */ @@ -42,18 +41,17 @@ private RemoteServerBinding(final Config config, final Credential credential) { /** * resolve. * @param config trusted config value - * @param allowedEndpoints trusted allowedEndpoints value + * @param routes trusted approved routes * @param localResolver trusted localResolver value * @return operation result */ - public static RemoteServerBinding resolve(final Config config, final Set allowedEndpoints, final Function localResolver) { - if (Objects.isNull(config) || Objects.isNull(allowedEndpoints) || Objects.isNull(localResolver)) { + public static RemoteServerBinding resolve(final Config config, final RemoteTransportRouteSet routes, + final Function localResolver) { + if (Objects.isNull(config) || Objects.isNull(routes) || Objects.isNull(localResolver)) { throw new IllegalArgumentException("Missing controlled target configuration"); } - // Exact configured URI, including path/port. Never resolve an Agent-provided URL. - if (!Set.copyOf(allowedEndpoints).contains(config.endpoint())) { - throw new SecurityException("Target is not in the configured allowlist"); - } + // Exact configured URI, including path/port, must also have a deployment-approved address. + routes.route(config.endpoint()); Credential credential; try { credential = localResolver.apply(config); @@ -80,16 +78,35 @@ String authorization() { } /** - * new Client. + * new Client bound to the historical fixed-IP route. * @return operation result */ public RequestScopedMcpClient newClient() { - return new RequestScopedMcpClient(this, event -> { + return newClient(RemoteTransportRoute.fixed(config.endpoint())); + } + + /** + * new Client bound to an approved route. + * @param route trusted immutable route + * @return operation result + */ + public RequestScopedMcpClient newClient(final RemoteTransportRoute route) { + return newClient(route, null); + } + + /** + * new Client with an explicit test-only TLS context. + * @param route trusted immutable route + * @param testContext fixture TLS context + * @return operation result + */ + RequestScopedMcpClient newClient(final RemoteTransportRoute route, final javax.net.ssl.SSLContext testContext) { + return new RequestScopedMcpClient(this, route, event -> { if (LOG.isDebugEnabled()) { LOG.debug("Remote MCP response server={} method={} id={} status={} bytes={}", event.get("server"), event.get("method"), event.get("id"), event.get("status"), event.get("bytes")); } - }); + }, testContext); } /** @@ -97,7 +114,26 @@ public RequestScopedMcpClient newClient() { * @return operation result */ public RemoteCatalogLifecycle.Config lifecycleConfig() { - return new RemoteCatalogLifecycle.Config(config.name(), config.credentialVersion(), this::newClient); + return lifecycleConfig(RemoteTransportRoute.fixed(config.endpoint())); + } + + /** + * lifecycle Config with deployment-approved route. + * @param route trusted immutable route + * @return operation result + */ + public RemoteCatalogLifecycle.Config lifecycleConfig(final RemoteTransportRoute route) { + return lifecycleConfig(route, null); + } + + /** + * lifecycle Config with a verification-only TLS context. + * @param route trusted immutable route + * @param verificationTlsContext fixture TLS context, never production configuration + * @return lifecycle configuration + */ + RemoteCatalogLifecycle.Config lifecycleConfig(final RemoteTransportRoute route, final javax.net.ssl.SSLContext verificationTlsContext) { + return new RemoteCatalogLifecycle.Config(config.name(), config.credentialVersion(), () -> newClient(route, verificationTlsContext)); } @Override @@ -142,4 +178,5 @@ public String toString() { return "ServiceCredential[REDACTED]"; } } + } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicy.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicy.java index 2854ff2d519b..1f014c980fcd 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicy.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicy.java @@ -55,10 +55,26 @@ public void connectFailed(final URI uri, final SocketAddress address, final IOEx * @param uri trusted uri value */ public static void endpoint(final URI uri) { - // No DNS: JDK connects to the configured address and validates HTTPS against its IP SAN. + // Fixed IP keeps the historical JDK path; controlled hostnames require an approved route. org.apache.shenyu.common.dto.AgentGatewayAggregationConfig.validateEndpoint(uri); } + /** + * Validate a historical fixed-IP target. + * @param uri trusted uri value + */ + public static void fixedEndpoint(final URI uri) { + org.apache.shenyu.common.dto.AgentGatewayAggregationConfig.validateFixedEndpoint(uri); + } + + /** + * Validate an HTTPS hostname without resolving it. + * @param uri trusted uri value + */ + public static void httpsHostname(final URI uri) { + org.apache.shenyu.common.dto.AgentGatewayAggregationConfig.validateHttpsHostnameEndpoint(uri); + } + /** * session. * @param values trusted values value diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRoute.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRoute.java new file mode 100644 index 000000000000..1d6b4c16b410 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRoute.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.shenyu.plugin.agent.gateway.remote; + +import java.net.InetAddress; +import java.net.URI; +import java.net.UnknownHostException; +import java.util.Objects; + +/** + * Immutable route from an approved target URI to its single connection address. + * DNS targets must be accompanied by an operator-approved address, so the JDK + * never performs an implicit second resolution after policy validation. + */ +final class RemoteTransportRoute { + + private final URI endpoint; + + private final InetAddress address; + + private RemoteTransportRoute(final URI endpoint, final InetAddress address) { + this.endpoint = endpoint; + this.address = address; + } + + /** + * Create a route whose connection address is the endpoint's fixed IPv4 address. + * @param endpoint approved fixed-IP endpoint + * @return immutable route + */ + static RemoteTransportRoute fixed(final URI endpoint) { + RemoteTransportPolicy.fixedEndpoint(endpoint); + try { + return new RemoteTransportRoute(endpoint, InetAddress.getByName(endpoint.getHost())); + } catch (UnknownHostException error) { + throw new IllegalArgumentException("Invalid fixed MCP endpoint address"); + } + } + + /** + * Create a controlled DNS route without querying DNS. + * @param endpoint approved HTTPS hostname endpoint + * @param approvedAddress operator-approved literal IPv4 address + * @return immutable route + */ + static RemoteTransportRoute controlledDns(final URI endpoint, final String approvedAddress) { + RemoteTransportPolicy.httpsHostname(endpoint); + if (Objects.isNull(approvedAddress) || !approvedAddress.matches("(?:0|[1-9][0-9]{0,2})(?:\\.(?:0|[1-9][0-9]{0,2})){3}")) { + throw new IllegalArgumentException("Invalid approved MCP address"); + } + try { + InetAddress address = InetAddress.getByName(approvedAddress); + if (address.isAnyLocalAddress() || address.isLinkLocalAddress() + || address.isMulticastAddress() || address.getHostAddress().startsWith("224.") + || address.getHostAddress().startsWith("240.") || "255.255.255.255".equals(address.getHostAddress())) { + throw new IllegalArgumentException("Unapproved MCP address class"); + } + return new RemoteTransportRoute(endpoint, address); + } catch (UnknownHostException error) { + throw new IllegalArgumentException("Invalid approved MCP address"); + } + } + + URI endpoint() { + return endpoint; + } + + InetAddress address() { + return address; + } + + @Override + public boolean equals(final Object other) { + return other instanceof RemoteTransportRoute route && endpoint.equals(route.endpoint) && address.equals(route.address); + } + + @Override + public int hashCode() { + return Objects.hash(endpoint, address); + } + + @Override + public String toString() { + return "RemoteTransportRoute[endpoint=" + endpoint.getHost() + ", address=" + address.getHostAddress() + "]"; + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRouteSet.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRouteSet.java new file mode 100644 index 000000000000..f81fd333b8de --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportRouteSet.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.shenyu.plugin.agent.gateway.remote; + +import java.net.URI; +import java.util.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** Immutable deployment-owned routes; hostname targets fail closed until approved. */ +final class RemoteTransportRouteSet { + + private final Map routes; + + private RemoteTransportRouteSet(final Map routes) { + this.routes = Map.copyOf(routes); + } + + /** + * Parse endpoint=address route declarations. + * @param declarations deployment-owned declarations, never Admin plugin data + * @return immutable routes + */ + static RemoteTransportRouteSet parse(final Collection declarations) { + if (Objects.isNull(declarations)) { + throw new IllegalArgumentException("Missing controlled MCP routes"); + } + Map parsed = declarations.stream() + .map(RemoteTransportRouteSet::parseRoute) + .collect(Collectors.toUnmodifiableMap(RemoteTransportRoute::endpoint, route -> route)); + return new RemoteTransportRouteSet(parsed); + } + + private static RemoteTransportRoute parseRoute(final String declaration) { + if (Objects.isNull(declaration) || declaration.length() > 2048) { + throw new IllegalArgumentException("Invalid controlled MCP route"); + } + int separator = declaration.lastIndexOf('='); + if (separator < 1) { + throw new IllegalArgumentException("Invalid controlled MCP route"); + } + URI endpoint = URI.create(declaration.substring(0, separator)); + String address = declaration.substring(separator + 1); + if (isLiteralIpv4(endpoint.getHost())) { + if (!address.isEmpty()) { + throw new IllegalArgumentException("Fixed-IP route cannot override its endpoint address"); + } + return RemoteTransportRoute.fixed(endpoint); + } + if (address.isEmpty()) { + throw new IllegalArgumentException("Controlled hostname route requires an address"); + } + return RemoteTransportRoute.controlledDns(endpoint, address); + } + + private static boolean isLiteralIpv4(final String value) { + return Objects.nonNull(value) && value.matches("(?:0|[1-9][0-9]{0,2})(?:\\.(?:0|[1-9][0-9]{0,2})){3}"); + } + + Set endpoints() { + return routes.keySet(); + } + + RemoteTransportRoute route(final URI endpoint) { + RemoteTransportRoute route = routes.get(endpoint); + if (Objects.isNull(route) || !route.endpoint().equals(endpoint)) { + throw new SecurityException("Target has no approved transport route"); + } + return route; + } + + @Override + public String toString() { + return "RemoteTransportRouteSet[endpoints=" + routes.size() + "]"; + } +} diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java index e0d2201eddbc..d21578964f3e 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClient.java @@ -24,32 +24,29 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.modelcontextprotocol.common.McpTransportContext; import io.modelcontextprotocol.spec.McpSchema; +import org.apache.http.HttpRequest; +import org.apache.http.HttpHost; import org.apache.shenyu.common.tracing.AgentTraceContext; import reactor.core.publisher.Mono; import reactor.core.publisher.SignalType; -import reactor.core.publisher.Sinks; -import java.io.ByteArrayOutputStream; import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; +import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.CompletionStage; +import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Flow; +import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; @@ -71,7 +68,9 @@ public final class RequestScopedMcpClient implements RemoteMcpEndpoint { private static final int MAX_IN_FLIGHT = 64; - private final HttpClient http; + private final RemoteTransportRoute route; + + private final ApacheRemoteMcpTransport http; private final URI endpoint; @@ -87,7 +86,7 @@ public final class RequestScopedMcpClient implements RemoteMcpEndpoint { private final AtomicInteger active = new AtomicInteger(); - private final Set> inFlight = ConcurrentHashMap.newKeySet(); + private final Set> inFlight = ConcurrentHashMap.newKeySet(); private volatile String session; @@ -110,12 +109,16 @@ public RequestScopedMcpClient(final RemoteServerBinding binding, final java.util } RequestScopedMcpClient(final RemoteServerBinding binding, final java.util.function.Consumer> observer, final javax.net.ssl.SSLContext testContext) { - HttpClient.Builder builder = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).proxy(RemoteTransportPolicy.directOnly()) - .followRedirects(HttpClient.Redirect.NEVER).connectTimeout(Duration.ofSeconds(2)); - if (Objects.nonNull(testContext)) { - builder.sslContext(testContext); + this(binding, RemoteTransportRoute.fixed(binding.config().endpoint()), observer, testContext); + } + + RequestScopedMcpClient(final RemoteServerBinding binding, final RemoteTransportRoute route, + final java.util.function.Consumer> observer, final javax.net.ssl.SSLContext testContext) { + if (!binding.config().endpoint().equals(route.endpoint())) { + throw new SecurityException("Route does not match the credential binding"); } - http = builder.build(); + this.route = Objects.requireNonNull(route, "route"); + http = ApacheRemoteMcpTransport.create(route, testContext); this.endpoint = binding.config().endpoint(); this.name = binding.config().name(); this.authorization = binding.authorization(); @@ -215,28 +218,16 @@ private Mono request(final String method, final Object params, final if (requestBytes.length > MAX_REQUEST_BYTES) { return Mono.error(new IllegalArgumentException("Request byte limit")); } - HttpRequest.Builder builder = HttpRequest.newBuilder(endpoint) - .timeout(budget) - .header("Content-Type", "application/json") - .header("Accept", "application/json, text/event-stream") - .header("Authorization", authorization) - .header("MCP-Protocol-Version", VERSION) - .POST(HttpRequest.BodyPublishers.ofByteArray(requestBytes)); - if (Objects.nonNull(session) && !"initialize".equals(method)) { - builder.header("MCP-Session-Id", session); - } - // A shared handshake, directory refresh or session cleanup never belongs to an Agent call. - if ("tools/call".equals(method)) { - AgentTraceContext.headers(transportContext.get(AgentTraceContext.HEADERS_KEY)).forEach(builder::setHeader); - } - HttpRequest outbound = builder.build(); if (active.incrementAndGet() > MAX_IN_FLIGHT) { active.decrementAndGet(); return Mono.error(new IllegalStateException("Client concurrency limit")); } - var owned = new AtomicReference>>(); + var owned = new AtomicReference>(); return Mono.defer(() -> { - CompletableFuture> future = http.sendAsync(outbound, ignored -> new BoundedBody(LIMIT)); + ApacheRemoteMcpTransport.AsyncRequestHandle future = http.execute( + new HttpHost(route.endpoint().getHost(), route.endpoint().getPort(), route.endpoint().getScheme()), + outboundRequest(method, requestBytes, + AgentTraceContext.headers(transportContext.get(AgentTraceContext.HEADERS_KEY))), budget.toMillis()); owned.set(future); inFlight.add(future); if (closed) { @@ -245,9 +236,10 @@ private Mono request(final String method, final Object params, final return requestSignal(future); }) .timeout(budget) + .onErrorMap(SocketTimeoutException.class, error -> new TimeoutException(error.getMessage())) .map(response -> decodeResponse(response, method, id, notification)) .doFinally(ignored -> { - CompletableFuture future = owned.get(); + Future future = owned.get(); if (Objects.nonNull(future)) { future.cancel(true); inFlight.remove(future); @@ -257,22 +249,40 @@ private Mono request(final String method, final Object params, final }); } - private ObjectNode decodeResponse(final HttpResponse response, final String method, final String id, final boolean notification) { + private HttpRequest outboundRequest(final String method, final byte[] requestBytes, final Map traceHeaders) { + ApacheRemoteMcpTransport.ConfigurableRequest request = new ApacheRemoteMcpTransport.ConfigurableRequest(method, endpoint.getRawPath()); + request.setEntity(new org.apache.http.entity.ByteArrayEntity(requestBytes, org.apache.http.entity.ContentType.APPLICATION_JSON)); + request.setHeader("Host", endpoint.getHost() + ":" + endpoint.getPort()); + request.setHeader("Content-Type", "application/json"); + request.setHeader("Accept", "application/json, text/event-stream"); + request.setHeader("Authorization", authorization); + request.setHeader("MCP-Protocol-Version", VERSION); + if (Objects.nonNull(session) && !"initialize".equals(method)) { + request.setHeader("MCP-Session-Id", session); + } + // A shared handshake, directory refresh or session cleanup never belongs to an Agent call. + if ("tools/call".equals(method)) { + traceHeaders.forEach(request::setHeader); + } + return request; + } + + private ObjectNode decodeResponse(final ApacheRemoteHttpResponse response, final String method, final String id, final boolean notification) { observer.accept(Map.of("event", "http-response", "server", name, "method", method, "id", id, - "status", response.statusCode(), "contentType", response.headers().firstValue("Content-Type").orElse(""), "bytes", response.body().length)); - if (response.statusCode() < 200 || response.statusCode() >= 300) { - throw new IllegalStateException("Upstream HTTP " + response.statusCode()); + "status", response.status(), "contentType", header(response, "Content-Type"), "bytes", response.body().length)); + if (response.status() < 200 || response.status() >= 300) { + throw new IllegalStateException("Upstream HTTP " + response.status()); } if ("initialize".equals(method)) { - session = RemoteTransportPolicy.session(response.headers().allValues("MCP-Session-Id")); + session = RemoteTransportPolicy.session(response.headers().getOrDefault("mcp-session-id", List.of())); } if (notification) { - if (response.statusCode() != 202 || response.body().length != 0) { + if (response.status() != 202 || response.body().length != 0) { throw new IllegalArgumentException("Invalid notification acknowledgement"); } return JSON.createObjectNode(); } - String contentType = response.headers().firstValue("Content-Type").orElse("").split(";")[0].trim(); + String contentType = header(response, "Content-Type").split(";")[0].trim(); ObjectNode envelope = decode(response.body(), contentType); if (!"2.0".equals(envelope.path("jsonrpc").asText()) || !id.equals(envelope.path("id").asText())) { throw new IllegalArgumentException("Mismatched protocol response id"); @@ -286,6 +296,10 @@ private ObjectNode decodeResponse(final HttpResponse response, final Str return ((ObjectNode) envelope.get("result")).deepCopy(); } + private static String header(final ApacheRemoteHttpResponse response, final String name) { + return response.headers().getOrDefault(name.toLowerCase(Locale.ROOT), List.of()).stream().findFirst().orElse(""); + } + private static ObjectNode decode(final byte[] bytes, final String contentType) { try { String text = StandardCharsets.UTF_8.newDecoder() @@ -347,102 +361,43 @@ public Mono closeGracefully() { private Mono terminate() { closed = true; // Whole-client close is shutdown only, never the individual request cancellation path. - for (CompletableFuture future : inFlight) { + for (Future future : inFlight) { future.cancel(true); } if (Objects.isNull(session)) { - return Mono.empty(); + return Mono.fromRunnable(this::closeTransport); } - HttpRequest request = HttpRequest.newBuilder(endpoint) - .timeout(Duration.ofSeconds(2)) - .header("MCP-Session-Id", session) - .header("Authorization", authorization) - .header("MCP-Protocol-Version", VERSION) - .DELETE() - // Bound completion of the body as well as connection/response headers. Owned future is cancelled on timeout. - .build(); - return Mono.defer(() -> { - var future = http.sendAsync(request, HttpResponse.BodyHandlers.discarding()); - return requestSignal(future).doFinally(ignored -> future.cancel(true)); - }) + HttpRequest request = outboundRequest("DELETE", new byte[0], Map.of()); + return Mono.defer(() -> requestSignal(http.execute( + new HttpHost(route.endpoint().getHost(), route.endpoint().getPort(), route.endpoint().getScheme()), request, + Duration.ofSeconds(2).toMillis()))) .timeout(Duration.ofSeconds(2)) - .flatMap(response -> - response.statusCode() >= 200 && response.statusCode() < 300 + .flatMap(response -> response.status() >= 200 && response.status() < 300 ? Mono.empty() - : Mono.error(new IllegalStateException("Session cleanup HTTP " + response.statusCode())) - ); + : Mono.error(new IllegalStateException("Session cleanup HTTP " + response.status()))) + .doFinally(ignored -> closeTransport()); } - static Mono requestSignal(final CompletableFuture request) { - Sinks.One signal = Sinks.one(); - request.whenComplete((response, error) -> { - Throwable failure = error; - while (failure instanceof CompletionException && Objects.nonNull(failure.getCause())) { - failure = failure.getCause(); - } - if (Objects.nonNull(failure)) { - // Retain active errors, but a detached request has no subscriber to receive late failures. - signal.tryEmitError(failure); - } else { - signal.tryEmitValue(response); - } - }); - return signal.asMono().doFinally(type -> { - if (type == SignalType.CANCEL) { - request.cancel(true); - } - }); + static Mono requestSignal(final ApacheRemoteMcpTransport.AsyncRequestHandle request) { + return request.signal() + .onErrorMap(CompletionException.class, RequestScopedMcpClient::unwrapCompletionException) + .doFinally(type -> { + if (type == SignalType.CANCEL) { + request.cancel(true); + } + }); } - private static final class BoundedBody implements HttpResponse.BodySubscriber { - - private final int limit; - - private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - - private final CompletableFuture result = new CompletableFuture<>(); - - private Flow.Subscription subscription; - - private BoundedBody(final int limit) { - this.limit = limit; - } - - @Override - public CompletionStage getBody() { - return result; - } - - @Override - public void onSubscribe(final Flow.Subscription value) { - subscription = value; - value.request(1); - } - - @Override - public void onNext(final List parts) { - long incoming = parts.stream().mapToLong(ByteBuffer::remaining).sum(); - if (incoming > limit - bytes.size()) { - subscription.cancel(); - result.completeExceptionally(new IllegalArgumentException("Response byte limit")); - return; - } - for (ByteBuffer part : parts) { - byte[] chunk = new byte[part.remaining()]; - part.get(chunk); - bytes.writeBytes(chunk); - } - subscription.request(1); - } - - @Override - public void onError(final Throwable error) { - result.completeExceptionally(error); - } + private static Throwable unwrapCompletionException(final CompletionException error) { + return Objects.requireNonNullElseGet(error.getCause(), () -> error); + } - @Override - public void onComplete() { - result.complete(bytes.toByteArray()); + private void closeTransport() { + try { + http.close(); + } catch (Exception error) { + throw new IllegalStateException("Remote MCP transport cleanup failed", error); } } + } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/tool/AgentToolRegistry.java index 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/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java index 96835df22a18..c7371ba00f03 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcherTest.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.JsonObject; +import org.apache.shenyu.common.dto.AgentGatewayAdmissionConfig; import com.google.gson.JsonParser; import org.apache.shenyu.plugin.agent.gateway.AgentGatewayConstants; import org.apache.shenyu.plugin.agent.gateway.tool.AgentToolExecutionException; @@ -429,6 +430,29 @@ void shouldKeepDeclaredCapabilitiesRequestLocalAndSeparateFromAuthorization() { assertEquals(1, calls.get()); } + @Test + void shouldAdmitLocalToolOnlyAfterPreExecutionValidation() { + AtomicInteger admitted = new AtomicInteger(); + AgentMcpResourceAdmission.ResourceAdmissionController admission = AgentMcpResourceAdmission.create( + new AgentGatewayAdmissionConfig(1, 0, 1, 0, 1, 0)); + try { + AgentToolProvider invalid = provider("order_status", input -> { + throw new IllegalArgumentException("invalid private input"); + }, input -> { + admitted.incrementAndGet(); + return Mono.just(input.getArguments()); + }); + AgentMcpDispatcher dispatcher = new AgentMcpDispatcher(new AgentToolRegistry(List.of(invalid)), + "shenyu-agent-gateway", AgentGatewayConstants.MCP_SERVER_VERSION, null, admission); + StepVerifier.create(dispatcher.dispatch(request("tools/call", "1", "order_status"), () -> context("A", Set.of("order_status")))) + .assertNext(response -> assertTrue(response.path("result").path("isError").booleanValue())) + .verifyComplete(); + assertEquals(0, admitted.get()); + } finally { + admission.close(); + } + } + private AgentMcpExecutionContext context(final String subject, final Set grants) { return new AgentMcpExecutionContext("internal-" + subject, subject, "rule", 1, Set.of("order_status"), grants); } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/protocol/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..eebedcb31f4c 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 @@ -19,24 +19,33 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.net.httpserver.HttpServer; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; +import com.google.gson.JsonParser; import io.modelcontextprotocol.common.McpTransportContext; import org.apache.shenyu.common.dto.PluginData; import org.apache.shenyu.common.metrics.AgentRuntimeMetrics; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpRemoteCatalog; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.junit.jupiter.params.provider.MethodSource; import java.net.InetSocketAddress; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.time.Instant; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; @@ -44,12 +53,18 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class ManagedRemoteMcpCatalogTest { + @TempDir + private static Path certificates; + @ParameterizedTest(name = "{0}") @MethodSource("configurationFixtures") void validatesSharedContractBeforeCandidatePreparation(final String name, final boolean accepted, final String source) { @@ -85,7 +100,7 @@ private static java.util.stream.Stream { + ManagedRemoteMcpCatalog catalog = ManagedRemoteMcpCatalog.forRoutes(Set.of(), Set.of(), reference -> { throw new IllegalStateException("No credentials expected"); }); try { @@ -108,7 +123,7 @@ void catalogMetricsDescribeAcquisitionNotBusinessOutcome() { void newerFencedEventClearsOnlyTheSupersededFailureDiagnostic() throws Exception { CountDownLatch entered = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); - ManagedRemoteMcpCatalog catalog = new ManagedRemoteMcpCatalog(Set.of(URI.create("https://192.0.2.10:443/mcp")), Set.of(), target -> { + ManagedRemoteMcpCatalog catalog = ManagedRemoteMcpCatalog.forRoutes(Set.of("https://192.0.2.10:443/mcp="), Set.of(), target -> { entered.countDown(); try { assertTrue(release.await(10, TimeUnit.SECONDS)); @@ -129,7 +144,7 @@ void newerFencedEventClearsOnlyTheSupersededFailureDiagnostic() throws Exception assertTrue(catalog.diagnosticsState().revision() > resolvingRevision); assertEquals("", catalog.diagnosticsState().lastFailure()); release.countDown(); - await(() -> catalog.diagnosticsState().lifecycle().currentVersion() > 1L); + await(() -> catalog.diagnosticsState().lifecycle().currentVersion() == 0L); assertEquals("", catalog.diagnosticsState().lastFailure()); assertEquals(0, catalog.diagnosticsState().lifecycle().clients()); catalog.accept(event(true, "[]")); @@ -140,6 +155,160 @@ 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(); + } + } + + @Test + void credentialRotationPinsNewRequestsAndRetiresTheOldLeaseWithoutLeakingSecrets() throws Exception { + CountDownLatch firstCallEntered = new CountDownLatch(1); + CountDownLatch releaseFirstCall = new CountDownLatch(1); + List authorizations = new java.util.concurrent.CopyOnWriteArrayList<>(); + SSLContext context = tlsContext("rotation", "SAN=DNS:mcp.invalid"); + var server = rotationServer(context, firstCallEntered, releaseFirstCall, authorizations); + URI endpoint = URI.create("https://mcp.invalid:" + server.getAddress().getPort() + "/mcp"); + ManagedRemoteMcpCatalog catalog = ManagedRemoteMcpCatalog.forRoutesWithVerificationTlsContext( + Set.of(endpoint + "=127.0.0.1"), Set.of(), + target -> new RemoteServerBinding.Credential(target, "v2".equals(target.credentialVersion()) ? "v2-secret" : "v1-secret"), context); + try { + catalog.reload(rotationConfig("v1").replace("https://192.0.2.10:443/mcp", endpoint.toString())).block(Duration.ofSeconds(5)); + assertEquals(2L, catalog.diagnosticsState().lifecycle().currentVersion()); + final var first = catalog.withSnapshot(snapshot -> snapshot.invoke("orders.lookup", + JsonParser.parseString("{\"token\":\"first\"}").getAsJsonObject(), + new org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext("first-request", "subject", "rule", 1, + Set.of("orders.lookup"), Set.of("orders.lookup"), Instant.now().plusSeconds(10)))).toFuture(); + assertTrue(firstCallEntered.await(5, TimeUnit.SECONDS)); + + catalog.accept(event(true, rotationConfig("v2").replace("https://192.0.2.10:443/mcp", endpoint.toString()))); + await(() -> catalog.diagnosticsState().lifecycle().currentVersion() > 2L); + var second = catalog.withSnapshot(snapshot -> snapshot.invoke("orders.lookup", + JsonParser.parseString("{\"token\":\"second\"}").getAsJsonObject(), + new org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpExecutionContext("second-request", "subject", "rule", 2, + Set.of("orders.lookup"), Set.of("orders.lookup"), Instant.now().plusSeconds(10)))).block(Duration.ofSeconds(5)); + assertEquals("second", second.path("structuredContent").path("token").asText()); + assertEquals("Bearer v2-secret", authorizations.stream().filter(value -> value.endsWith("v2-secret")).findFirst().orElseThrow()); + + releaseFirstCall.countDown(); + assertEquals("first", first.get(5, TimeUnit.SECONDS).path("structuredContent").path("token").asText()); + await(() -> catalog.diagnosticsState().lifecycle().currentVersion() == 3L); + assertTrue(authorizations.stream().anyMatch(value -> "Bearer v1-secret".equals(value))); + + catalog.accept(event(false, "{}")); + await(() -> catalog.diagnosticsState().lifecycle().clients() == 0L); + StepVerifier.create(catalog.withSnapshot(snapshot -> Mono.just(new ObjectMapper().createObjectNode()))) + .expectError(AgentMcpRemoteCatalog.CatalogUnavailableException.class).verify(Duration.ofSeconds(5)); + String diagnostics = String.valueOf(catalog.diagnostics()); + assertTrue(!diagnostics.contains("v1-secret") && !diagnostics.contains("v2-secret")); + } finally { + releaseFirstCall.countDown(); + catalog.closeAsync().block(Duration.ofSeconds(5)); + server.stop(0); + } + } + + private static HttpServer rotationServer(final SSLContext context, final CountDownLatch firstCallEntered, + final CountDownLatch releaseFirstCall, final List authorizations) throws Exception { + HttpsServer server = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.setHttpsConfigurator(new HttpsConfigurator(context)); + server.createContext("/ready", exchange -> { + exchange.sendResponseHeaders(204, -1); + exchange.close(); + }); + server.createContext("/mcp", exchange -> { + try { + if ("DELETE".equals(exchange.getRequestMethod())) { + exchange.sendResponseHeaders(204, -1); + return; + } + var json = new ObjectMapper(); + var request = json.readTree(exchange.getRequestBody()); + String method = request.path("method").asText(); + if ("notifications/initialized".equals(method)) { + exchange.sendResponseHeaders(202, -1); + return; + } + if ("initialize".equals(method) || "tools/call".equals(method)) { + authorizations.add(exchange.getRequestHeaders().getFirst("Authorization")); + if (request.path("params").path("arguments").path("token").asText().equals("first")) { + firstCallEntered.countDown(); + try { + assertTrue(releaseFirstCall.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + } + } + } + var result = json.createObjectNode(); + if ("initialize".equals(method)) { + result.put("protocolVersion", "2025-06-18"); + result.putObject("capabilities").putObject("tools"); + result.putObject("serverInfo").put("name", "fixture").put("version", "1"); + } else if ("tools/list".equals(method)) { + var tool = result.putArray("tools").addObject(); + tool.put("name", "lookup").put("description", "Lookup"); + tool.putObject("inputSchema").put("type", "object"); + } else { + result.putObject("structuredContent").put("token", + request.path("params").path("arguments").path("token").asText()); + } + var envelope = json.createObjectNode().put("jsonrpc", "2.0"); + envelope.set("id", request.get("id")); + envelope.set("result", result); + byte[] bytes = json.writeValueAsBytes(envelope); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, bytes.length); + exchange.getResponseBody().write(bytes); + } finally { + exchange.close(); + } + }); + server.setExecutor(java.util.concurrent.Executors.newFixedThreadPool(4)); + server.start(); + return server; + } + + private static SSLContext tlsContext(final String name, final String extension) throws Exception { + Path file = certificates.resolve(name + ".p12"); + String keytool = Path.of(System.getProperty("java.home"), "bin", + System.getProperty("os.name").startsWith("Windows") ? "keytool.exe" : "keytool").toString(); + Process process = new ProcessBuilder(keytool, "-genkeypair", "-alias", "fixture", "-keyalg", "RSA", + "-keysize", "2048", "-validity", "2", "-dname", "CN=fixture", "-ext", extension, + "-storetype", "PKCS12", "-keystore", file.toString(), "-storepass", "changeit", "-noprompt") + .redirectErrorStream(true).redirectOutput(certificates.resolve(name + "-keytool.log").toFile()).start(); + assertTrue(process.waitFor(45, TimeUnit.SECONDS)); + assertEquals(0, process.exitValue()); + KeyStore store = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(file)) { + store.load(input, "changeit".toCharArray()); + } + KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keys.init(store, "changeit".toCharArray()); + TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trust.init(store); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keys.getKeyManagers(), trust.getTrustManagers(), null); + return context; + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void withdrawnDuringSuccessfulCredentialResolutionDoesNotStartRemoteHandshake(final boolean emptyConfiguration) throws Exception { @@ -187,7 +356,7 @@ void withdrawnDuringSuccessfulCredentialResolutionDoesNotStartRemoteHandshake(fi URI endpoint = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/mcp"); warmFixture(endpoint); handshakes.set(0); - ManagedRemoteMcpCatalog catalog = new ManagedRemoteMcpCatalog(Set.of(endpoint), Set.of(), target -> { + ManagedRemoteMcpCatalog catalog = ManagedRemoteMcpCatalog.forRoutes(Set.of(endpoint + "="), Set.of(), target -> { entered.countDown(); try { assertTrue(release.await(10, TimeUnit.SECONDS)); @@ -202,16 +371,16 @@ void withdrawnDuringSuccessfulCredentialResolutionDoesNotStartRemoteHandshake(fi assertTrue(entered.await(5, TimeUnit.SECONDS)); catalog.accept(event(emptyConfiguration, "{}")); release.countDown(); - await(() -> catalog.diagnosticsState().lifecycle().currentVersion() > 1L); + final long withdrawnVersion = emptyConfiguration ? 2L : 0L; + await(() -> catalog.diagnosticsState().lifecycle().currentVersion() == withdrawnVersion); assertEquals(0, handshakes.get(), "A superseded enable event must not allocate or initialize a remote client"); assertEquals(0, catalog.diagnosticsState().lifecycle().clients()); - long disabledVersion = catalog.diagnosticsState().lifecycle().currentVersion(); - catalog.accept(event(true, config().replace("https://192.0.2.10:443/mcp", endpoint.toString()))); - await(() -> catalog.diagnosticsState().lifecycle().currentVersion() > disabledVersion); - assertEquals(1, handshakes.get(), "A fresh explicit enable must still discover the remote directory"); - catalog.accept(event(false, "{}")); - await(() -> catalog.diagnosticsState().lifecycle().currentVersion() > disabledVersion + 1L); - assertEquals(0, catalog.diagnosticsState().lifecycle().clients()); + if (emptyConfiguration) { + catalog.accept(event(false, "{}")); + } + await(() -> catalog.diagnosticsState().lifecycle().currentVersion() == 0L + && catalog.diagnosticsState().lifecycle().clients() == 0 + && catalog.diagnosticsState().lifecycle().cleanupFailures().isEmpty()); } finally { release.countDown(); catalog.closeAsync().block(Duration.ofSeconds(5)); @@ -226,7 +395,7 @@ void resolvesCredentialsOnOwnedWorkerAndDropsSupersededEnableEvents() throws Exc final AtomicInteger resolutions = new AtomicInteger(); final AtomicBoolean workerThread = new AtomicBoolean(); URI endpoint = URI.create("https://192.0.2.10:443/mcp"); - final ManagedRemoteMcpCatalog catalog = new ManagedRemoteMcpCatalog(Set.of(endpoint), Set.of(), target -> { + final ManagedRemoteMcpCatalog catalog = ManagedRemoteMcpCatalog.forRoutes(Set.of(endpoint + "="), Set.of(), target -> { resolutions.incrementAndGet(); workerThread.set(Thread.currentThread().getName().startsWith("agent-mcp-config")); entered.countDown(); @@ -243,7 +412,7 @@ void resolvesCredentialsOnOwnedWorkerAndDropsSupersededEnableEvents() throws Exc catalog.accept(event(true, config())); catalog.accept(event(false, config())); release.countDown(); - await(() -> catalog.diagnosticsState().lifecycle().currentVersion() > 1L); + await(() -> catalog.diagnosticsState().lifecycle().generations() == 0); assertTrue(workerThread.get()); assertEquals(1, resolutions.get()); assertEquals(0, catalog.diagnosticsState().lifecycle().clients()); @@ -257,7 +426,7 @@ void resolvesCredentialsOnOwnedWorkerAndDropsSupersededEnableEvents() throws Exc void boundsQueueAndRequiresExplicitRefreshAfterOverflow() throws Exception { CountDownLatch entered = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); - final ManagedRemoteMcpCatalog catalog = new ManagedRemoteMcpCatalog(Set.of(URI.create("https://192.0.2.10:443/mcp")), Set.of(), target -> { + final ManagedRemoteMcpCatalog catalog = ManagedRemoteMcpCatalog.forRoutes(Set.of("https://192.0.2.10:443/mcp="), Set.of(), target -> { entered.countDown(); try { assertTrue(release.await(10, TimeUnit.SECONDS)); @@ -296,7 +465,8 @@ private static void warmFixture(final URI endpoint) throws Exception { assertEquals(204, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build() .send(ready, HttpResponse.BodyHandlers.discarding()).statusCode()); var reference = new RemoteServerBinding.Config("orders", endpoint, "service/orders", "v1"); - var warmup = RemoteServerBinding.resolve(reference, Set.of(endpoint), target -> new RemoteServerBinding.Credential(target, "fixed-test-token")).newClient(); + var warmup = RemoteServerBinding.resolve(reference, RemoteTransportRouteSet.parse(Set.of(endpoint + "=")), + target -> new RemoteServerBinding.Credential(target, "fixed-test-token")).newClient(); try { warmup.initialize().then(warmup.listTools(null)) .contextWrite(context -> context.put(McpTransportContext.KEY, @@ -319,6 +489,18 @@ private static String config() { + "\"credentialRef\":\"service/orders\",\"credentialVersion\":\"v1\"}]}}"; } + private static String rotationConfig(final String version) { + return "{\"aggregation\":{\"revision\":\"" + version + "\",\"servers\":[{\"name\":\"orders\"," + + "\"endpoint\":\"https://192.0.2.10:443/mcp\",\"credentialRef\":\"service/orders\"," + + "\"credentialVersion\":\"" + version + "\"}]}}"; + } + + 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..c8fe37479c87 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; @@ -107,7 +108,7 @@ void remoteResourcesStayOffForExistingToolsOnlyDeployments() throws Exception { void cancellingAnActualHttpReadDoesNotCancelItsPeer() throws Exception { try (Fixture fixture = new Fixture("orders", false)) { RemoteServerBinding.Config target = new RemoteServerBinding.Config("orders", fixture.endpoint(), "service", "v1"); - RequestScopedMcpClient client = RemoteServerBinding.resolve(target, Set.of(fixture.endpoint()), + RequestScopedMcpClient client = RemoteServerBinding.resolve(target, RemoteTransportRouteSet.parse(Set.of(fixture.endpoint() + "=")), reference -> new RemoteServerBinding.Credential(reference, "resources-test-service")).newClient(); try { client.initialize().block(WAIT); @@ -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/RemoteTransportPolicyTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicyTest.java index 7aa001d179cf..72bad0c9b885 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicyTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RemoteTransportPolicyTest.java @@ -34,29 +34,45 @@ class RemoteTransportPolicyTest { @ParameterizedTest - @ValueSource(strings = {"https://192.0.2.10:443/mcp", "https://10.1.2.3:8443/tools/mcp", "http://127.0.0.1:8080/mcp"}) + @ValueSource(strings = {"https://192.0.2.10:443/mcp", "https://10.1.2.3:8443/tools/mcp", "http://127.0.0.1:8080/mcp", "https://example.com:443/mcp"}) void acceptsOnlyUnambiguousFixedIpTargets(final String endpoint) { assertDoesNotThrow(() -> RemoteTransportPolicy.endpoint(URI.create(endpoint))); } @ParameterizedTest - @ValueSource(strings = {"https://example.com:443/mcp", "http://192.0.2.10:8080/mcp", "https://0.0.0.0:443/mcp", - "https://169.254.169.254:443/mcp", "https://224.1.2.3:443/mcp", "https://255.255.255.255:443/mcp", "https://256.1.2.3:443/mcp", "https://010.1.2.3:443/mcp", + @ValueSource(strings = {"http://example.com:443/mcp", "http://192.0.2.10:8080/mcp", "https://0.0.0.0:443/mcp", + "https://169.254.169.254:443/mcp", "https://224.1.2.3:443/mcp", "https://255.255.255.255:443/mcp", "https://256.1.2.3:443/mcp", "https://[::1]:443/mcp", "https://127.0.0.1/mcp", "https://user@127.0.0.1:443/mcp", "https://127.0.0.1:443/mcp?x=1", "https://127.0.0.1:443/a/../mcp", "https://127.0.0.1:443/%2e/mcp", "https://127.0.0.1:443//mcp"}) void rejectsDnsPlaintextRemoteAndAmbiguousAddresses(final String endpoint) { assertThrows(IllegalArgumentException.class, () -> RemoteTransportPolicy.endpoint(URI.create(endpoint))); } + @Test + void controlledHostnameRequiresAnApprovedRoute() { + final URI endpoint = URI.create("https://example.com:443/mcp"); + assertThrows(IllegalArgumentException.class, () -> RemoteTransportRouteSet.parse(Set.of("https://example.com:443/mcp"))); + assertThrows(IllegalArgumentException.class, () -> RemoteTransportRouteSet.parse(Set.of("https://192.0.2.10:443/mcp=203.0.113.10"))); + assertThrows(IllegalArgumentException.class, () -> RemoteTransportRouteSet.parse(Set.of("https://example.com:443/mcp=not-an-address"))); + RemoteTransportRoute first = RemoteTransportRouteSet.parse(Set.of(endpoint + "=203.0.113.10")).route(endpoint); + RemoteTransportRoute second = RemoteTransportRouteSet.parse(Set.of(endpoint + "=203.0.113.11")).route(endpoint); + assertEquals(first, first); + org.junit.jupiter.api.Assertions.assertNotEquals(first, second); + assertThrows(SecurityException.class, () -> RemoteTransportRouteSet.parse(Set.of("https://example.com:443/mcp=203.0.113.10")) + .route(URI.create("https://other.example:443/mcp"))); + } + @Test void neverUsesJvmProxyAndBindsCredentialToExactTarget() { URI endpoint = URI.create("https://192.0.2.10:443/mcp"); assertEquals(List.of(Proxy.NO_PROXY), RemoteTransportPolicy.directOnly().select(endpoint)); RemoteServerBinding.Config config = new RemoteServerBinding.Config("orders", endpoint, "service/orders", "v1"); RemoteServerBinding.Config other = new RemoteServerBinding.Config("orders", URI.create("https://192.0.2.10:443/other"), "service/orders", "v1"); - assertThrows(SecurityException.class, () -> RemoteServerBinding.resolve(config, Set.of(endpoint), ignored -> new RemoteServerBinding.Credential(other, "fake"))); - assertThrows(SecurityException.class, () -> RemoteServerBinding.resolve(config, Set.of(), ignored -> new RemoteServerBinding.Credential(config, "fake"))); - SecurityException error = assertThrows(SecurityException.class, () -> RemoteServerBinding.resolve(config, Set.of(endpoint), ignored -> { + RemoteTransportRouteSet routes = RemoteTransportRouteSet.parse(Set.of(endpoint + "=")); + assertThrows(SecurityException.class, () -> RemoteServerBinding.resolve(config, routes, ignored -> new RemoteServerBinding.Credential(other, "fake"))); + assertThrows(SecurityException.class, () -> RemoteServerBinding.resolve(config, RemoteTransportRouteSet.parse(Set.of("https://example.com:443/mcp=203.0.113.10")), + ignored -> new RemoteServerBinding.Credential(config, "fake"))); + SecurityException error = assertThrows(SecurityException.class, () -> RemoteServerBinding.resolve(config, routes, ignored -> { throw new IllegalStateException("SECRET"); })); assertEquals(null, error.getCause()); 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..4c311e1b1763 --- /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, RemoteTransportRouteSet.parse(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/remote/RequestScopedMcpClientTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientTest.java index 3cd82faf49ec..1f9b10e7b755 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpClientTest.java @@ -403,7 +403,7 @@ public boolean cancel(final boolean mayInterruptIfRunning) { }; Hooks.onErrorDropped(dropped::add); try { - Disposable subscription = RequestScopedMcpClient.requestSignal(future).subscribe(); + Disposable subscription = RequestScopedMcpClient.requestSignal(new ApacheRemoteMcpTransport.AsyncRequestHandle<>(future)).subscribe(); subscription.dispose(); assertTrue(cancelled.get()); future.completeExceptionally(new CompletionException(new HttpConnectTimeoutException("Controlled late failure"))); @@ -416,7 +416,7 @@ public boolean cancel(final boolean mayInterruptIfRunning) { @Test void activeConnectFailureStillReachesSubscriber() { CompletableFuture future = new CompletableFuture<>(); - Mono signal = RequestScopedMcpClient.requestSignal(future); + Mono signal = RequestScopedMcpClient.requestSignal(new ApacheRemoteMcpTransport.AsyncRequestHandle<>(future)); HttpConnectTimeoutException failure = new HttpConnectTimeoutException("Controlled active failure"); future.completeExceptionally(new CompletionException(failure)); StepVerifier.create(signal).expectErrorSatisfies(error -> assertSame(failure, error)).verify(WAIT); @@ -651,7 +651,7 @@ private RequestScopedMcpClient client() { private RequestScopedMcpClient client(final Consumer> observer) { URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/mcp"); RemoteServerBinding.Config target = new RemoteServerBinding.Config("orders", uri, "service/orders", "v1"); - return new RequestScopedMcpClient(RemoteServerBinding.resolve(target, Set.of(uri), + return new RequestScopedMcpClient(RemoteServerBinding.resolve(target, RemoteTransportRouteSet.parse(Set.of(uri + "=")), ignored -> new RemoteServerBinding.Credential(target, "fixed-test-token")), observer); } diff --git a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpTlsTest.java b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpTlsTest.java index ec84e26b9887..e81f48f06de0 100644 --- a/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpTlsTest.java +++ b/shenyu-plugin/shenyu-plugin-agent-gateway/src/test/java/org/apache/shenyu/plugin/agent/gateway/remote/RequestScopedMcpTlsTest.java @@ -74,6 +74,21 @@ void acceptsTrustedChainWithMatchingIpSan() throws Exception { } } + @Test + void acceptsControlledHostnameOnlyThroughItsApprovedAddress() throws Exception { + SSLContext context = certificate("dns", "SAN=DNS:mcp.invalid"); + try (Server server = new Server(context, "127.0.0.2")) { + URI endpoint = URI.create("https://mcp.invalid:" + server.server.getAddress().getPort() + "/mcp"); + RemoteServerBinding.Config config = new RemoteServerBinding.Config("orders", endpoint, "service/orders", "v1"); + RemoteTransportRouteSet routes = RemoteTransportRouteSet.parse(Set.of(endpoint + "=127.0.0.2")); + RequestScopedMcpClient client = RemoteServerBinding.resolve(config, routes, + ignored -> new RemoteServerBinding.Credential(config, "fake-tls-token")) + .newClient(routes.route(endpoint), context); + assertEquals("2025-06-18", client.initialize().block(Duration.ofSeconds(5)).protocolVersion()); + client.closeGracefully().block(Duration.ofSeconds(5)); + } + } + @Test void rejectsUntrustedCertificateWithDefaultTrust() throws Exception { try (Server server = new Server(validContext)) { @@ -118,7 +133,11 @@ private static final class Server implements AutoCloseable { private final HttpsServer server; private Server(final SSLContext context) throws Exception { - server = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + this(context, "127.0.0.1"); + } + + private Server(final SSLContext context, final String address) throws Exception { + server = HttpsServer.create(new InetSocketAddress(address, 0), 0); server.setHttpsConfigurator(new HttpsConfigurator(context)); server.createContext("/ready", exchange -> { exchange.sendResponseHeaders(204, -1); @@ -157,7 +176,8 @@ private Server(final SSLContext context) throws Exception { private RequestScopedMcpClient client(final SSLContext trustedContext) { URI endpoint = URI.create("https://127.0.0.1:" + server.getAddress().getPort() + "/mcp"); RemoteServerBinding.Config config = new RemoteServerBinding.Config("orders", endpoint, "service/orders", "v1"); - RemoteServerBinding binding = RemoteServerBinding.resolve(config, Set.of(endpoint), ignored -> new RemoteServerBinding.Credential(config, "fake-tls-token")); + RemoteServerBinding binding = RemoteServerBinding.resolve(config, RemoteTransportRouteSet.parse(Set.of(endpoint + "=")), + ignored -> new RemoteServerBinding.Credential(config, "fake-tls-token")); return new RequestScopedMcpClient(binding, ignored -> { }, trustedContext); } 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/AiProxyDownstreamDisconnectHttpTest.java b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyDownstreamDisconnectHttpTest.java index 4b572521d7ec..ed6dcfcb7519 100644 --- a/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyDownstreamDisconnectHttpTest.java +++ b/shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyDownstreamDisconnectHttpTest.java @@ -144,6 +144,7 @@ void writeFailureAfterCommitKeepsTheStrongEvidenceAndIsAnError() { try (Probe probe = new Probe(Flux.just(FIRST_CHUNK) .concatWith(Flux.error(new IllegalStateException("private upstream text"))))) { probe.consumeToleratingFailure(); + assertSingleObservation(probe); assertEquals(AiCallOutcome.ERROR, probe.terminal().outcome(), "a failed write is not a success"); assertEquals(AiCallOutcome.ERROR, probe.attempts().get(0).outcome(), "attempt outcome"); assertEquals("TRANSPORT_FAILURE", probe.attempts().get(0).completion().evidence().name(), 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/prometheus/AgentAdmissionMetricsCollector.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollector.java new file mode 100644 index 000000000000..03281af24dde --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollector.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.shenyu.plugin.metrics.prometheus; + +import io.prometheus.client.Collector; +import io.prometheus.client.GaugeMetricFamily; +import org.apache.shenyu.common.metrics.AgentAdmissionMetrics; + +import java.util.List; +import java.util.stream.Collectors; + +/** On-scrape admission state using bounded aggregate labels. */ +public final class AgentAdmissionMetricsCollector extends Collector implements Collector.Describable { + + @Override + public List collect() { + return samples(AgentAdmissionMetrics.snapshots()); + } + + @Override + public List describe() { + return samples(List.of()); + } + + private List samples(final List states) { + GaugeMetricFamily inFlight = new GaugeMetricFamily("shenyu_agent_admission_inflight", + "Admitted work by fixed scope", List.of("scope")); + GaugeMetricFamily queued = new GaugeMetricFamily("shenyu_agent_admission_queued", + "Queued work by fixed scope", List.of("scope")); + GaugeMetricFamily inFlightLimit = new GaugeMetricFamily("shenyu_agent_admission_inflight_limit", + "Configured in-flight limit by fixed scope", List.of("scope")); + GaugeMetricFamily queueLimit = new GaugeMetricFamily("shenyu_agent_admission_queue_limit", + "Configured queue limit by fixed scope", List.of("scope")); + GaugeMetricFamily rejected = new GaugeMetricFamily("shenyu_agent_admission_rejections_total", + "Explicit admission rejections by fixed scope", List.of("scope")); + for (AgentAdmissionMetrics.Scope scope : AgentAdmissionMetrics.Scope.values()) { + List scoped = states.stream() + .filter(state -> state.scope() == scope).collect(Collectors.toList()); + inFlight.addMetric(label(scope), sum(scoped, AgentAdmissionMetrics.Snapshot::inFlight)); + queued.addMetric(label(scope), sum(scoped, AgentAdmissionMetrics.Snapshot::queued)); + inFlightLimit.addMetric(label(scope), sum(scoped, AgentAdmissionMetrics.Snapshot::inFlightLimit)); + queueLimit.addMetric(label(scope), sum(scoped, AgentAdmissionMetrics.Snapshot::queueLimit)); + rejected.addMetric(label(scope), states.stream().filter(state -> state.scope() == scope) + .mapToLong(AgentAdmissionMetrics.Snapshot::rejected).sum()); + } + return List.of(inFlight, queued, inFlightLimit, queueLimit, rejected); + } + + private long sum(final List states, + final java.util.function.ToIntFunction value) { + return states.stream().mapToLong(value::applyAsInt).sum(); + } + + private List label(final AgentAdmissionMetrics.Scope scope) { + return List.of(scope.name().toLowerCase(java.util.Locale.ROOT)); + } +} diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java index fbe9bf7db1ba..45e8bc91c968 100644 --- a/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java +++ b/shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/prometheus/PrometheusMetricsService.java @@ -103,6 +103,7 @@ private void register(final MetricsConfig config) { } new LoggingQueueMetricsCollector().register(); new AgentCatalogMetricsCollector().register(); + new AgentAdmissionMetricsCollector().register(); String jvmEnabled = String.valueOf(config.getProps().getProperty("jvm_enabled")); if (StringUtils.isNotEmpty(jvmEnabled)) { boolean enabled = Boolean.parseBoolean(jvmEnabled); diff --git a/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollectorTest.java b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollectorTest.java new file mode 100644 index 000000000000..66865b8f4e5f --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-metrics/src/test/java/org/apache/shenyu/plugin/metrics/prometheus/AgentAdmissionMetricsCollectorTest.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.shenyu.plugin.metrics.prometheus; + +import org.apache.shenyu.common.metrics.AgentAdmissionMetrics; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AgentAdmissionMetricsCollectorTest { + + @Test + void shouldAggregateFixedScopesWithoutIdentityLabels() { + AgentAdmissionMetrics.Snapshot snapshot = new AgentAdmissionMetrics.Snapshot( + AgentAdmissionMetrics.Scope.REMOTE, 2, 3, 4, 5, 6); + List names = new AgentAdmissionMetricsCollector().collect().stream() + .map(family -> family.samples.stream().map(sample -> sample.name).toList()).flatMap(List::stream).toList(); + assertEquals(15, names.size()); + assertEquals(5, names.stream().filter(name -> name.startsWith("shenyu_agent_admission_")).distinct().count()); + } +} diff --git a/shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/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..5ce847819792 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,6 +20,8 @@ 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.AiCallObserver; import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpCallTracer; @@ -29,6 +31,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; @@ -49,7 +52,6 @@ import org.apache.shenyu.plugin.agent.gateway.remote.ManagedRemoteMcpCatalog; import org.apache.shenyu.plugin.agent.gateway.remote.RemoteServiceCredentialResolver; import org.apache.shenyu.plugin.agent.gateway.remote.FileRemoteServiceCredentialResolver; -import java.net.URI; import java.nio.file.Path; import java.util.Arrays; import java.util.List; @@ -77,6 +79,7 @@ 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 * @return the plugin @@ -85,6 +88,7 @@ public class AgentGatewayPluginConfiguration { 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, @@ -109,7 +113,7 @@ public ShenyuPlugin agentGatewayPlugin(final ObjectProvider p && !beanFactory.containsBean(JWT_SECURITY_RESOLVER_BEAN_NAME)) { throw new IllegalStateException("Enabled MCP JWT identity requires the optional JWT adapter dependencies"); } - return createPlugin(providers, authorities, catalogs.getIfAvailable(), tracer, 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)); @@ -117,16 +121,22 @@ public ShenyuPlugin agentGatewayPlugin(final ObjectProvider p 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) { 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); + return new AgentGatewayPlugin(new AgentMcpHttpHandler(dispatcher, resolver, tracer, terminalObserver), llmIdentityEnabled ? resolver : null, aiObserver); } @@ -134,12 +144,47 @@ private ShenyuPlugin createPlugin(final ObjectProvider provid * 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,21 +192,36 @@ public PluginDataHandler agentGatewayPluginDataHandler(final ObjectProvider tools, - final ObjectProvider credentials) { - 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()); + final ObjectProvider credentials, + final AgentMcpResourceAdmission.ResourceAdmissionController admission) { + String fixedEndpoints = environment.getProperty("shenyu.plugins.agent.gateway.aggregation.allowed-endpoints", ""); + String controlledRoutes = environment.getProperty("shenyu.plugins.agent.gateway.aggregation.allowed-routes", ""); + Set allowed = java.util.stream.Stream.concat( + declarations(fixedEndpoints, true), declarations(controlledRoutes, false)) + .collect(Collectors.toUnmodifiableSet()); + if (allowed.isEmpty()) { + throw new IllegalStateException("Agent Gateway aggregation requires an approved transport route"); + } 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 ManagedRemoteMcpCatalog.forRoutes(allowed, tools.orderedStream().map(AgentToolProvider::getName).collect(Collectors.toUnmodifiableSet()), resolver, admission, environment.getProperty("shenyu.plugins.agent.gateway.aggregation.resources-enabled", Boolean.class, false)); } + private static java.util.stream.Stream declarations(final String value, final boolean fixedEndpoints) { + return Arrays.stream(value.split(",")) + .map(String::trim) + .filter(candidate -> !candidate.isBlank()) + .map(candidate -> fixedEndpoints ? candidate + "=" : candidate); + } + private static Mono keyAuthenticationPresent(final org.springframework.web.server.ServerWebExchange exchange) { if (org.springframework.util.ClassUtils.isPresent("org.apache.shenyu.plugin.key.auth.KeyAuthAuthentication", AgentGatewayPluginConfiguration.class.getClassLoader())) { return org.apache.shenyu.plugin.key.auth.KeyAuthAuthentication.from(exchange).hasElement(); 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..b502e2a7e5e3 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 @@ -32,28 +32,43 @@ 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.AgentMcpDispatcher; +import org.apache.shenyu.plugin.agent.gateway.protocol.AgentMcpResourceAdmission; +import org.apache.shenyu.plugin.agent.gateway.remote.ManagedRemoteMcpCatalog; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.shenyu.plugin.api.ShenyuPlugin; import org.apache.shenyu.plugin.base.handler.PluginDataHandler; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.test.util.ReflectionTestUtils; import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; import reactor.test.StepVerifier; 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 { @@ -242,6 +257,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") @@ -267,7 +414,7 @@ void primaryMustNotHideConflictingIdentityAuthorities() { @Test void shouldAssembleOptInCatalogAndWireTrustedPluginSync() { contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.gateway.aggregation.enabled=true", - "shenyu.plugins.agent.gateway.aggregation.allowed-endpoints=https://192.0.2.10:443/mcp") + "shenyu.plugins.agent.gateway.aggregation.allowed-routes=https://192.0.2.10:443/mcp=") .withBean(org.apache.shenyu.plugin.agent.gateway.remote.RemoteServiceCredentialResolver.class, () -> reference -> { throw new SecurityException("Missing fixture credentials"); }).run(context -> { @@ -281,10 +428,22 @@ void shouldAssembleOptInCatalogAndWireTrustedPluginSync() { }); } + @Test + void fixedEndpointPropertyRemainsCompatible() { + contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.gateway.aggregation.enabled=true", + "shenyu.plugins.agent.gateway.aggregation.allowed-endpoints=https://192.0.2.10:443/mcp") + .withBean(org.apache.shenyu.plugin.agent.gateway.remote.RemoteServiceCredentialResolver.class, () -> reference -> { + throw new SecurityException("Missing fixture credentials"); + }).run(context -> { + assertTrue(context.containsBean("agentGatewayRemoteCatalog")); + context.getBean(org.apache.shenyu.plugin.agent.gateway.remote.ManagedRemoteMcpCatalog.class).close(); + }); + } + @Test void shouldRejectDomainAllowlistWithoutRelaxingTlsPolicy() { contextRunner.withPropertyValues("shenyu.plugins.agent.gateway.enabled=true", "shenyu.plugins.agent.gateway.aggregation.enabled=true", - "shenyu.plugins.agent.gateway.aggregation.allowed-endpoints=https://example.com:443/mcp") + "shenyu.plugins.agent.gateway.aggregation.allowed-routes=https://example.com:443/mcp") .withBean(org.apache.shenyu.plugin.agent.gateway.remote.RemoteServiceCredentialResolver.class, () -> reference -> { throw new SecurityException("unused"); }).run(context -> assertNotNull(context.getStartupFailure())); 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,