Croway commented on code in PR #9509:
URL: https://github.com/apache/camel-quarkus/pull/9509#discussion_r4705886579


##########
integration-tests/mcp-server/src/test/java/org/apache/camel/quarkus/component/mcp/server/it/McpServerOAuthTest.java:
##########
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.quarkus.component.mcp.server.it;
+
+import java.net.URI;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import io.quarkiverse.mcp.server.TextContent;
+import io.quarkiverse.mcp.server.ToolResponse;
+import io.quarkiverse.mcp.server.test.McpAssured;
+import io.quarkiverse.mcp.server.test.McpAssured.McpStreamableTestClient;
+import io.quarkus.test.common.QuarkusTestResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.RestAssured;
+import org.eclipse.microprofile.config.ConfigProvider;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Exercises a real Keycloak/OIDC identity through MCP and into a Camel tool 
route. */
+@QuarkusTest
+@QuarkusTestResource(value = McpServerKeycloakTestResource.class, 
restrictToAnnotatedClass = true)
+class McpServerOAuthTest {
+
+    private static final String INITIALIZE_REQUEST = 
"{\"jsonrpc\":\"2.0\",\"id\":1,"
+            + 
"\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\","
+            + 
"\"capabilities\":{},\"clientInfo\":{\"name\":\"camel-quarkus-keycloak-test\",\"version\":\"1\"}}}";
+
+    @Test
+    void anonymousMcpRequestIsRejected() {
+        postInitialize(null, 401, false);
+    }
+
+    @Test
+    void invalidBearerTokenIsRejected() {
+        postInitialize("not-a-valid-keycloak-token", 401, false);
+    }
+
+    @Test
+    void protectedResourceMetadataIsPublished() {
+        String issuer = keycloakIssuer();
+        String metadata = 
RestAssured.get("/.well-known/oauth-protected-resource")
+                .then()
+                .statusCode(200)
+                .extract()
+                .asString();
+        
assertThat(metadata).contains("authorization_servers").contains(issuer);
+    }
+
+    // This exercises quarkus-mcp-server's loopback DNS-rebinding check, not a 
general Origin allow-list.
+    @Test
+    void untrustedOriginIsRejectedEvenWithValidBearerToken() {
+        postInitialize(accessToken(), 403, true);
+    }
+
+    @Test
+    void validKeycloakBearerTokenPropagatesIdentityIntoCamelTool() {
+        String token = accessToken();
+        int port = 
ConfigProvider.getConfig().getValue("quarkus.http.test-port", Integer.class);
+        McpStreamableTestClient client = McpAssured.newStreamableClient()
+                .setBaseUri(URI.create("http://localhost:%d".formatted(port)))
+                .setBearerToken(token)
+                .build()
+                .connect();
+
+        try {
+            client.when()
+                    .toolsCall("whoami", Map.of(), response -> {
+                        String content = textOf(response);
+                        
assertThat(content).startsWith("alice|alice|").contains("mcp-operator");
+                    })
+                    .toolsCall("whooauth", Map.of(), response -> {
+                        String[] context = textOf(response).split("\\|", -1);
+                        assertThat(context).hasSize(5);
+                        assertThat(context[0]).isNotBlank();
+                        
assertThat(context[1]).contains("profile").doesNotContain("\"");
+                        assertThat(context[2]).isEqualTo("alice");
+                        assertThat(context[3]).isEqualTo("false"); // 
raw_token must not enter exchange properties
+                        assertThat(context[4]).isEqualTo("true"); // JSON-P 
realm_access is exposed as a Java Map
+                    })
+                    .thenAssertResults();
+        } finally {
+            client.disconnect();
+        }
+    }
+
+    private static String keycloakIssuer() {
+        String issuer = 
System.getProperty(McpServerKeycloakTestResource.ISSUER_PROPERTY);
+        if (issuer == null || issuer.isBlank()) {
+            throw new IllegalStateException("Keycloak issuer system property 
was not set by the test resource");
+        }
+        return issuer;
+    }
+
+    private static String accessToken() {
+        String issuer = keycloakIssuer();
+        return RestAssured.given()
+                .contentType("application/x-www-form-urlencoded")
+                .formParam("grant_type", "password")
+                .formParam("client_id", "mcp-test-client")
+                .formParam("client_secret", "mcp-test-secret")
+                .formParam("username", "alice")
+                .formParam("password", "alice-password")
+                .post(issuer + "/protocol/openid-connect/token")
+                .then()
+                .statusCode(200)
+                .extract()
+                .path("access_token");
+    }
+
+    private static void postInitialize(String token, int expectedStatus, 
boolean untrustedOrigin) {
+        var request = RestAssured.given()
+                .header("Accept", "application/json, text/event-stream")
+                .contentType("application/json")
+                .body(INITIALIZE_REQUEST);
+        if (token != null) {
+            request.header("Authorization", "Bearer " + token);
+        }
+        if (untrustedOrigin) {
+            // Keep Host bound to the real localhost destination; only Origin 
is hostile.
+            request.header("Origin", "http://evil.example.com";);
+        }
+        var response = request.post("/mcp");
+        assertThat(response.statusCode()).isEqualTo(expectedStatus);
+        if (untrustedOrigin) {
+            // With CORS disabled for this module, this message proves the MCP 
server's
+            // loopback DNS-rebinding check (rather than Quarkus CORS) 
rejected the request.
+            assertThat(response.asString() + " " + 
response.getStatusLine()).contains("Invalid origin");

Review Comment:
   **This assertion also passes when CORS rejects the request.** Both filters 
answer 403 with an empty body and put the reason in the status message. 
quarkus-mcp-server's `HttpMcpServerRecorder` sets `Invalid origin`, and Quarkus 
4.0.0's `CORSFilter` sets `CORS Rejected - Invalid origin`. So 
`contains("Invalid origin")` is true for both, and the test would stay green if 
CORS were turned on again in this module. Checking the whole status line tells 
them apart:
   
   ```java
   assertThat(response.getStatusLine()).endsWith(" 403 Invalid origin");
   ```
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



##########
extensions/mcp-server/runtime/src/main/java/org/apache/camel/quarkus/component/mcp/server/QuarkusMcpServerEngine.java:
##########
@@ -191,6 +395,565 @@ public boolean supportsResources() {
         return true;
     }
 
+    @Override
+    public void resourceTemplateAdded(McpServerResourceTemplate 
resourceTemplate) {
+        AiResourceUriTemplate matcher;
+        try {
+            matcher = new 
AiResourceUriTemplate(resourceTemplate.uriTemplate());
+            validateQuarkusResourceTemplate(resourceTemplate.uriTemplate());
+        } catch (IllegalArgumentException e) {
+            throw new McpServerRefusedException(
+                    "Unsupported MCP resource template '" + 
resourceTemplate.uriTemplate() + "': " + e.getMessage(),
+                    e);
+        }
+
+        // Retry cleanup if a previous route stop failed to remove this 
template.
+        try {
+            removeRegisteredResourceTemplate(resourceTemplate.uriTemplate());
+        } catch (Exception e) {
+            throw new McpServerRefusedException(
+                    "Previously registered MCP resource template '" + 
resourceTemplate.uriTemplate()
+                            + "' could not be removed before re-registration",
+                    e);
+        }
+
+        // Multiple matching templates make resource reads ambiguous in 
quarkus-mcp-server.
+        // Definitions on other MCP servers are independent and must remain 
untouched.
+        for (ResourceTemplateManager.ResourceTemplateInfo existing : 
resourceTemplateManager) {
+            if (!existing.serverNames().contains(McpServer.DEFAULT)) {
+                continue;
+            }
+            // A native Quarkus template may use regex syntax in its authority 
or path that Camel's
+            // literal matcher cannot model. Fail closed when its authority 
expression can match
+            // this Camel template, even when the authority strings differ.
+            boolean pathRegexWithSameAuthority = 
hasQuarkusRegexSyntaxInPath(existing.uriTemplate())
+                    && uriAuthority(resourceTemplate.uriTemplate())
+                            .equals(uriAuthority(existing.uriTemplate()));
+            if (quarkusAuthorityMayOverlap(existing.uriTemplate(), 
resourceTemplate.uriTemplate())
+                    || pathRegexWithSameAuthority) {
+                throw new McpServerRefusedException(
+                        "Resource template '" + resourceTemplate.uriTemplate()
+                                + "' cannot be checked safely against 
application template '"
+                                + existing.uriTemplate()
+                                + "' because its URI authority or path uses 
regex syntax that Camel cannot model");
+            }
+            if (templatesOverlap(matcher, existing.uriTemplate())) {
+                throw new McpServerRefusedException(
+                        "Resource template '" + resourceTemplate.uriTemplate()
+                                + "' overlaps resource template '"
+                                + existing.uriTemplate() + "'");
+            }
+        }
+
+        ResourceTemplateManager.ResourceTemplateDefinition definition = 
resourceTemplateManager
+                .newResourceTemplate(resourceTemplate.name())
+                .setUriTemplate(resourceTemplate.uriTemplate())
+                .setMimeType(resourceTemplate.mimeType())
+                .setDescription(resourceTemplate.description());
+        if (resourceTemplate.title() != null && 
!resourceTemplate.title().isBlank()) {
+            definition.setTitle(resourceTemplate.title());
+        }
+        definition.setHandler(arguments -> {
+            String requestedUri = arguments.requestUri().value();
+            if (matcher.match(requestedUri).isEmpty()) {
+                // quarkus-mcp-server's regex accepts some URIs outside 
Camel's RFC 6570
+                // path-segment matcher (for example, a query suffix on the 
final segment).
+                throw new McpException("Resource URI does not match the 
registered template",
+                        JsonRpcErrorCodes.RESOURCE_NOT_FOUND);
+            }
+            McpResourceReadResult result = 
resourceTemplate.handler().read(requestedUri);
+            if (result.isError()) {
+                throw new McpException(result.errorMessage(), 
JsonRpcErrorCodes.INTERNAL_ERROR);
+            }
+            // Keep Base64 unwrapped: BlobResourceContents.create(String, 
byte[]) inserts MIME line breaks.
+            ResourceContents contents = result.blob() != null
+                    ? new BlobResourceContents(requestedUri, 
Base64.getEncoder().encodeToString(result.blob()),
+                            resourceTemplate.mimeType())
+                    : new TextResourceContents(requestedUri, result.text(), 
resourceTemplate.mimeType());
+            return new ResourceResponse(List.of(contents));
+        });
+        try {
+            definition.register();
+        } catch (IllegalArgumentException e) {
+            throw new McpServerRefusedException(
+                    "Resource template '" + resourceTemplate.uriTemplate() + 
"' could not be registered: "
+                            + e.getMessage(),
+                    e);
+        }
+        registeredResourceTemplates.put(resourceTemplate.uriTemplate(), 
resourceTemplate.name());
+        LOG.debug("MCP resource template added: {}", 
resourceTemplate.uriTemplate());
+    }
+
+    @Override
+    public void resourceTemplateRemoved(String uriTemplate) {
+        try {
+            removeRegisteredResourceTemplate(uriTemplate);
+            LOG.debug("MCP resource template removed: {}", uriTemplate);
+        } catch (Exception e) {
+            // Keep the ownership entry so a later route start can retry the 
removal.
+            LOG.warn(
+                    "Failed to remove MCP resource template {}; ownership 
retained for retry",
+                    uriTemplate, e);
+        }
+    }
+
+    private void removeRegisteredResourceTemplate(String uriTemplate) throws 
Exception {
+        String name = registeredResourceTemplates.get(uriTemplate);
+        if (name == null) {
+            // Refused templates are not owned by this engine.
+            return;
+        }
+
+        resourceTemplateManager.removeResourceTemplate(name, 
McpServer.DEFAULT);
+        registeredResourceTemplates.remove(uriTemplate, name);
+    }
+
+    @Override
+    public boolean supportsResourceTemplates() {
+        return true;
+    }
+
+    private static boolean hasQuarkusRegexSyntaxInPath(String uriTemplate) {
+        int colon = uriTemplate.indexOf(':');
+        if (colon <= 0) {
+            return true;
+        }
+        int pathStart = uriTemplate.startsWith("//", colon + 1)
+                ? uriTemplate.indexOf('/', colon + 3)
+                : uriTemplate.indexOf('/', colon + 1);
+        // A native query-parameter template without a path (e.g. 
crm://search?q={term})
+        // cannot overlap a Camel path template and must not block unrelated 
registrations.
+        if (pathStart < 0) {
+            return false;
+        }
+        String path = uriTemplate.substring(pathStart + 1);
+        int queryStart = path.indexOf('?');
+        if (queryStart >= 0) {
+            path = path.substring(0, queryStart);
+        }
+        for (int index = 0; index < path.length();) {
+            char current = path.charAt(index);
+            if (current == '{') {
+                int end = path.indexOf('}', index + 1);
+                if (end < 0 || 
!isQuarkusTemplateVariableName(path.substring(index + 1, end))) {
+                    return true;
+                }
+                index = end + 1;
+            } else if (current == '}' || 
QUARKUS_TEMPLATE_REGEX_METACHARACTERS.indexOf(current) >= 0) {
+                return true;
+            } else {
+                index++;
+            }
+        }
+        return false;
+    }
+
+    private static String uriAuthority(String uriTemplate) {
+        int colon = uriTemplate.indexOf(':');
+        if (colon <= 0) {
+            return uriTemplate;
+        }
+
+        int authorityStart = uriTemplate.startsWith("//", colon + 1)
+                ? colon + 3
+                : colon + 1;
+
+        int authorityEnd = uriTemplate.length();
+        int pathStart = uriTemplate.indexOf('/', authorityStart);
+        int queryStart = uriTemplate.indexOf('?', authorityStart);
+        int fragmentStart = uriTemplate.indexOf('#', authorityStart);
+
+        if (pathStart >= 0) {
+            authorityEnd = Math.min(authorityEnd, pathStart);
+        }
+        if (queryStart >= 0) {
+            authorityEnd = Math.min(authorityEnd, queryStart);
+        }
+        if (fragmentStart >= 0) {
+            authorityEnd = Math.min(authorityEnd, fragmentStart);
+        }
+
+        return uriTemplate.substring(0, authorityEnd);
+    }
+
+    private static String uriScheme(String uriTemplate) {
+        int colon = uriTemplate.indexOf(':');
+        return colon > 0 ? uriTemplate.substring(0, colon) : "";
+    }
+
+    /**
+     * Checks whether an application-defined Quarkus authority pattern can 
match
+     * a Camel authority. Quarkus treats literal regex metacharacters as regex
+     * syntax, while Camel treats them literally.
+     */
+    private static boolean quarkusAuthorityMayOverlap(
+            String applicationTemplate, String camelTemplate) {
+        String applicationAuthority = uriAuthority(applicationTemplate);
+        String camelAuthority = uriAuthority(camelTemplate);
+
+        if (!uriScheme(applicationTemplate).equals(uriScheme(camelTemplate))) {
+            return false;
+        }
+
+        // A Camel authority variable can match an application authority even 
when
+        // their literal strings differ. Fail closed rather than trying to 
intersect
+        // two URI-template patterns.
+        if (camelAuthority.indexOf('{') >= 0) {
+            return true;
+        }
+
+        if (!hasQuarkusRegexSyntaxInAuthority(applicationTemplate)) {
+            return false;
+        }
+
+        try {
+            return 
camelAuthority.matches(toQuarkusRegex(applicationAuthority));
+        } catch (IllegalArgumentException e) {
+            // If the application authority pattern cannot be parsed here, fail
+            // closed rather than risk registering an ambiguous Camel template.
+            return true;
+        }
+    }
+
+    private static boolean hasQuarkusRegexSyntaxInAuthority(String 
uriTemplate) {
+        int colon = uriTemplate.indexOf(':');
+        if (colon <= 0) {
+            return true;
+        }
+
+        int authorityStart = uriTemplate.startsWith("//", colon + 1)
+                ? colon + 3
+                : colon + 1;
+
+        String authority = uriAuthority(uriTemplate);
+        if (authorityStart >= authority.length()) {
+            return false;
+        }
+
+        for (int index = authorityStart; index < authority.length(); index++) {
+            char current = authority.charAt(index);
+            if (current == '{' || current == '}'
+                    || QUARKUS_TEMPLATE_REGEX_METACHARACTERS.indexOf(current) 
>= 0) {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * Preserves Quarkus' raw regex syntax and converts URI-template variables
+     * to a non-slash expression for authority matching.
+     */
+    private static String toQuarkusRegex(String uriAuthority) {
+        StringBuilder regex = new StringBuilder();
+
+        for (int index = 0; index < uriAuthority.length();) {
+            char current = uriAuthority.charAt(index);
+
+            if (current == '{') {
+                int end = uriAuthority.indexOf('}', index + 1);
+                if (end < 0
+                        || !isQuarkusTemplateVariableName(
+                                uriAuthority.substring(index + 1, end))) {
+                    throw new IllegalArgumentException("Invalid URI-template 
variable in authority");
+                }
+
+                regex.append("[^/]+");
+                index = end + 1;
+                continue;
+            }
+
+            if (current == '}') {
+                throw new IllegalArgumentException("Unmatched closing brace in 
authority");
+            }
+
+            // Deliberately do not quote regex metacharacters. The Quarkiverse
+            // matcher interprets these characters as regular-expression 
syntax.
+            regex.append(current);
+            index++;
+        }
+
+        return regex.toString();
+    }
+
+    /*
+     * Quarkiverse MCP Server compiles the literal parts of a URI template as 
raw
+     * regular expressions and replaces only {\w+} variables. Reject syntax 
that
+     * Camel accepts but the Quarkus matcher would interpret differently.
+     */
+    private static void validateQuarkusResourceTemplate(String uriTemplate) {
+        int index = 0;
+        boolean hasVariable = false;
+        while (index < uriTemplate.length()) {
+            char current = uriTemplate.charAt(index);
+            if (current == '{') {
+                int end = uriTemplate.indexOf('}', index + 1);
+                if (end < 0) {
+                    throw new IllegalArgumentException("unclosed URI-template 
variable");
+                }
+                String variable = uriTemplate.substring(index + 1, end);
+                if (!isQuarkusTemplateVariableName(variable)) {
+                    throw new IllegalArgumentException(
+                            "variable names must contain only ASCII letters, 
digits or underscore (\\w+)");
+                }
+                hasVariable = true;
+                index = end + 1;
+                continue;
+            }
+            if (current == '}') {
+                throw new IllegalArgumentException("unmatched closing brace in 
URI template");
+            }
+            if (QUARKUS_TEMPLATE_REGEX_METACHARACTERS.indexOf(current) >= 0) {

Review Comment:
   **Refusing every regex metacharacter also refuses `.`, which most URIs 
contain.** This follows my round-2 suggestion, but I hadn't weighed how common 
dots are. I ran `validateQuarkusResourceTemplate` from this commit as-is, next 
to Camel's `AiResourceUriTemplate`:
   
   ```
   crm://api.example.com/customers/{id}   Camel Main: accepted | ed222bd3d8: 
refused (literal character '.' is a regular-expression metacharacter ...)
   docs://manual/v4.24/{page}             Camel Main: accepted | ed222bd3d8: 
refused
   file:///data/reports.d/{name}          Camel Main: accepted | ed222bd3d8: 
refused
   crm://customers/{id}                   Camel Main: accepted | ed222bd3d8: 
accepted
   ```
   
   So a host name or a version number in the template is enough to have the 
route refused on Quarkus only. With the new read-time check, a looser 
quarkus-mcp-server match no longer reaches the route. For `.`, the remaining 
risk is two templates matching the same URI.
   
   The clean fix is upstream. 
`ResourceTemplateManagerImpl#createMatcherFromUriTemplate` still compiles the 
literal text as a regex on quarkus-mcp-server `main` (9401256e). Quoting it 
there, for example `Pattern.quote` around each literal part, would let this 
check go away. Until then, the refusal is documented, so it may be fine to 
keep. It would still be worth an upstream issue and a mention in the 
CAMEL-26360 parity notes.
   
   _Claude Code (Opus 5.5) on behalf of Federico Mariani_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to