diff --git a/docs/mcp.md b/docs/mcp.md index a8aae2cc05..042026c4b6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4,13 +4,72 @@ The Data API exposes commands as MCP tools over Streamable HTTP. Use `tools/list ## Endpoint and requests -The default endpoint is `/v1/mcp`. It follows the HTTP and MCP root paths described in the [configuration guide](../CONFIGURATION.md#mcp-logging). Keep authentication paths aligned when changing the endpoint. +The default endpoint is `/v1/mcp`. It follows the HTTP and MCP root paths described in the [configuration guide](../CONFIGURATION.md#mcp-logging). The server derives the MCP authentication paths from that configuration. Tool execution is disabled by default. Enable it with `stargate.feature.flags.mcp=true`, or send `Feature-Flag-mcp` with value `true` when the server has no configured override. This flag does not grant database permissions. Current tests send protocol version `2026-07-28` and call tools without initialization or a session ID. Each request carries its own protocol metadata. [McpHttpTestSupport](../src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpHttpTestSupport.java) defines the tested headers and JSON-RPC envelope. -The current implementation uses the existing Data API `Token` header. A missing token returns HTTP 401 before tool execution. OAuth connection and migration instructions remain separate work in [#2643](https://github.com/stargate/data-api/issues/2643). These tests do not establish compatibility with every MCP client or protocol revision. +The existing Data API `Token` and `X-Cassandra-Token` headers remain supported on ordinary REST endpoints when header authentication is enabled. MCP retains that behavior until OAuth mode is enabled. Missing credentials return HTTP 401 before tool execution. These tests do not establish compatibility with every MCP client or protocol revision. + +## OAuth authentication + +OAuth mode is disabled by default. Enabling it makes the MCP transport accept only Bearer access tokens and leaves ordinary REST authentication unchanged. Configure the public MCP origin, authorization server, and JWT trust settings. For the default endpoint: + +```properties +stargate.auth.bearer.enabled=true +stargate.feature.flags.mcp=true +stargate.mcp.auth.public-base-url=https://api.example.com +stargate.mcp.auth.server-url=https://auth.example.com +mp.jwt.verify.issuer=https://auth.example.com +mp.jwt.verify.publickey.location=https://auth.example.com/.well-known/jwks.json +mp.jwt.verify.audiences=https://api.example.com/v1/mcp +``` + +Use the issuer and verification key published by your authorization server. A local public-key file can replace the JWKS URL. Enabling Bearer authentication requires a build with `quarkus.smallrye-jwt.enabled=true`, an explicit issuer, and a verification key. For a fixed public URL, configure its audience at startup. Use the canonical value `Authorization` for `mp.jwt.token.header`. With MCP enabled, the token must have exactly one audience, the public MCP resource URL. + +The public base URL contains the scheme, host, and optional port. The server derives the MCP resource path from its HTTP and MCP root configuration. For example, HTTP root `/service` and MCP root `/tools` require audience `https://api.example.com/service/tools`. OAuth mode requires a dedicated MCP path beneath the HTTP root. Root-only configurations are rejected at startup because the current framework does not keep those transport routes within application authentication. Public discovery requires MCP to be enabled in server configuration. An approved browser origin can read the challenge and fetch the metadata without credentials. The metadata is available at `/.well-known/oauth-protected-resource`, under the HTTP root when configured, and is absent when Bearer authentication or MCP is disabled. + +A deployment that serves one public host per database sets a host suffix instead of the fixed base URL. Each request host made of a single DNS label under that suffix is then its own resource. + +```properties +stargate.mcp.auth.public-host-suffix=.apps.example.com +``` + +A request to `https://db1-us-east-2.apps.example.com/v1/mcp` receives metadata and a challenge that name that host, and its token must carry that exact URL as its sole audience. A token naming a different database or multiple audiences receives HTTP 401. The published scheme is always `https`, and a port other than 443 is kept. A request on any other host receives HTTP 401 without a challenge, and its metadata request receives HTTP 404. Set either `stargate.mcp.auth.public-base-url` or the suffix, never both. `mp.jwt.verify.audiences` is not required with a suffix, and a value set there is checked in addition to the request host. The host is the one the request arrives with, after any forwarded-host handling enabled through `quarkus.http.proxy`, so the gateway must pass the public host through unchanged. + +Unauthenticated MCP requests receive HTTP 401 with an absolute `WWW-Authenticate: Bearer resource_metadata="..."` URL. Send `Authorization: Bearer ` on every subsequent stateless HTTP request, including catalog requests. The validator checks the token before tool execution. Legacy MCP headers and invalid Bearer credentials cannot fall back to legacy authentication in OAuth mode. When OAuth mode is disabled, legacy MCP authentication keeps its existing precedence. An MCP access token alone does not authenticate an ordinary REST request. + +OAuth tool calls forward the verified JWT to the database. REST keeps its configured credential resolver. Embedding and reranking calls can use separately supplied provider credentials. Stored credentials that require a credential-service token are unavailable in OAuth mode. + +The shared `data-api-auth` HTTP permission selects the Data API authenticator for MCP transport and ordinary `v1` routes, including under strict inclusive authentication. Keep this permission in place when adding route policies. A competing policy that selects a different authenticator can cause requests on those routes to be denied. Public resource discovery remains available without credentials. + +The token’s space-separated `scope` claim controls which tools it can call. `astra:db:read` covers reads, `astra:db:write` covers reads and data changes, and `astra:db:admin` covers schema changes. Missing scope returns HTTP 403 with an `insufficient_scope` Bearer challenge naming the required scope. Database permission denials return HTTP 403 with the `UNAUTHORIZED_ACCESS` tool error and a Bearer challenge pointing to resource metadata. The optional `stargate.mcp.auth.scopes-supported` setting controls the scopes advertised in that metadata. + +This endpoint is an OAuth protected resource, not an authorization server. Browser login, client registration, organization/role selection, and token issuance remain outside Data API. The backend must support the agreed JWT credential contract. Successful initialization or tool discovery does not prove authorized database execution. + +Local verification used DSE 6.9.21's native OIDC authentication alongside internal password authentication. It required an OIDC issuer, the MCP resource audience, `allow_token_via_password_authentication=true`, and `token_username=token`. DSE mapped an issuer-signed claim to a restricted database role. The issuer derived that claim from validated organization membership and role selection. Internal password authentication alone cannot validate these JWT credentials. Each deployment needs matching issuer, audience, and database permission configuration. + +The compatibility tests inspect the HTTP-to-command boundary with a processor test double. Validate real permitted and denied database calls against the deployment's backend as well. Migration work remains tracked in [#2643](https://github.com/stargate/data-api/issues/2643). + +### Reusable OAuth smoke test + +With OAuth and MCP enabled, use an existing collection and a known document to test the database path. Run from the repository root with Python 3.10 or later. + +```sh +python3 docs/mcp/oauth_smoke.py \ + --endpoint https://api.example.com/v1/mcp \ + --keyspace demo_readonly --collection messages \ + --filter '{"id":"welcome"}' \ + --expect-document '{"id":"welcome","value":"hello"}' \ + --denied-keyspace demo_other_org +``` + +The [script](mcp/oauth_smoke.py) prompts for an access token without echoing it. Automation can supply `MCP_ACCESS_TOKEN` through the environment. Obtain the token from the deployment's authorization server for the exact MCP resource audience. The script consumes that token and does not perform browser login or token issuance. + +It checks the unauthenticated HTTP 401 challenge, public resource metadata, authenticated tool catalog, and exact `findOne` document. It prints the available tool names and exits nonzero on HTTP, protocol, application, or document mismatches. The optional `--denied-keyspace` repeats the read against another existing keyspace and requires HTTP 403 and `UNAUTHORIZED_ACCESS`. No write tools are called. The script uses the stateless protocol version described above and does not test older session-based clients. + +Run the script's focused tests with `python3 -B -m unittest discover -s docs/mcp -p 'test_*.py' -v`. ## Results and errors diff --git a/docs/mcp/oauth_smoke.py b/docs/mcp/oauth_smoke.py new file mode 100644 index 0000000000..39c62b1114 --- /dev/null +++ b/docs/mcp/oauth_smoke.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Check a Data API OAuth resource and a database read with an existing token.""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import getpass +import ipaddress +import json +import os +import re +import sys +import urllib.error +import urllib.parse +import urllib.request +import warnings + +PROTOCOL = "2026-07-28" +MAX_BODY = 2 * 1024 * 1024 +MAX_CATALOG_PAGES = 100 + + +class SmokeFailure(ValueError): + pass + + +def require(condition, message): + if not condition: + raise SmokeFailure(message) + + +def origin(url): + try: + parts = urllib.parse.urlsplit(url) + host, port = parts.hostname, parts.port + try: + loopback = ipaddress.ip_address(host or "").is_loopback + except ValueError: + loopback = host == "localhost" + require(host and (parts.scheme == "https" or parts.scheme == "http" and loopback) + and parts.username is None and parts.password is None + and not parts.query and not parts.fragment, + "URLs must use HTTPS or loopback HTTP without credentials, queries, or fragments") + return parts.scheme, host, port or (443 if parts.scheme == "https" else 80) + except ValueError as error: + if isinstance(error, SmokeFailure): + raise + raise SmokeFailure("Invalid URL") from None + + +def json_object(raw): + try: + value = json.loads(raw) + except (ValueError, UnicodeDecodeError): + raise SmokeFailure("Expected a JSON object") from None + require(isinstance(value, dict), "Expected a JSON object") + return value + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args): + return None + + +@dataclass +class Response: + status: int + headers: object + body: bytes + + def json(self): + return json_object(self.body) + + def bearer_challenge(self): + scheme, _, parameters = self.headers.get("WWW-Authenticate", "").partition(" ") + fields = {} + if scheme.lower() == "bearer": + for parameter in urllib.request.parse_http_list(parameters): + match = re.fullmatch(r'([\w-]+)\s*=\s*(?:"([^"]*)"|([^\s",]+))', parameter) + if not match or match[1].lower() in fields: + return {} + fields[match[1].lower()] = match[2] if match[2] is not None else match[3] + return fields + + +class Client: + def __init__(self, endpoint): + origin(endpoint) + self.endpoint = endpoint + self.sequence = 0 + self.opener = urllib.request.build_opener(NoRedirect()) + + def request(self, url, data=None, headers=None): + origin(url) + request = urllib.request.Request(url, data=data, headers=headers or {}) + try: + response = self.opener.open(request, timeout=20) + except urllib.error.HTTPError as error: + response = error + with response: + body = response.read(MAX_BODY + 1) + require(len(body) <= MAX_BODY, "Response exceeds size limit") + return Response(response.code, response.headers, body) + + def rpc(self, method, params, token=None): + self.sequence += 1 + payload = {"jsonrpc": "2.0", "id": self.sequence, "method": method, + "params": {**params, "_meta": { + "io.modelcontextprotocol/protocolVersion": PROTOCOL, + "io.modelcontextprotocol/clientCapabilities": {}}}} + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "MCP-Protocol-Version": PROTOCOL, "Mcp-Method": method} + if method == "tools/call": + headers["Mcp-Name"] = params["name"] + if token: + headers["Authorization"] = "Bearer " + token + return self.request(self.endpoint, json.dumps(payload).encode(), headers) + + def result(self, method, params, token, denied_metadata=None): + response = self.rpc(method, params, token) + expected_status = 403 if denied_metadata is not None else 200 + require(response.status == expected_status, + f"{method} returned HTTP {response.status}, expected {expected_status}") + if denied_metadata is not None: + challenge = response.bearer_challenge() + require(challenge.get("resource_metadata") == denied_metadata and "error" not in challenge, + "Database denial requires the Bearer discovery challenge without an OAuth error") + body = response.json() + require(body.get("jsonrpc") == "2.0" and body.get("id") == self.sequence, + "JSON-RPC response did not match its request") + require("error" not in body and isinstance(body.get("result"), dict), + "MCP returned a protocol error or no result") + return body["result"] + + +def smoke_test(endpoint, token, keyspace, collection, filter_value, expected_document, + denied_keyspace=None): + require(isinstance(token, str) and bool(token) and not any(c.isspace() for c in token), + "A nonempty access token without whitespace is required") + require(isinstance(filter_value, dict) and isinstance(expected_document, dict), + "The filter and expected document must be JSON objects") + client = Client(endpoint) + challenge = client.rpc("tools/list", {}) + require(challenge.status == 401, f"Unauthenticated MCP returned HTTP {challenge.status}, expected 401") + metadata_url = challenge.bearer_challenge().get("resource_metadata") + require(metadata_url, "The 401 challenge is missing Bearer resource metadata") + require(origin(metadata_url) == origin(endpoint), "Resource metadata must use the MCP origin") + response = client.request(metadata_url) + require(response.status == 200, f"Resource metadata returned HTTP {response.status}") + document = response.json() + servers = document.get("authorization_servers") + require(document.get("resource") == endpoint and isinstance(servers, list) and bool(servers) + and all(isinstance(server, str) for server in servers) + and isinstance(document.get("bearer_methods_supported"), list) + and "header" in document["bearer_methods_supported"], "Resource metadata is inconsistent") + for server in servers: + origin(server) + print("PASS Unauthenticated challenge and protected-resource metadata") + + names = [] + seen_cursors = set() + params = {} + for _ in range(MAX_CATALOG_PAGES): + catalog = client.result("tools/list", params, token) + tools = catalog.get("tools") + require(isinstance(tools, list) + and all(isinstance(tool, dict) and isinstance(tool.get("name"), str) + and tool["name"] for tool in tools), "Invalid tool catalog") + names.extend(tool["name"] for tool in tools) + cursor = catalog.get("nextCursor") + if cursor is None: + break + require(isinstance(cursor, str) and cursor and cursor not in seen_cursors, + "Invalid or repeated tool catalog cursor") + seen_cursors.add(cursor) + params = {"cursor": cursor} + else: + raise SmokeFailure("Tool catalog exceeded the page limit") + require(len(names) == len(set(names)) and "findOne" in names, + "Expected a complete, unique catalog containing findOne") + print(f"PASS Authenticated catalog ({len(names)} tools): " + + json.dumps(names).replace(token, "[REDACTED]")) + + arguments = {"keyspace": keyspace, "collection": collection, "filter": filter_value} + result = client.result("tools/call", {"name": "findOne", "arguments": arguments}, token) + content = result.get("structuredContent") + require(result.get("isError", False) is False and isinstance(content, dict) + and not content.get("errors") and content.get("document") == expected_document, + "Database read did not return the expected document without application errors") + print("PASS Database read returned the exact expected document") + if denied_keyspace is not None: + result = client.result("tools/call", {"name": "findOne", "arguments": { + **arguments, "keyspace": denied_keyspace}}, token, denied_metadata=metadata_url) + content = result.get("structuredContent") + require(result.get("isError") is True and isinstance(content, dict) + and isinstance(content.get("errors"), list) and len(content["errors"]) == 1 + and isinstance(content["errors"][0], dict) + and content["errors"][0].get("errorCode") == "UNAUTHORIZED_ACCESS", + "Denied read did not return UNAUTHORIZED_ACCESS") + print("PASS Other keyspace read returned HTTP 403 with UNAUTHORIZED_ACCESS") + return names + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("endpoint", "keyspace", "collection"): + parser.add_argument("--" + name, required=True) + + def object_argument(value): + try: + return json_object(value) + except SmokeFailure as error: + raise argparse.ArgumentTypeError(str(error)) from None + + parser.add_argument("--filter", required=True, type=object_argument, dest="filter_value") + parser.add_argument("--expect-document", required=True, type=object_argument, dest="expected_document") + parser.add_argument("--denied-keyspace") + args = parser.parse_args() + try: + with warnings.catch_warnings(): + warnings.simplefilter("error", getpass.GetPassWarning) + token = os.environ.get("MCP_ACCESS_TOKEN") or getpass.getpass("OAuth access token: ") + smoke_test(token=token, **vars(args)) + except SmokeFailure as error: + print("FAIL " + str(error), file=sys.stderr) + return 1 + except (OSError, ValueError, EOFError, getpass.GetPassWarning): + print("FAIL Request or token input failed", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/mcp/test_oauth_smoke.py b/docs/mcp/test_oauth_smoke.py new file mode 100644 index 0000000000..81d0547549 --- /dev/null +++ b/docs/mcp/test_oauth_smoke.py @@ -0,0 +1,209 @@ +"""Run with python3 -B -m unittest discover -s docs/mcp -p 'test_*.py'.""" + +from contextlib import redirect_stderr, redirect_stdout +from http.server import BaseHTTPRequestHandler, HTTPServer +from io import StringIO +import json +import os +import sys +import threading +import unittest +from unittest.mock import patch +import warnings + +import oauth_smoke as smoke + + +class OAuthSmokeTest(unittest.TestCase): + def setUp(self): + self.requests = [] + self.mutation = lambda method, body: body + self.redirect = False + self.denied_status = 403 + self.pages = {None: {"tools": [{"name": "findOne"}, {"name": "findKeyspaces"}]}} + owner = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def send(self, status, body, **headers): + raw = json.dumps(body).encode() + self.send_response(status) + for key, value in headers.items(): + self.send_header(key.replace("_", "-"), value) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + def do_GET(self): + owner.requests.append((self.path, dict(self.headers), None)) + body = {"resource": owner.endpoint, "authorization_servers": [owner.base], + "bearer_methods_supported": ["header"]} + self.send(200, owner.mutation("metadata", body)) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + owner.requests.append((self.path, dict(self.headers), body)) + if "Authorization" not in self.headers: + self.send(401, {}, WWW_Authenticate=f'Bearer resource_metadata="{owner.base}/metadata"') + return + if owner.redirect: + self.send(302, {}, Location=owner.base + "/redirected") + return + status = 200 + if body["method"] == "tools/list": + result = owner.pages[body["params"].get("cursor")] + elif body["params"]["arguments"]["keyspace"] == "denied": + status = owner.denied_status + result = {"isError": True, "structuredContent": { + "errors": [{"errorCode": "UNAUTHORIZED_ACCESS"}]}} + else: + result = {"isError": False, "structuredContent": {"document": {"id": "hello"}}} + response = {"jsonrpc": "2.0", "id": body["id"], "result": result} + self.send(status, owner.mutation(body["method"], response), + **(owner.denied_headers if status == 403 else {})) + + self.server = HTTPServer(("127.0.0.1", 0), Handler) + self.base = "http://127.0.0.1:" + str(self.server.server_port) + self.endpoint = self.base + "/v1/mcp" + self.denied_headers = {"WWW_Authenticate": f'Bearer resource_metadata="{self.base}/metadata"'} + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.thread.join) + self.addCleanup(self.server.shutdown) + + def run_smoke(self, **overrides): + arguments = {"endpoint": self.endpoint, "token": "test-token", "keyspace": "allowed", + "collection": "messages", "filter_value": {"id": "hello"}, + "expected_document": {"id": "hello"}} + with redirect_stdout(StringIO()): + return smoke.smoke_test(**{**arguments, **overrides}) + + def test_read_and_denied_read_use_bearer_only_on_mcp(self): + self.assertEqual(self.run_smoke(denied_keyspace="denied"), ["findOne", "findKeyspaces"]) + self.assertEqual(len(self.requests), 5) + for path, headers, body in self.requests: + self.assertNotIn("Token", headers) + self.assertNotIn("X-Cassandra-Token", headers) + if body is None or body["id"] == 1: + self.assertNotIn("Authorization", headers) + else: + self.assertEqual(headers["Authorization"], "Bearer test-token") + self.assertEqual(path, "/v1/mcp") + self.assertEqual(headers["Mcp-Protocol-Version"], smoke.PROTOCOL) + self.assertEqual(body["params"]["_meta"], { + "io.modelcontextprotocol/protocolVersion": smoke.PROTOCOL, + "io.modelcontextprotocol/clientCapabilities": {}}) + self.assertEqual(self.requests[-1][2]["params"]["arguments"], { + "keyspace": "denied", "collection": "messages", "filter": {"id": "hello"}}) + + def test_catalog_follows_cursor_to_find_one(self): + self.pages = { + None: {"tools": [{"name": "findKeyspaces"}], "nextCursor": "more"}, + "more": {"tools": [{"name": "findOne"}]}, + } + self.assertEqual(self.run_smoke(), ["findKeyspaces", "findOne"]) + + def test_catalog_rejects_a_repeated_cursor(self): + self.pages = { + None: {"tools": [{"name": "findOne"}], "nextCursor": "more"}, + "more": {"tools": [{"name": "findKeyspaces"}], "nextCursor": "more"}, + } + with self.assertRaisesRegex(smoke.SmokeFailure, "cursor"): + self.run_smoke() + + def test_database_denial_requires_http_403(self): + self.denied_status = 200 + with self.assertRaisesRegex(smoke.SmokeFailure, "expected 403"): + self.run_smoke(denied_keyspace="denied") + + def test_database_denial_requires_its_discovery_challenge(self): + challenge = self.denied_headers["WWW_Authenticate"] + for headers in ({}, {"WWW_Authenticate": challenge.replace("/metadata", "/other")}, + {"WWW_Authenticate": challenge + ', error="insufficient_scope"'}): + with self.subTest(headers=headers), self.assertRaisesRegex(smoke.SmokeFailure, "challenge"): + self.denied_headers = headers + self.run_smoke(denied_keyspace="denied") + + def test_wrong_document_fails(self): + with self.assertRaisesRegex(smoke.SmokeFailure, "expected document"): + self.run_smoke(expected_document={"id": "different"}) + + def test_setup_error_does_not_count_as_permission_denial(self): + def mutation(method, body): + if method == "tools/call" and body["result"].get("isError"): + body["result"]["structuredContent"]["errors"][0]["errorCode"] = "UNAUTHENTICATED_REQUEST" + return body + self.mutation = mutation + with self.assertRaisesRegex(smoke.SmokeFailure, "UNAUTHORIZED_ACCESS"): + self.run_smoke(denied_keyspace="denied") + + def test_application_error_cannot_pass_with_matching_document(self): + def mutation(method, body): + if method == "tools/call": + body["result"]["structuredContent"]["errors"] = [{"errorCode": "INVALID_QUERY"}] + return body + self.mutation = mutation + with self.assertRaisesRegex(smoke.SmokeFailure, "application errors"): + self.run_smoke() + + def test_rpc_id_must_match(self): + def mutation(method, body): + if method == "tools/list": + body["id"] += 1 + return body + self.mutation = mutation + with self.assertRaisesRegex(smoke.SmokeFailure, "did not match"): + self.run_smoke() + + def test_resource_must_match_endpoint(self): + def mutation(method, body): + if method == "metadata": + body["resource"] += "/other" + return body + self.mutation = mutation + with self.assertRaisesRegex(smoke.SmokeFailure, "metadata is inconsistent"): + self.run_smoke() + self.assertEqual(len(self.requests), 2) + + def test_authenticated_redirect_is_not_followed(self): + self.redirect = True + with self.assertRaisesRegex(smoke.SmokeFailure, "HTTP 302"): + self.run_smoke() + self.assertEqual([path for path, _, _ in self.requests], ["/v1/mcp", "/metadata", "/v1/mcp"]) + + def test_cross_origin_metadata_is_not_requested(self): + with patch.object(smoke.Client, "rpc", return_value=smoke.Response(401, { + "WWW-Authenticate": 'Bearer resource_metadata="https://other.example/metadata"'}, b"")): + with self.assertRaisesRegex(smoke.SmokeFailure, "MCP origin"): + self.run_smoke() + self.assertEqual(self.requests, []) + + def test_unsafe_urls_fail_before_network(self): + for endpoint in ("http://api.example/v1/mcp", "https://user:pass@api.example/v1/mcp", + "https://api.example/v1/mcp?token=secret", "https://api.example/#fragment"): + with self.subTest(endpoint=endpoint), self.assertRaises(smoke.SmokeFailure): + self.run_smoke(endpoint=endpoint) + self.assertEqual(self.requests, []) + + def test_prompt_fails_closed_when_hidden_input_is_unavailable(self): + arguments = ["oauth_smoke.py", "--endpoint", self.endpoint, "--keyspace", "allowed", + "--collection", "messages", "--filter", '{}', "--expect-document", '{}'] + def unavailable_prompt(*args): + warnings.warn("secret input must not be echoed", smoke.getpass.GetPassWarning) + self.fail("The prompt continued after its hidden-input warning") + output, error = StringIO(), StringIO() + with patch.object(sys, "argv", arguments), patch.dict(os.environ, {"MCP_ACCESS_TOKEN": ""}), \ + patch.object(smoke.getpass, "getpass", side_effect=unavailable_prompt), \ + patch.object(smoke, "smoke_test") as run, redirect_stdout(output), redirect_stderr(error): + self.assertEqual(smoke.main(), 1) + run.assert_not_called() + self.assertEqual(output.getvalue(), "") + self.assertEqual(error.getvalue(), "FAIL Request or token input failed\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/pom.xml b/pom.xml index 9660c4c763..9ce97ad61a 100644 --- a/pom.xml +++ b/pom.xml @@ -130,6 +130,10 @@ io.quarkus quarkus-security + + io.quarkus + quarkus-smallrye-jwt + io.quarkus quarkus-grpc diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/request/RequestContext.java b/src/main/java/io/stargate/sgv2/jsonapi/api/request/RequestContext.java index e0c770d6b4..312f8bf080 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/request/RequestContext.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/request/RequestContext.java @@ -11,6 +11,7 @@ import io.stargate.sgv2.jsonapi.api.request.tenant.RequestTenantResolver; import io.stargate.sgv2.jsonapi.api.request.tenant.Tenant; import io.stargate.sgv2.jsonapi.api.request.token.RequestAuthTokenResolver; +import io.stargate.sgv2.jsonapi.api.security.McpOAuthMetadata; import io.stargate.sgv2.jsonapi.config.BillingConfig; import io.stargate.sgv2.jsonapi.config.feature.ApiFeatures; import io.stargate.sgv2.jsonapi.config.feature.FeaturesConfig; @@ -18,12 +19,16 @@ import io.stargate.sgv2.jsonapi.service.billing.Billing; import io.stargate.sgv2.jsonapi.service.schema.SchemaRegistry; import io.vertx.ext.web.RoutingContext; +import jakarta.annotation.Nullable; import jakarta.enterprise.context.RequestScoped; import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; +import jakarta.inject.Provider; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.SecurityContext; import java.util.List; +import java.util.Optional; +import org.eclipse.microprofile.jwt.JsonWebToken; import org.slf4j.MDC; /** @@ -43,6 +48,7 @@ public class RequestContext implements LoggingMDCContext { private static final String ROUTING_REQUEST_ID = RequestContext.class.getName() + ".requestId"; private final String authToken; + private final String providerAuthToken; private final String requestId; private final UserAgent userAgent; private final Tenant tenant; @@ -65,6 +71,7 @@ public class RequestContext implements LoggingMDCContext { public RequestContext(Tenant tenant, String authToken, UserAgent userAgent) { this.authToken = authToken; + this.providerAuthToken = authToken; this.requestId = generateRequestId(); this.userAgent = userAgent; this.tenant = tenant; @@ -73,63 +80,86 @@ public RequestContext(Tenant tenant, String authToken, UserAgent userAgent) { this.httpHeaders = null; } - /** - * Constructor for non-JAX-RS HTTP contexts (e.g., MCP Streamable HTTP) where JAX-RS {@link - * SecurityContext} is not available but Quarkus {@link SecurityIdentity} is. Uses the same - * resolution logic as the CDI constructor. - */ + /** Builds the MCP request context from the identity authenticated by the HTTP transport. */ public RequestContext( RoutingContext routingContext, SecurityIdentity securityIdentity, Instance tenantResolver, + Instance tokenResolver, Instance embeddingCredentialsResolver) { this.httpHeaders = new HttpHeaderAccess(routingContext.request().headers()); - // Token from SecurityIdentity principal (same as PrincipalTokenResolver logic) + var principal = securityIdentity.getPrincipal(); this.authToken = normalizeOptionalString( - securityIdentity.getPrincipal() != null - ? securityIdentity.getPrincipal().getName() - : null); + principal instanceof JsonWebToken jwt + ? jwt.getRawToken() + : tokenResolver.get().resolve(routingContext, principal)); + this.providerAuthToken = principal instanceof JsonWebToken ? null : authToken; this.requestId = getOrCreateRequestId(routingContext); this.userAgent = new UserAgent(httpHeaders.getHeader(HttpHeaders.USER_AGENT)); this.tenant = tenantResolver.get().resolve(routingContext, null); this.embeddingCredentials = - embeddingCredentialsResolver.get().resolveEmbeddingCredentials(tenant, routingContext); + resolveEmbeddingCredentials(embeddingCredentialsResolver.get(), routingContext); - this.rerankingCredentials = - HeaderBasedRerankingKeyResolver.resolveRerankingKey(routingContext) - .map(s -> new RerankingCredentials(tenant, normalizeOptionalString(s))) - .orElseGet(() -> new RerankingCredentials(tenant, authToken)); + this.rerankingCredentials = resolveRerankingCredentials(routingContext); } @Inject public RequestContext( RoutingContext routingContext, - SecurityContext securityContext, + Provider restSecurityContext, + SecurityIdentity securityIdentity, Instance tenantResolver, Instance tokenResolver, - Instance embeddingCredentialsResolver) { + Instance embeddingCredentialsResolver, + McpOAuthMetadata oauthMetadata) { this.httpHeaders = new HttpHeaderAccess(routingContext.request().headers()); + boolean mcpRequest = oauthMetadata.isMcpRequest(routingContext); + var securityContext = mcpRequest ? null : restSecurityContext.get(); + var principal = + mcpRequest ? securityIdentity.getPrincipal() : securityContext.getUserPrincipal(); this.authToken = - normalizeOptionalString(tokenResolver.get().resolve(routingContext, securityContext)); - this.requestId = generateRequestId(); + normalizeOptionalString( + mcpRequest && principal instanceof JsonWebToken jwt + ? jwt.getRawToken() + : tokenResolver.get().resolve(routingContext, principal)); + this.providerAuthToken = + mcpRequest && (oauthMetadata.bearerEnabled() || principal instanceof JsonWebToken) + ? null + : authToken; + this.requestId = mcpRequest ? getOrCreateRequestId(routingContext) : generateRequestId(); this.userAgent = new UserAgent(httpHeaders.getHeader(HttpHeaders.USER_AGENT)); this.tenant = tenantResolver.get().resolve(routingContext, securityContext); this.embeddingCredentials = - embeddingCredentialsResolver.get().resolveEmbeddingCredentials(tenant, routingContext); - - // user specified the reranking key in the request header, use that. - // fall back to whatever they provided as the auth token for the API - this.rerankingCredentials = - HeaderBasedRerankingKeyResolver.resolveRerankingKey(routingContext) - .map(s -> new RerankingCredentials(tenant, normalizeOptionalString(s))) - .orElseGet(() -> new RerankingCredentials(tenant, authToken)); + resolveEmbeddingCredentials(embeddingCredentialsResolver.get(), routingContext); + + this.rerankingCredentials = resolveRerankingCredentials(routingContext); + } + + private RerankingCredentials resolveRerankingCredentials(RoutingContext context) { + var key = + HeaderBasedRerankingKeyResolver.resolveRerankingKey(context).orElse(providerAuthToken); + return new RerankingCredentials(tenant, normalizeOptionalString(key)); + } + + private EmbeddingCredentials resolveEmbeddingCredentials( + EmbeddingCredentialsResolver resolver, RoutingContext context) { + var credentials = resolver.resolveEmbeddingCredentials(tenant, context); + if (providerAuthToken != null || credentials.authToken().isEmpty()) { + return credentials; + } + return new EmbeddingCredentials( + credentials.tenant(), + credentials.apiKey(), + credentials.accessId(), + credentials.secretId(), + Optional.empty()); } private static String generateRequestId() { @@ -171,6 +201,12 @@ public String authToken() { return authToken; } + /** Legacy credential for provider services. MCP access tokens are scoped to the database. */ + @Nullable + public String providerAuthToken() { + return providerAuthToken; + } + /** Non-null {@link UserAgent} for the request, resolved from the request. */ public UserAgent userAgent() { return userAgent; diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/FixedTokenResolver.java b/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/FixedTokenResolver.java index 9dbed81aba..720f4511d5 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/FixedTokenResolver.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/FixedTokenResolver.java @@ -18,7 +18,7 @@ package io.stargate.sgv2.jsonapi.api.request.token; import io.vertx.ext.web.RoutingContext; -import jakarta.ws.rs.core.SecurityContext; +import java.security.Principal; /** The {@link RequestAuthTokenResolver} that uses a fixed token supplied by the configuration. */ public class FixedTokenResolver implements RequestAuthTokenResolver { @@ -31,7 +31,7 @@ public FixedTokenResolver(String fixedToken) { /** {@inheritDoc} */ @Override - public String resolve(RoutingContext context, SecurityContext securityContext) { + public String resolve(RoutingContext context, Principal principal) { return fixedToken; } } diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/HeaderTokenResolver.java b/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/HeaderTokenResolver.java index 99b285c2cb..2940ffa57e 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/HeaderTokenResolver.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/HeaderTokenResolver.java @@ -18,7 +18,7 @@ package io.stargate.sgv2.jsonapi.api.request.token; import io.vertx.ext.web.RoutingContext; -import jakarta.ws.rs.core.SecurityContext; +import java.security.Principal; /** The {@link RequestAuthTokenResolver} that resolves a token from the HTTP header. */ public class HeaderTokenResolver implements RequestAuthTokenResolver { @@ -32,7 +32,7 @@ public HeaderTokenResolver(String headerName) { /** {@inheritDoc} */ @Override - public String resolve(RoutingContext context, SecurityContext securityContext) { + public String resolve(RoutingContext context, Principal principal) { return context.request().getHeader(headerName); } } diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/PrincipalTokenResolver.java b/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/PrincipalTokenResolver.java index e6112812f1..1f303c1219 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/PrincipalTokenResolver.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/PrincipalTokenResolver.java @@ -18,16 +18,18 @@ package io.stargate.sgv2.jsonapi.api.request.token; import io.vertx.ext.web.RoutingContext; -import jakarta.ws.rs.core.SecurityContext; import java.security.Principal; +import org.eclipse.microprofile.jwt.JsonWebToken; -/** {@link RequestAuthTokenResolver} that reads the token from the {@link Principal#getName()}. */ +/** Resolves validated JWT credentials or the legacy token stored as the principal name. */ public class PrincipalTokenResolver implements RequestAuthTokenResolver { /** {@inheritDoc} */ @Override - public String resolve(RoutingContext context, SecurityContext securityContext) { - var principal = securityContext.getUserPrincipal(); + public String resolve(RoutingContext context, Principal principal) { + if (principal instanceof JsonWebToken jwt) { + return jwt.getRawToken(); + } return principal != null ? principal.getName() : null; } } diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/RequestAuthTokenResolver.java b/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/RequestAuthTokenResolver.java index 082639d4d9..ea60fa3da4 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/RequestAuthTokenResolver.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/request/token/RequestAuthTokenResolver.java @@ -18,23 +18,24 @@ package io.stargate.sgv2.jsonapi.api.request.token; import io.vertx.ext.web.RoutingContext; -import jakarta.ws.rs.core.SecurityContext; +import java.security.Principal; /** * Resolver of the Cassandra token. * *

The implementation can use any information from the {@link RoutingContext} or {@link - * SecurityContext} to obtain the token. + * Principal} to obtain the token. */ @FunctionalInterface public interface RequestAuthTokenResolver { /** - * Returns a Cassandra token given a {@link RoutingContext} and a {@link SecurityContext}. + * Returns a Cassandra token given a {@link RoutingContext} and its authenticated {@link + * Principal}. * * @param context the routing context - * @param securityContext the security context + * @param principal the authenticated principal * @return The Cassandra token. If empty, indicates that no token should be used. */ - String resolve(RoutingContext context, SecurityContext securityContext); + String resolve(RoutingContext context, Principal principal); } diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/security/DataApiAuthenticationPolicy.java b/src/main/java/io/stargate/sgv2/jsonapi/api/security/DataApiAuthenticationPolicy.java new file mode 100644 index 0000000000..17342ec5d5 --- /dev/null +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/security/DataApiAuthenticationPolicy.java @@ -0,0 +1,39 @@ +package io.stargate.sgv2.jsonapi.api.security; + +import io.quarkus.security.identity.SecurityIdentity; +import io.quarkus.security.runtime.QuarkusSecurityIdentity; +import io.quarkus.vertx.http.runtime.security.HttpSecurityPolicy; +import io.smallrye.mutiny.Uni; +import io.vertx.ext.web.RoutingContext; +import jakarta.enterprise.context.ApplicationScoped; + +/** Checks which mechanism supplied the identity before the route's authorization policy runs. */ +@ApplicationScoped +public class DataApiAuthenticationPolicy implements HttpSecurityPolicy { + static final String NAME = "data-api"; + private static final String ATTRIBUTE = DataApiAuthenticationPolicy.class.getName(); + private static final Object VERIFIED = new Object(); + + static SecurityIdentity authenticatedIdentity(SecurityIdentity identity) { + return QuarkusSecurityIdentity.builder(identity) + .addPermissions(identity.getPermissions()) + .addAttribute(ATTRIBUTE, VERIFIED) + .build(); + } + + @Override + public String name() { + return NAME; + } + + @Override + public Uni checkPermission( + RoutingContext context, Uni identity, AuthorizationRequestContext request) { + // A competing shared HTTP permission may have selected another mechanism. + return identity.map( + id -> + id.isAnonymous() || id.getAttribute(ATTRIBUTE) == VERIFIED + ? CheckResult.PERMIT + : CheckResult.DENY); + } +} diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/security/HeaderBasedAuthenticationMechanism.java b/src/main/java/io/stargate/sgv2/jsonapi/api/security/HeaderBasedAuthenticationMechanism.java index 8d90af5118..2ea92630c0 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/security/HeaderBasedAuthenticationMechanism.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/security/HeaderBasedAuthenticationMechanism.java @@ -20,25 +20,29 @@ import static io.stargate.sgv2.jsonapi.config.constants.HttpConstants.AUTHENTICATION_TOKEN_HEADER_NAME; import static io.stargate.sgv2.jsonapi.config.constants.HttpConstants.DEPRECATED_AUTHENTICATION_TOKEN_HEADER_NAME; +import io.quarkus.security.AuthenticationFailedException; import io.quarkus.security.identity.IdentityProviderManager; import io.quarkus.security.identity.SecurityIdentity; import io.quarkus.security.identity.request.AuthenticationRequest; +import io.quarkus.security.identity.request.TokenAuthenticationRequest; +import io.quarkus.smallrye.jwt.runtime.auth.JsonWebTokenCredential; import io.quarkus.vertx.http.runtime.security.ChallengeData; import io.quarkus.vertx.http.runtime.security.HttpAuthenticationMechanism; import io.quarkus.vertx.http.runtime.security.HttpCredentialTransport; import io.quarkus.vertx.http.runtime.security.HttpSecurityUtils; import io.smallrye.mutiny.Uni; import io.stargate.sgv2.jsonapi.api.security.challenge.impl.ErrorChallengeSender; +import io.stargate.sgv2.jsonapi.config.AuthConfig; import io.vertx.ext.web.RoutingContext; import jakarta.enterprise.inject.Instance; +import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.Response; -import java.util.Collections; import java.util.Optional; import java.util.Set; +import org.eclipse.microprofile.jwt.JsonWebToken; /** - * Implementation of the {@link HttpAuthenticationMechanism} that authenticates on a header. If a - * target header exists, request is considered as authenticated. + * Coordinates OAuth-only MCP requests and the existing Data API token headers. * * @see HeaderIdentityProvider */ @@ -47,19 +51,90 @@ public class HeaderBasedAuthenticationMechanism implements HttpAuthenticationMec /** The name of the header to be used for the authentication. */ private final String headerName; + private final boolean headerEnabled; + private final boolean bearerEnabled; + private final McpOAuthMetadata metadata; + /** Customize the challenge. */ private final Instance customChallengeSender; public HeaderBasedAuthenticationMechanism( - String headerName, Instance customChallengeSender) { - this.headerName = headerName; + AuthConfig config, + Instance customChallengeSender, + McpOAuthMetadata metadata) { + this.headerName = config.headerBased().headerName(); + this.headerEnabled = config.headerBased().enabled(); + this.bearerEnabled = config.bearer().enabled(); this.customChallengeSender = customChallengeSender; + this.metadata = metadata; } - /** Validate Header existence */ @Override public Uni authenticate( RoutingContext context, IdentityProviderManager identityProviderManager) { + return authenticateCredentials(context, identityProviderManager) + .onItem() + .ifNotNull() + .transform(DataApiAuthenticationPolicy::authenticatedIdentity) + .onFailure(AuthenticationFailedException.class) + .invoke( + failure -> + // The MCP transport writes authentication failures without requesting a challenge. + metadata + .challenge(context) + .ifPresent( + challenge -> + context.response().putHeader(HttpHeaders.WWW_AUTHENTICATE, challenge))); + } + + private Uni authenticateCredentials( + RoutingContext context, IdentityProviderManager identityProviderManager) { + String authorization = context.request().getHeader(HttpHeaders.AUTHORIZATION); + if (bearerEnabled && metadata.isMcpRequest(context)) { + context.put(HttpAuthenticationMechanism.class.getName(), this); + if (authorization == null + || !authorization.regionMatches(true, 0, "Bearer ", 0, 7) + || authorization.substring(7).isBlank()) { + return Uni.createFrom().failure(new AuthenticationFailedException()); + } + var request = + new TokenAuthenticationRequest( + new JsonWebTokenCredential(authorization.substring(7).trim())); + HttpSecurityUtils.setRoutingContextAttribute(request, context); + return identityProviderManager + .authenticate(request) + .map(identity -> requireAudience(context, identity)); + } + + if (headerEnabled) { + String headerValue = legacyHeader(context); + if (headerValue != null) { + context.put(HttpAuthenticationMechanism.class.getName(), this); + var request = new HeaderAuthenticationRequest(headerName, headerValue); + HttpSecurityUtils.setRoutingContextAttribute(request, context); + return identityProviderManager.authenticate(request); + } + } + + // Bearer credentials are only supported on an OAuth-enabled MCP transport. + if (authorization != null) { + context.put(HttpAuthenticationMechanism.class.getName(), this); + return Uni.createFrom().failure(new AuthenticationFailedException()); + } + return Uni.createFrom().optional(Optional.empty()); + } + + /** A verified token is only usable on the resource it was issued for. */ + private SecurityIdentity requireAudience(RoutingContext context, SecurityIdentity identity) { + Set audience = + identity.getPrincipal() instanceof JsonWebToken token ? token.getAudience() : null; + if (!metadata.acceptsAudience(context, audience)) { + throw new AuthenticationFailedException(); + } + return identity; + } + + private String legacyHeader(RoutingContext context) { // Data API Authentication header key: Token String headerValue = context.request().getHeader(headerName); // Data API Authentication header key: token @@ -70,21 +145,30 @@ public Uni authenticate( if (null == headerValue) { headerValue = context.request().getHeader(DEPRECATED_AUTHENTICATION_TOKEN_HEADER_NAME); } - if (null != headerValue) { - HeaderAuthenticationRequest request = - new HeaderAuthenticationRequest(headerName, headerValue); - HttpSecurityUtils.setRoutingContextAttribute(request, context); - return identityProviderManager.authenticate(request); - } - // No suitable header has been found in this requests - return Uni.createFrom().optional(Optional.empty()); + return headerValue; + } + + @Override + public int getPriority() { + // Preserve challenge ordering on routes without an explicit authentication scheme. + return 3000; } /** {@inheritDoc} */ @Override public Uni getChallenge(RoutingContext context) { - return Uni.createFrom() - .item(new ChallengeData(Response.Status.UNAUTHORIZED.getStatusCode(), null, null)); + var challenge = + metadata + .challenge(context) + .map( + value -> + new ChallengeData( + Response.Status.UNAUTHORIZED.getStatusCode(), + HttpHeaders.WWW_AUTHENTICATE, + value)) + .orElseGet( + () -> new ChallengeData(Response.Status.UNAUTHORIZED.getStatusCode(), null, null)); + return Uni.createFrom().item(challenge); } /** @@ -104,14 +188,17 @@ public Uni sendChallenge(RoutingContext context) { /** {@inheritDoc} */ @Override public Set> getCredentialTypes() { - return Collections.singleton(HeaderAuthenticationRequest.class); + return Set.of(HeaderAuthenticationRequest.class, TokenAuthenticationRequest.class); } /** {@inheritDoc} */ @Override public Uni getCredentialTransport(RoutingContext context) { HttpCredentialTransport transport = - new HttpCredentialTransport(HttpCredentialTransport.Type.OTHER_HEADER, headerName); + new HttpCredentialTransport( + HttpCredentialTransport.Type.OTHER_HEADER, + headerName, + DataApiAuthenticationPolicy.NAME); return Uni.createFrom().item(transport); } } diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/security/McpOAuthMetadata.java b/src/main/java/io/stargate/sgv2/jsonapi/api/security/McpOAuthMetadata.java new file mode 100644 index 0000000000..ec370bddbd --- /dev/null +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/security/McpOAuthMetadata.java @@ -0,0 +1,251 @@ +package io.stargate.sgv2.jsonapi.api.security; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.Startup; +import io.smallrye.jwt.auth.principal.JWTAuthContextInfo; +import io.stargate.sgv2.jsonapi.api.v1.mcp.McpEndpointConfigSourceFactory; +import io.stargate.sgv2.jsonapi.config.AuthConfig; +import io.stargate.sgv2.jsonapi.config.McpAuthConfig; +import io.stargate.sgv2.jsonapi.config.feature.ApiFeature; +import io.stargate.sgv2.jsonapi.config.feature.ApiFeatures; +import io.stargate.sgv2.jsonapi.config.feature.FeaturesConfig; +import io.vertx.core.net.HostAndPort; +import io.vertx.ext.web.RoutingContext; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import java.net.URI; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import org.eclipse.microprofile.config.inject.ConfigProperty; + +/** + * Keeps discovery, authentication challenges and audience checks on the same public resource. + * + *

The resource is the public URL of the MCP endpoint. A deployment with one public host + * configures it with {@code stargate.mcp.auth.public-base-url}. A deployment that serves one public + * host per database configures {@code stargate.mcp.auth.public-host-suffix} instead, and each + * request host under that suffix is its own resource. + */ +@Startup +@ApplicationScoped +public class McpOAuthMetadata { + private static final String PUBLIC_BASE_URL = "stargate.mcp.auth.public-base-url"; + private static final String PUBLIC_HOST_SUFFIX = "stargate.mcp.auth.public-host-suffix"; + private static final int HTTPS_PORT = 443; + + private static final String DNS_LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"; + private static final Pattern HOST_LABEL = Pattern.compile(DNS_LABEL); + private static final Pattern HOST_SUFFIX = Pattern.compile("(?:\\." + DNS_LABEL + "){2,}"); + + private final McpEndpointConfigSourceFactory.TransportPaths transportPaths; + private final String endpointPath; + private final String metadataPath; + + private final boolean bearerEnabled; + + /** True when Bearer authentication and MCP are both enabled in server configuration. */ + private final boolean published; + + /** Null unless each request host is its own resource. */ + private final String hostSuffix; + + /** Null unless the deployment publishes one fixed resource. */ + private final URI fixedBase; + + private final List authorizationServers; + private final List scopesSupported; + + @Inject + public McpOAuthMetadata( + AuthConfig authConfig, + FeaturesConfig featuresConfig, + McpAuthConfig config, + @ConfigProperty(name = McpEndpointConfigSourceFactory.ENDPOINT_PATH) String endpointPath, + @ConfigProperty(name = McpEndpointConfigSourceFactory.METADATA_PATH) String metadataPath, + JWTAuthContextInfo jwtConfig) { + this.transportPaths = McpEndpointConfigSourceFactory.transportPaths(endpointPath); + this.endpointPath = endpointPath; + this.metadataPath = metadataPath; + this.bearerEnabled = authConfig.bearer().enabled(); + String httpRoot = + metadataPath.substring( + 0, metadataPath.length() - ProtectedResourceMetadataResource.PATH.length()); + if (bearerEnabled + && (endpointPath.equals(httpRoot.isEmpty() ? "/" : httpRoot) + || !endpointPath.startsWith(httpRoot + "/"))) { + // SDK 2.0.3 registers root endpoints on a different router from their auth permissions. + throw new IllegalArgumentException( + "OAuth requires quarkus.mcp.server.http.root-path to use a dedicated path below the HTTP root"); + } + // The audience check must hold whenever a Bearer token can reach MCP, and a request header can + // enable MCP when server configuration leaves the feature undefined. + this.hostSuffix = bearerEnabled ? hostSuffix(config) : null; + this.published = + bearerEnabled + && ApiFeatures.fromConfigAndRequest(featuresConfig, null) + .isFeatureEnabled(ApiFeature.MCP); + this.fixedBase = + bearerEnabled && hostSuffix == null ? config.publicBaseUrl().orElse(null) : null; + if (fixedBase != null) { + validateUrl(fixedBase, PUBLIC_BASE_URL, true); + } + if (!published) { + authorizationServers = List.of(); + scopesSupported = List.of(); + return; + } + + if (hostSuffix == null && fixedBase == null) { + throw new IllegalArgumentException( + PUBLIC_BASE_URL + " or " + PUBLIC_HOST_SUFFIX + " is required"); + } + URI authorizationServer = + config + .serverUrl() + .orElseThrow( + () -> new IllegalArgumentException("stargate.mcp.auth.server-url is required")); + validateUrl(authorizationServer, "stargate.mcp.auth.server-url", false); + if (fixedBase != null + && (jwtConfig.getExpectedAudience() == null + || !jwtConfig + .getExpectedAudience() + .contains(fixedBase.resolve(endpointPath).toString()))) { + throw new IllegalArgumentException( + "mp.jwt.verify.audiences must include the configured public MCP resource"); + } + this.authorizationServers = List.of(authorizationServer); + this.scopesSupported = List.copyOf(config.scopesSupported().orElseGet(List::of)); + } + + /** Empty when discovery is disabled or the request host is not one this deployment serves. */ + public Optional document(RoutingContext context) { + return publicBase(context) + .map( + base -> + new ProtectedResourceMetadata( + base.resolve(endpointPath), + authorizationServers, + List.of("header"), + scopesSupported)); + } + + public boolean isMcpRequest(RoutingContext context) { + return transportPaths.matches(context.normalizedPath()); + } + + public Optional challenge(RoutingContext context) { + if (!published || !isMcpRequest(context)) { + return Optional.empty(); + } + return publicBase(context) + .map(base -> "Bearer resource_metadata=\"" + base.resolve(metadataPath) + "\""); + } + + public String insufficientScopeChallenge(RoutingContext context, String scope) { + return challenge(context).map(value -> value + ", ").orElse("Bearer ") + + "error=\"insufficient_scope\", scope=\"" + + scope + + "\""; + } + + public boolean bearerEnabled() { + return bearerEnabled; + } + + /** Requires a single audience matching the canonical MCP resource. */ + public boolean acceptsAudience(RoutingContext context, Set audience) { + return audience != null + && audience.size() == 1 + && resourceBase(context) + .map(base -> base.resolve(endpointPath).toString()) + .filter(audience::contains) + .isPresent(); + } + + /** True when each request host is its own audience, so no static audience list applies. */ + public boolean audienceFromRequestHost() { + return hostSuffix != null; + } + + private Optional publicBase(RoutingContext context) { + return published ? resourceBase(context) : Optional.empty(); + } + + private Optional resourceBase(RoutingContext context) { + return hostSuffix == null ? Optional.ofNullable(fixedBase) : requestBase(context); + } + + /** + * The public origin of the request host, when it is a single label under the configured suffix. + * Any other host is refused rather than echoed, so a token issued for another service cannot be + * replayed here under that service's host name. + */ + private Optional requestBase(RoutingContext context) { + HostAndPort authority = context.request().authority(); + if (authority == null || authority.host() == null) { + return Optional.empty(); + } + String host = authority.host().toLowerCase(Locale.ROOT); + if (!host.endsWith(hostSuffix) + || !HOST_LABEL.matcher(host.substring(0, host.length() - hostSuffix.length())).matches()) { + return Optional.empty(); + } + int port = authority.port(); + return Optional.of( + URI.create("https://" + host + (port > 0 && port != HTTPS_PORT ? ":" + port : ""))); + } + + private static String hostSuffix(McpAuthConfig config) { + Optional suffix = config.publicHostSuffix(); + if (suffix.isEmpty()) { + return null; + } + if (config.publicBaseUrl().isPresent()) { + throw new IllegalArgumentException( + "Set only one of " + PUBLIC_BASE_URL + " and " + PUBLIC_HOST_SUFFIX); + } + if (!HOST_SUFFIX.matcher(suffix.get()).matches()) { + throw new IllegalArgumentException( + PUBLIC_HOST_SUFFIX + + " must be a lowercase DNS suffix that starts with a dot and has at least two labels"); + } + return suffix.get(); + } + + private static void validateUrl(URI uri, String property, boolean originOnly) { + String scheme = uri.getScheme(); + String host = uri.getHost(); + boolean loopback = + "localhost".equalsIgnoreCase(host) + || "127.0.0.1".equals(host) + || "::1".equals(host) + || "[::1]".equals(host); + boolean secure = + "https".equalsIgnoreCase(scheme) || ("http".equalsIgnoreCase(scheme) && loopback); + if (!secure + || host == null + || uri.getUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || (originOnly + && uri.getRawPath() != null + && !uri.getRawPath().isEmpty() + && !uri.getRawPath().equals("/"))) { + throw new IllegalArgumentException( + property + + " must be an HTTPS URL or loopback HTTP URL" + + (originOnly ? " without a path" : "")); + } + } + + public record ProtectedResourceMetadata( + URI resource, + @JsonProperty("authorization_servers") List authorizationServers, + @JsonProperty("bearer_methods_supported") List bearerMethodsSupported, + @JsonProperty("scopes_supported") @JsonInclude(JsonInclude.Include.NON_EMPTY) + List scopesSupported) {} +} diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/security/ProtectedResourceMetadataResource.java b/src/main/java/io/stargate/sgv2/jsonapi/api/security/ProtectedResourceMetadataResource.java new file mode 100644 index 0000000000..6e54867a72 --- /dev/null +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/security/ProtectedResourceMetadataResource.java @@ -0,0 +1,45 @@ +package io.stargate.sgv2.jsonapi.api.security; + +import io.stargate.sgv2.jsonapi.api.v1.mcp.McpOriginFilter; +import io.vertx.core.http.HttpHeaders; +import io.vertx.ext.web.RoutingContext; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.NotFoundException; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; + +/** Publishes the authorization server for the MCP resource the request addressed. */ +@Path(ProtectedResourceMetadataResource.PATH) +public class ProtectedResourceMetadataResource { + public static final String PATH = "/.well-known/oauth-protected-resource"; + + private final McpOAuthMetadata metadata; + private final Provider routingContext; + private final McpOriginFilter origins; + + @Inject + public ProtectedResourceMetadataResource( + McpOAuthMetadata metadata, Provider routingContext, McpOriginFilter origins) { + this.metadata = metadata; + this.routingContext = routingContext; + this.origins = origins; + } + + @GET + @Produces(MediaType.APPLICATION_JSON) + public McpOAuthMetadata.ProtectedResourceMetadata get() { + var context = routingContext.get(); + var document = metadata.document(context).orElseThrow(NotFoundException::new); + var requestOrigins = context.request().headers().getAll(HttpHeaders.ORIGIN); + context.response().headers().add(HttpHeaders.VARY, "Origin"); + if (origins.allowsOrigin(requestOrigins)) { + context + .response() + .putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestOrigins.getFirst()); + } + return document; + } +} diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/security/challenge/impl/ErrorChallengeSender.java b/src/main/java/io/stargate/sgv2/jsonapi/api/security/challenge/impl/ErrorChallengeSender.java index 76475a3ae3..c5e471ac74 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/security/challenge/impl/ErrorChallengeSender.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/security/challenge/impl/ErrorChallengeSender.java @@ -32,24 +32,35 @@ public class ErrorChallengeSender /** Object mapper for custom response. */ private final ObjectMapper objectMapper; - /** Result is always constant */ - private final CommandResult commandResult; + private final CommandResult missingTokenResult; + private final CommandResult invalidTokenResult; @Inject public ErrorChallengeSender(ObjectMapper objectMapper) { this.objectMapper = objectMapper; - commandResult = + missingTokenResult = CommandResult.statusOnlyBuilder(RequestTracing.NO_OP) .addThrowable( APISecurityException.Code.MISSING_AUTHENTICATION_TOKEN.get( "authHeader", HttpConstants.AUTHENTICATION_TOKEN_HEADER_NAME)) .build(); + invalidTokenResult = + CommandResult.statusOnlyBuilder(RequestTracing.NO_OP) + .addThrowable(APISecurityException.Code.UNAUTHENTICATED_REQUEST.get()) + .build(); } /** {@inheritDoc} */ @Override public Uni apply(RoutingContext context, ChallengeData challengeData) { + var commandResult = + context.request().getHeader(HttpHeaders.AUTHORIZATION) == null + ? missingTokenResult + : invalidTokenResult; + challengeData + .getHeaders() + .forEach((name, value) -> context.response().headers().set(name, value)); try { // try to serialize String response = objectMapper.writeValueAsString(commandResult); diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/security/configuration/HeaderBasedSecurityConfiguration.java b/src/main/java/io/stargate/sgv2/jsonapi/api/security/configuration/HeaderBasedSecurityConfiguration.java index b72c75a02e..2e20086423 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/security/configuration/HeaderBasedSecurityConfiguration.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/security/configuration/HeaderBasedSecurityConfiguration.java @@ -18,27 +18,80 @@ package io.stargate.sgv2.jsonapi.api.security.configuration; import io.quarkus.arc.lookup.LookupIfProperty; +import io.quarkus.runtime.Startup; import io.quarkus.security.identity.IdentityProvider; +import io.quarkus.smallrye.jwt.runtime.auth.MpJwtValidator; import io.quarkus.vertx.http.runtime.security.HttpAuthenticationMechanism; +import io.smallrye.jwt.auth.principal.JWTAuthContextInfo; import io.stargate.sgv2.jsonapi.api.security.HeaderAuthenticationRequest; import io.stargate.sgv2.jsonapi.api.security.HeaderBasedAuthenticationMechanism; import io.stargate.sgv2.jsonapi.api.security.HeaderIdentityProvider; +import io.stargate.sgv2.jsonapi.api.security.McpOAuthMetadata; import io.stargate.sgv2.jsonapi.api.security.challenge.impl.ErrorChallengeSender; import io.stargate.sgv2.jsonapi.config.AuthConfig; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.inject.Produces; +import jakarta.ws.rs.core.HttpHeaders; +import java.util.ArrayList; /** The configuration for the header based security. */ public class HeaderBasedSecurityConfiguration { @Produces @ApplicationScoped - @LookupIfProperty(name = "stargate.auth.header-based.enabled", stringValue = "true") + @Startup HttpAuthenticationMechanism httpAuthenticationMechanism( - AuthConfig config, Instance customChallengeSender) { - String headerName = config.headerBased().headerName(); - return new HeaderBasedAuthenticationMechanism(headerName, customChallengeSender); + AuthConfig config, + Instance customChallengeSender, + McpOAuthMetadata metadata, + JWTAuthContextInfo jwtConfig, + Instance jwtVerifier) { + if (config.bearer().enabled()) { + if (jwtVerifier.isUnsatisfied()) { + throw new IllegalStateException( + "Bearer authentication requires the SmallRye JWT verifier. Build with" + + " quarkus.smallrye-jwt.enabled=true."); + } + validateBearerConfiguration(jwtConfig, metadata.audienceFromRequestHost()); + } + return new HeaderBasedAuthenticationMechanism(config, customChallengeSender, metadata); + } + + /** + * @param audienceFromRequestHost true when {@link McpOAuthMetadata} checks each token against the + * host it was sent to, which replaces the static audience list + */ + static void validateBearerConfiguration( + JWTAuthContextInfo config, boolean audienceFromRequestHost) { + var missing = new ArrayList(); + if (!isConfigured(config.getIssuedBy())) { + missing.add("mp.jwt.verify.issuer"); + } + if (!isConfigured(config.getPublicKeyLocation()) + && !isConfigured(config.getPublicKeyContent()) + && config.getPublicVerificationKey() == null) { + missing.add("mp.jwt.verify.publickey.location or mp.jwt.verify.publickey"); + } + if (!HttpHeaders.AUTHORIZATION.equals(config.getTokenHeader())) { + // The built-in JWT mechanism reads this header on requests our mechanism leaves alone, and + // it would accept a token from a cookie there without the checks made for MCP. + missing.add("mp.jwt.token.header=Authorization"); + } + if (!audienceFromRequestHost + && (config.getExpectedAudience() == null + || config.getExpectedAudience().stream() + .noneMatch(HeaderBasedSecurityConfiguration::isConfigured))) { + missing.add("mp.jwt.verify.audiences"); + } + if (!missing.isEmpty()) { + throw new IllegalStateException( + "Bearer authentication requires " + String.join(", ", missing)); + } + } + + private static boolean isConfigured(String value) { + return value != null && !value.isBlank(); } @Produces diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/CollectionResource.java b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/CollectionResource.java index 7fbbe62563..4ab4b3bf25 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/CollectionResource.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/CollectionResource.java @@ -252,7 +252,7 @@ public Uni> postCommand( embeddingProvider = embeddingProviderFactory.create( requestContext.tenant(), - requestContext.authToken(), + requestContext.providerAuthToken(), vectorColDef.vectorizeDefinition().provider(), vectorColDef.vectorizeDefinition().modelName(), vectorColDef.vectorSize(), diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpEndpointConfigSourceFactory.java b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpEndpointConfigSourceFactory.java index d6bece2da5..5db5c72fca 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpEndpointConfigSourceFactory.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpEndpointConfigSourceFactory.java @@ -4,16 +4,18 @@ import io.smallrye.config.ConfigSourceContext; import io.smallrye.config.ConfigSourceFactory; import io.smallrye.config.PropertiesConfigSource; +import io.stargate.sgv2.jsonapi.api.security.ProtectedResourceMetadataResource; import java.net.URI; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.eclipse.microprofile.config.spi.ConfigSource; -/** Shares the normalized MCP endpoint with request logging and Quarkus access logging. */ +/** Shares normalized MCP paths with request logging and HTTP authentication. */ @StaticInitSafe public class McpEndpointConfigSourceFactory implements ConfigSourceFactory { - static final String ENDPOINT_PATH = "stargate.jsonapi.mcp.endpoint-path"; + public static final String ENDPOINT_PATH = "stargate.jsonapi.mcp.endpoint-path"; + public static final String METADATA_PATH = "stargate.jsonapi.mcp.metadata-path"; @Override public Iterable getConfigSources(ConfigSourceContext context) { @@ -37,6 +39,11 @@ public Iterable getConfigSources(ConfigSourceContext context) { } String excludePattern = Pattern.quote(endpointPath) + (endpointPath.equals("/") ? ".*" : "(/.*)?"); + String metadataPath = + URI.create(httpRoot) + .resolve(ProtectedResourceMetadataResource.PATH.substring(1)) + .normalize() + .getPath(); // A config source is needed because Quarkus creates its access logger before CDI startup. // The default source ordinal leaves explicit operator exclusions at their normal precedence. return List.of( @@ -44,8 +51,18 @@ public Iterable getConfigSources(ConfigSourceContext context) { Map.of( ENDPOINT_PATH, endpointPath, + METADATA_PATH, + metadataPath, "quarkus.http.access-log.exclude-pattern", - excludePattern), + excludePattern, + "quarkus.http.auth.permission.mcp.paths", + transportPaths(endpointPath).permissionPaths(), + "quarkus.http.auth.permission.mcp.policy", + "authenticated", + "quarkus.http.auth.permission.mcp-metadata.paths", + metadataPath, + "quarkus.http.auth.permission.mcp-metadata.policy", + "permit"), "MCP endpoint")); } @@ -70,5 +87,19 @@ public boolean matches(String normalizedPath) { && path.length() > messagesPrefix.length() && path.indexOf('/', messagesPrefix.length()) == -1); } + + public String permissionPaths() { + return String.join( + ",", + List.of( + endpoint, + endpoint.equals("/") ? endpoint : endpoint + "/", + sse, + sse + "/", + messagesPrefix + "*") + .stream() + .distinct() + .toList()); + } } } diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthScope.java b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthScope.java new file mode 100644 index 0000000000..2be57c6035 --- /dev/null +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthScope.java @@ -0,0 +1,77 @@ +package io.stargate.sgv2.jsonapi.api.v1.mcp; + +import io.stargate.sgv2.jsonapi.api.model.command.CommandName; +import java.util.Arrays; + +/** Scope required for an MCP tool in addition to the underlying database permissions. */ +enum McpOAuthScope { + READ("astra:db:read"), + WRITE("astra:db:write"), + ADMIN("astra:db:admin"); + + private final String value; + + McpOAuthScope(String value) { + this.value = value; + } + + String value() { + return value; + } + + boolean isGrantedBy(Object claim) { + if (!(claim instanceof String scope)) { + return false; + } + var granted = Arrays.asList(scope.split(" +")); + return granted.contains(value) || (this == READ && granted.contains(WRITE.value)); + } + + static McpOAuthScope requiredFor(CommandName command) { + return switch (command) { + case COUNT_DOCUMENTS, + ESTIMATED_DOCUMENT_COUNT, + FIND, + FIND_AND_RERANK, + FIND_COLLECTIONS, + FIND_EMBEDDING_PROVIDERS, + FIND_KEYSPACES, + FIND_NAMESPACES, + FIND_ONE, + FIND_RERANKING_PROVIDERS, + LIST_INDEXES, + LIST_TABLES, + LIST_TYPES -> + READ; + case DELETE_MANY, + DELETE_ONE, + FIND_ONE_AND_DELETE, + FIND_ONE_AND_REPLACE, + FIND_ONE_AND_UPDATE, + INSERT_MANY, + INSERT_ONE, + UPDATE_MANY, + UPDATE_ONE -> + WRITE; + case ALTER_TABLE, + ALTER_TYPE, + CREATE_COLLECTION, + CREATE_INDEX, + CREATE_KEYSPACE, + CREATE_NAMESPACE, + CREATE_TABLE, + CREATE_TEXT_INDEX, + CREATE_TYPE, + CREATE_VECTOR_INDEX, + DELETE_COLLECTION, + DROP_INDEX, + DROP_KEYSPACE, + DROP_NAMESPACE, + DROP_TABLE, + DROP_TYPE -> + ADMIN; + case BEGIN_OFFLINE_SESSION, END_OFFLINE_SESSION, OFFLINE_GET_STATUS, OFFLINE_INSERT_MANY -> + throw new IllegalArgumentException("Command is unavailable over MCP: " + command); + }; + } +} diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOriginFilter.java b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOriginFilter.java index 177e7bb502..c4c148f786 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOriginFilter.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOriginFilter.java @@ -75,8 +75,7 @@ void filter(RoutingContext context) { context.next(); return; } - String origin = origins.get(0); - if (origins.size() > 1 || !allowedOrigins.contains(origin)) { + if (!allowsOrigin(origins)) { response .setStatusCode(403) .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") @@ -84,6 +83,7 @@ void filter(RoutingContext context) { return; } + String origin = origins.getFirst(); if (isPreflight(request)) { response .setStatusCode(204) @@ -101,6 +101,10 @@ void filter(RoutingContext context) { context.next(); } + public boolean allowsOrigin(List origins) { + return origins.size() == 1 && allowedOrigins.contains(origins.getFirst()); + } + private static boolean isPreflight(HttpServerRequest request) { return HttpMethod.OPTIONS.equals(request.method()) && request.headers().contains(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD); diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpResource.java b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpResource.java index 29eb50ea2a..697290fca2 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpResource.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpResource.java @@ -7,6 +7,7 @@ import io.micrometer.core.instrument.MeterRegistry; import io.quarkiverse.mcp.server.Cancellation; import io.quarkiverse.mcp.server.InputRequiredException; +import io.quarkiverse.mcp.server.JsonRpcErrorCodes; import io.quarkiverse.mcp.server.McpException; import io.quarkiverse.mcp.server.ToolResponse; import io.quarkus.security.AuthenticationException; @@ -18,8 +19,11 @@ import io.stargate.sgv2.jsonapi.api.request.EmbeddingCredentialsResolver; import io.stargate.sgv2.jsonapi.api.request.RequestContext; import io.stargate.sgv2.jsonapi.api.request.tenant.RequestTenantResolver; +import io.stargate.sgv2.jsonapi.api.request.token.RequestAuthTokenResolver; +import io.stargate.sgv2.jsonapi.api.security.McpOAuthMetadata; import io.stargate.sgv2.jsonapi.config.feature.ApiFeature; import io.stargate.sgv2.jsonapi.exception.APIException; +import io.stargate.sgv2.jsonapi.exception.APISecurityException; import io.stargate.sgv2.jsonapi.exception.SchemaException; import io.stargate.sgv2.jsonapi.exception.ServerException; import io.stargate.sgv2.jsonapi.exception.mappers.FrameworkExceptionMapper; @@ -39,9 +43,12 @@ import jakarta.validation.ConstraintViolationException; import jakarta.validation.Validator; import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletionException; import java.util.function.Supplier; +import org.eclipse.microprofile.jwt.JsonWebToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,6 +63,7 @@ public class McpResource { private final ObjectMapper objectMapper; private final Validator validator; + private final McpOAuthMetadata oauthMetadata; private final MeteredCommandProcessor meteredCommandProcessor; private final CommandContext.BuilderSupplier contextBuilderSupplier; private final EmbeddingProviderFactory embeddingProviderFactory; @@ -65,12 +73,14 @@ public class McpResource { private final Provider routingContextProvider; private final Provider securityIdentityProvider; private final Instance tenantResolver; + private final Instance tokenResolver; private final Instance embeddingCredentialsResolver; @Inject public McpResource( ObjectMapper objectMapper, Validator validator, + McpOAuthMetadata oauthMetadata, MeteredCommandProcessor meteredCommandProcessor, MeterRegistry meterRegistry, JsonProcessingMetricsReporter jsonProcessingMetricsReporter, @@ -81,12 +91,14 @@ public McpResource( Provider routingContextProvider, Provider securityIdentityProvider, Instance tenantResolver, + Instance tokenResolver, Instance embeddingCredentialsResolver) { // TODO: these vars are needed to replicate what we do in GeneralResource, // KeyspaceResource, etc. We should refactor to avoid duplication later. this.objectMapper = objectMapper; this.validator = validator; + this.oauthMetadata = oauthMetadata; this.meteredCommandProcessor = meteredCommandProcessor; this.embeddingProviderFactory = embeddingProviderFactory; this.schemaObjectCacheSupplier = schemaObjectCacheSupplier; @@ -94,6 +106,7 @@ public McpResource( this.routingContextProvider = routingContextProvider; this.securityIdentityProvider = securityIdentityProvider; this.tenantResolver = tenantResolver; + this.tokenResolver = tokenResolver; this.embeddingCredentialsResolver = embeddingCredentialsResolver; this.contextBuilderSupplier = @@ -200,7 +213,7 @@ public Uni processCollectionCommand( embeddingProvider = embeddingProviderFactory.create( requestContext.tenant(), - requestContext.authToken(), + requestContext.providerAuthToken(), vectorColDef.vectorizeDefinition().provider(), vectorColDef.vectorizeDefinition().modelName(), vectorColDef.vectorSize(), @@ -235,8 +248,10 @@ public Uni processCommand( () -> { Uni> contextUni; try { + var routingContext = routingContextProvider.get(); // Mutiny captures context when callbacks are assembled. - McpRequestLogging.activate(routingContextProvider.get()); + McpRequestLogging.activate(routingContext); + requireOAuthScope(routingContext, command); var violations = validator.validate(command); if (!violations.isEmpty()) { throw new ConstraintViolationException(violations); @@ -252,13 +267,52 @@ public Uni processCommand( failure == null ? executeCommand(context, command) : handleSetupFailure(failure)) - .map(CommandResult::toToolResponse) + .map(this::toToolResponse) .invoke(result -> McpRequestLogging.commandCompleted(command, result)) .onFailure() .invoke(failure -> McpRequestLogging.commandFailed(command)); }); } + private ToolResponse toToolResponse(CommandResult result) { + if (oauthMetadata.bearerEnabled() + && result.errors().stream() + .anyMatch( + error -> + APISecurityException.Code.UNAUTHORIZED_ACCESS + .name() + .equals(error.errorCode()))) { + // The token already has the required scope. Only database permissions can grant this action. + var context = routingContextProvider.get(); + context + .response() + .setStatusCode(Response.Status.FORBIDDEN.getStatusCode()) + .putHeader( + HttpHeaders.WWW_AUTHENTICATE, oauthMetadata.challenge(context).orElse("Bearer")); + } + return result.toToolResponse(); + } + + private void requireOAuthScope(RoutingContext context, Command command) { + if (!oauthMetadata.bearerEnabled()) { + return; + } + var requiredScope = McpOAuthScope.requiredFor(command.commandName()); + if (securityIdentityProvider.get().getPrincipal() instanceof JsonWebToken jwt + && requiredScope.isGrantedBy(jwt.getClaim("scope"))) { + return; + } + + // The transport writes the JSON-RPC error using this HTTP status and challenge. + context + .response() + .setStatusCode(Response.Status.FORBIDDEN.getStatusCode()) + .putHeader( + HttpHeaders.WWW_AUTHENTICATE, + oauthMetadata.insufficientScopeChallenge(context, requiredScope.value())); + throw new McpException("Insufficient OAuth scope", JsonRpcErrorCodes.SECURITY_ERROR); + } + private Uni executeCommand(CommandContext context, Command command) { // Defer the feature check and processor call so synchronous failures still close the context. return Uni.createFrom() @@ -340,6 +394,7 @@ private RequestContext createRequestContext() { routingContextProvider.get(), securityIdentityProvider.get(), tenantResolver, + tokenResolver, embeddingCredentialsResolver); } } diff --git a/src/main/java/io/stargate/sgv2/jsonapi/config/AuthConfig.java b/src/main/java/io/stargate/sgv2/jsonapi/config/AuthConfig.java index 9cdcfa9fd1..21b52a2327 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/config/AuthConfig.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/config/AuthConfig.java @@ -38,6 +38,16 @@ public interface AuthConfig { @Valid HeaderBasedAuthConfig headerBased(); + /** Configuration for verified Bearer authentication. */ + @Valid + BearerAuthConfig bearer(); + + interface BearerAuthConfig { + + @WithDefault("false") + boolean enabled(); + } + /** Configuration for the header based authentication. */ interface HeaderBasedAuthConfig { diff --git a/src/main/java/io/stargate/sgv2/jsonapi/config/McpAuthConfig.java b/src/main/java/io/stargate/sgv2/jsonapi/config/McpAuthConfig.java new file mode 100644 index 0000000000..03c478912c --- /dev/null +++ b/src/main/java/io/stargate/sgv2/jsonapi/config/McpAuthConfig.java @@ -0,0 +1,24 @@ +package io.stargate.sgv2.jsonapi.config; + +import io.smallrye.config.ConfigMapping; +import java.net.URI; +import java.util.List; +import java.util.Optional; + +/** Public authorization discovery for the MCP endpoint. */ +@ConfigMapping(prefix = "stargate.mcp.auth") +public interface McpAuthConfig { + Optional serverUrl(); + + /** The one public origin of a deployment that serves a single host. */ + Optional publicBaseUrl(); + + /** + * The DNS suffix shared by the public hosts of a deployment that serves one host per database, + * such as {@code .apps.example.com}. Each request host is then its own resource and audience. Set + * this or {@link #publicBaseUrl()}, not both. + */ + Optional publicHostSuffix(); + + Optional> scopesSupported(); +} diff --git a/src/main/java/io/stargate/sgv2/jsonapi/service/embedding/gateway/EmbeddingGatewayClient.java b/src/main/java/io/stargate/sgv2/jsonapi/service/embedding/gateway/EmbeddingGatewayClient.java index a5f37ba0de..4fec39f590 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/service/embedding/gateway/EmbeddingGatewayClient.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/service/embedding/gateway/EmbeddingGatewayClient.java @@ -137,8 +137,10 @@ public Uni vectorize( var contextBuilder = EmbeddingGateway.ProviderEmbedRequest.ProviderContext.newBuilder() .setProviderName(modelProvider().apiName()) - .setTenantId(tenant.toString()) - .putAuthTokens(DATA_API_TOKEN, authToken); + .setTenantId(tenant.toString()); + if (authToken != null) { + contextBuilder.putAuthTokens(DATA_API_TOKEN, authToken); + } embeddingCredentials .apiKey() diff --git a/src/main/java/io/stargate/sgv2/jsonapi/service/embedding/operation/SyncServiceCredentialResolvingProvider.java b/src/main/java/io/stargate/sgv2/jsonapi/service/embedding/operation/SyncServiceCredentialResolvingProvider.java index 3070c7451f..1bd2fb9469 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/service/embedding/operation/SyncServiceCredentialResolvingProvider.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/service/embedding/operation/SyncServiceCredentialResolvingProvider.java @@ -1,5 +1,7 @@ package io.stargate.sgv2.jsonapi.service.embedding.operation; +import static io.stargate.sgv2.jsonapi.service.resolver.ValidateCredentials.requireCredentialServiceToken; + import io.smallrye.mutiny.Uni; import io.stargate.sgv2.jsonapi.api.request.EmbeddingCredentials; import io.stargate.sgv2.jsonapi.api.request.tenant.Tenant; @@ -102,6 +104,7 @@ public int maxBatchSize() { * behavior). */ private Uni resolveCredentials() { + String serviceToken = requireCredentialServiceToken(authToken); String providerName = modelProvider().apiName(); // Build parallel SyncService calls and track which accepted token name each one is for @@ -113,7 +116,7 @@ private Uni resolveCredentials() { acceptedNames.add(entry.getKey()); credNames.add(entry.getValue()); resolveUnis.add( - syncServiceClient.getCredential(authToken, tenant, providerName, entry.getValue())); + syncServiceClient.getCredential(serviceToken, tenant, providerName, entry.getValue())); } return Uni.join() diff --git a/src/main/java/io/stargate/sgv2/jsonapi/service/operation/embeddings/EmbeddingTaskBuilder.java b/src/main/java/io/stargate/sgv2/jsonapi/service/operation/embeddings/EmbeddingTaskBuilder.java index 0a39def305..530e06553f 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/service/operation/embeddings/EmbeddingTaskBuilder.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/service/operation/embeddings/EmbeddingTaskBuilder.java @@ -83,7 +83,7 @@ public EmbeddingTask build() { .embeddingProviderFactory() .create( commandContext.requestContext().tenant(), - commandContext.requestContext().authToken(), + commandContext.requestContext().providerAuthToken(), vectorizeDefinition.provider(), vectorizeDefinition.modelName(), dimension, diff --git a/src/main/java/io/stargate/sgv2/jsonapi/service/reranking/gateway/RerankingEGWClient.java b/src/main/java/io/stargate/sgv2/jsonapi/service/reranking/gateway/RerankingEGWClient.java index cb4d75099e..4a3fb58c18 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/service/reranking/gateway/RerankingEGWClient.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/service/reranking/gateway/RerankingEGWClient.java @@ -69,8 +69,10 @@ public Uni rerank( var contextBuilder = EmbeddingGateway.ProviderRerankingRequest.ProviderContext.newBuilder() .setProviderName(modelProvider().apiName()) - .setTenantId(tenant.toString()) - .putAuthTokens(DATA_API_TOKEN, authToken); + .setTenantId(tenant.toString()); + if (authToken != null) { + contextBuilder.putAuthTokens(DATA_API_TOKEN, authToken); + } if (!rerankingCredentials.apiKey().isEmpty()) { contextBuilder.putAuthTokens(RERANKING_API_KEY, rerankingCredentials.apiKey()); } diff --git a/src/main/java/io/stargate/sgv2/jsonapi/service/resolver/FindAndRerankOperationBuilder.java b/src/main/java/io/stargate/sgv2/jsonapi/service/resolver/FindAndRerankOperationBuilder.java index 684a422d4a..6f12bc93b9 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/service/resolver/FindAndRerankOperationBuilder.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/service/resolver/FindAndRerankOperationBuilder.java @@ -132,7 +132,7 @@ public Operation build() { .rerankingProviderFactory() .create( commandContext.requestContext().tenant(), - commandContext.requestContext().authToken(), + commandContext.requestContext().providerAuthToken(), rerankServiceDef.provider(), rerankServiceDef.modelName(), rerankServiceDef.authentication(), diff --git a/src/main/java/io/stargate/sgv2/jsonapi/service/resolver/ValidateCredentials.java b/src/main/java/io/stargate/sgv2/jsonapi/service/resolver/ValidateCredentials.java index e3f692ae26..0e6fbdd1f7 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/service/resolver/ValidateCredentials.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/service/resolver/ValidateCredentials.java @@ -25,7 +25,16 @@ public class ValidateCredentials { @Inject RequestContext dataApiRequestInfo; + public static String requireCredentialServiceToken(String token) { + if (token == null) { + throw SchemaException.Code.VECTORIZE_CREDENTIAL_INVALID.get( + Map.of("errorMessage", "Stored provider credentials require a separate service token.")); + } + return token; + } + public boolean validate(String provider, String value) { + String token = requireCredentialServiceToken(dataApiRequestInfo.providerAuthToken()); if (channel == null) { channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); } @@ -34,7 +43,7 @@ public boolean validate(String provider, String value) { validateCredentialRequest.setCredential(value); validateCredentialRequest.setTenantId(dataApiRequestInfo.tenant().toString()); validateCredentialRequest.setProviderName(provider); - validateCredentialRequest.setToken(dataApiRequestInfo.authToken()); + validateCredentialRequest.setToken(token); EmbeddingServiceGrpc.EmbeddingServiceBlockingStub embeddingService = EmbeddingServiceGrpc.newBlockingStub(channel); final EmbeddingGateway.ValidateCredentialResponse validateCredentialResponse = diff --git a/src/main/java/io/stargate/sgv2/jsonapi/syncservice/SyncServiceClient.java b/src/main/java/io/stargate/sgv2/jsonapi/syncservice/SyncServiceClient.java index 0980c84673..ddac6f9edc 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/syncservice/SyncServiceClient.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/syncservice/SyncServiceClient.java @@ -1,5 +1,7 @@ package io.stargate.sgv2.jsonapi.syncservice; +import static io.stargate.sgv2.jsonapi.service.resolver.ValidateCredentials.requireCredentialServiceToken; + import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -42,7 +44,10 @@ public class SyncServiceClient { */ public void validateKey(String provider, String key) { validateKeyAsync( - dataApiRequestInfo.authToken(), dataApiRequestInfo.tenant().toString(), provider, key) + requireCredentialServiceToken(dataApiRequestInfo.providerAuthToken()), + dataApiRequestInfo.tenant().toString(), + provider, + key) .await() .atMost(Duration.ofSeconds(10)); } diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 0c733d09b6..32c321246e 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -89,15 +89,21 @@ quarkus: pattern: "%h %l %t \"%r\" %s %b" # McpEndpointConfigSourceFactory excludes the effective MCP path from access logs. - # every /v1 path is authenticated by default + # every v1 path under the HTTP root is authenticated by default # adapt if changing the authentication mechanism auth: # disable basic auth completely basic: false proactive: false permission: + # Require Data API identities alongside the route's own authorization policy. + data-api-auth: + paths: v1/*,${quarkus.http.auth.permission.mcp.paths} + auth-mechanism: data-api + shared: true + policy: data-api default: - paths: /v1/* + paths: v1/* policy: authenticated limits: diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/request/token/PrincipalTokenResolverTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/request/token/PrincipalTokenResolverTest.java new file mode 100644 index 0000000000..32f2a86bb0 --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/request/token/PrincipalTokenResolverTest.java @@ -0,0 +1,32 @@ +package io.stargate.sgv2.jsonapi.api.request.token; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.eclipse.microprofile.jwt.JsonWebToken; +import org.junit.jupiter.api.Test; + +class PrincipalTokenResolverTest { + + private final PrincipalTokenResolver resolver = new PrincipalTokenResolver(); + + @Test + void preservesRawJwtInsteadOfItsSubject() { + var principal = mock(JsonWebToken.class); + when(principal.getName()).thenReturn("client-id"); + when(principal.getRawToken()).thenReturn("signed-access-token"); + + assertThat(resolver.resolve(null, principal)).isEqualTo("signed-access-token"); + } + + @Test + void preservesLegacyPrincipalCredentials() { + assertThat(resolver.resolve(null, () -> "legacy-token")).isEqualTo("legacy-token"); + } + + @Test + void anonymousPrincipalHasNoCredential() { + assertThat(resolver.resolve(null, null)).isNull(); + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/security/DataApiAuthenticationPolicyTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/security/DataApiAuthenticationPolicyTest.java new file mode 100644 index 0000000000..262ef8f450 --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/security/DataApiAuthenticationPolicyTest.java @@ -0,0 +1,42 @@ +package io.stargate.sgv2.jsonapi.api.security; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.quarkus.security.StringPermission; +import io.quarkus.security.identity.SecurityIdentity; +import io.quarkus.security.runtime.QuarkusSecurityIdentity; +import io.smallrye.mutiny.Uni; +import org.junit.jupiter.api.Test; + +class DataApiAuthenticationPolicyTest { + @Test + void acceptsTheDataApiIdentityWithItsExistingPermissions() { + var read = new StringPermission("read"); + var identity = + QuarkusSecurityIdentity.builder().setPrincipal(() -> "user").addPermission(read).build(); + + var authenticated = DataApiAuthenticationPolicy.authenticatedIdentity(identity); + assertThat(isPermitted(authenticated)).isTrue(); + assertThat(authenticated.getPermissions()).containsExactly(read); + } + + @Test + void leavesAnonymousAccessToTheRoutePermission() { + var identity = QuarkusSecurityIdentity.builder().setAnonymous(true).build(); + assertThat(isPermitted(identity)).isTrue(); + } + + @Test + void rejectsAnIdentityFromAnotherMechanism() { + var identity = QuarkusSecurityIdentity.builder().setPrincipal(() -> "other-user").build(); + assertThat(isPermitted(identity)).isFalse(); + } + + private static boolean isPermitted(SecurityIdentity identity) { + return new DataApiAuthenticationPolicy() + .checkPermission(null, Uni.createFrom().item(identity), null) + .await() + .indefinitely() + .isPermitted(); + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/security/HeaderBasedAuthenticationMechanismTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/security/HeaderBasedAuthenticationMechanismTest.java new file mode 100644 index 0000000000..89d7e02a25 --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/security/HeaderBasedAuthenticationMechanismTest.java @@ -0,0 +1,328 @@ +package io.stargate.sgv2.jsonapi.api.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.quarkus.security.AuthenticationFailedException; +import io.quarkus.security.identity.IdentityProviderManager; +import io.quarkus.security.identity.SecurityIdentity; +import io.quarkus.security.identity.request.AuthenticationRequest; +import io.quarkus.security.identity.request.TokenAuthenticationRequest; +import io.quarkus.security.runtime.QuarkusSecurityIdentity; +import io.quarkus.vertx.http.runtime.security.HttpAuthenticationMechanism; +import io.smallrye.mutiny.Uni; +import io.stargate.sgv2.jsonapi.api.security.challenge.impl.ErrorChallengeSender; +import io.stargate.sgv2.jsonapi.config.AuthConfig; +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.ext.web.RoutingContext; +import jakarta.enterprise.inject.Instance; +import jakarta.ws.rs.core.HttpHeaders; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import org.eclipse.microprofile.jwt.JsonWebToken; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +class HeaderBasedAuthenticationMechanismTest { + + @Test + void bearerCredentialsReachTheJwtProviderBeforeLegacyHeaders() { + var manager = mock(IdentityProviderManager.class); + var identity = jwtIdentity(Set.of("https://db-one.apps.example.test/v1/mcp")); + when(manager.authenticate(any())).thenReturn(Uni.createFrom().item(identity)); + var mechanism = mechanism(true, true); + var context = context(Map.of("Authorization", "Bearer encoded-jwt", "Token", "legacy-token")); + + var authenticated = mechanism.authenticate(context, manager).await().indefinitely(); + assertThat(authenticated.getPrincipal()).isSameAs(identity.getPrincipal()); + + var request = ArgumentCaptor.forClass(AuthenticationRequest.class); + verify(manager).authenticate(request.capture()); + assertThat(request.getValue()).isInstanceOf(TokenAuthenticationRequest.class); + assertThat(((TokenAuthenticationRequest) request.getValue()).getToken().getToken()) + .isEqualTo("encoded-jwt"); + verify(context).put(HttpAuthenticationMechanism.class.getName(), mechanism); + } + + @ParameterizedTest + @ValueSource(strings = {"Bearer", "Bearer ", "Bearer\tencoded-jwt", "Basic encoded"}) + void malformedAuthorizationCannotFallBackToALegacyHeader(String authorization) { + var manager = mock(IdentityProviderManager.class); + var context = context(Map.of("Authorization", authorization, "Token", "legacy-token")); + var mechanism = mechanism(true, true); + + assertThatThrownBy(() -> mechanism.authenticate(context, manager).await().indefinitely()) + .isInstanceOf(AuthenticationFailedException.class); + verify(context).put(HttpAuthenticationMechanism.class.getName(), mechanism); + verifyNoInteractions(manager); + } + + @Test + void providerFailureCannotFallBackToALegacyHeader() { + var manager = mock(IdentityProviderManager.class); + when(manager.authenticate(any())) + .thenReturn(Uni.createFrom().failure(new AuthenticationFailedException())); + var context = context(Map.of("Authorization", "Bearer invalid-jwt", "Token", "legacy-token")); + var mechanism = mechanism(true, true); + + assertThatThrownBy(() -> mechanism.authenticate(context, manager).await().indefinitely()) + .isInstanceOf(AuthenticationFailedException.class); + verify(context).put(HttpAuthenticationMechanism.class.getName(), mechanism); + var request = ArgumentCaptor.forClass(AuthenticationRequest.class); + verify(manager).authenticate(request.capture()); + assertThat(request.getValue()).isInstanceOf(TokenAuthenticationRequest.class); + } + + @Test + void rejectedBearerIncludesTheChallengeBeforeTheMcpTransportWritesItsError() { + var manager = mock(IdentityProviderManager.class); + when(manager.authenticate(any())) + .thenReturn(Uni.createFrom().failure(new AuthenticationFailedException())); + var context = context(Map.of("Authorization", "Bearer invalid-jwt")); + var response = mock(HttpServerResponse.class); + when(context.response()).thenReturn(response); + var metadata = mock(McpOAuthMetadata.class); + String challenge = + "Bearer" + + " resource_metadata=\"https://data.example.test/.well-known/oauth-protected-resource\""; + when(metadata.isMcpRequest(context)).thenReturn(true); + when(metadata.challenge(context)).thenReturn(Optional.of(challenge)); + var mechanism = + new HeaderBasedAuthenticationMechanism(authConfig(true, true), instance(), metadata); + + assertThatThrownBy(() -> mechanism.authenticate(context, manager).await().indefinitely()) + .isInstanceOf(AuthenticationFailedException.class); + verify(response).putHeader(HttpHeaders.WWW_AUTHENTICATE, challenge); + } + + @Test + void bearerIssuedForAnotherResourceIsRejectedWithTheChallenge() { + var manager = mock(IdentityProviderManager.class); + var audience = Set.of("https://db-two.apps.example.test/v1/mcp"); + var identity = jwtIdentity(audience); + when(manager.authenticate(any())).thenReturn(Uni.createFrom().item(identity)); + var context = context(Map.of("Authorization", "Bearer encoded-jwt")); + var response = mock(HttpServerResponse.class); + when(context.response()).thenReturn(response); + var metadata = mock(McpOAuthMetadata.class); + String challenge = + "Bearer" + + " resource_metadata=\"https://db-one.apps.example.test/.well-known/oauth-protected-resource\""; + when(metadata.isMcpRequest(context)).thenReturn(true); + when(metadata.challenge(context)).thenReturn(Optional.of(challenge)); + when(metadata.acceptsAudience(context, audience)).thenReturn(false); + var mechanism = + new HeaderBasedAuthenticationMechanism(authConfig(true, true), instance(), metadata); + + assertThatThrownBy(() -> mechanism.authenticate(context, manager).await().indefinitely()) + .isInstanceOf(AuthenticationFailedException.class); + verify(metadata).acceptsAudience(context, audience); + verify(response).putHeader(HttpHeaders.WWW_AUTHENTICATE, challenge); + } + + @Test + void bearerIssuedForTheRequestedResourceAuthenticates() { + var manager = mock(IdentityProviderManager.class); + var audience = Set.of("https://db-one.apps.example.test/v1/mcp"); + var identity = jwtIdentity(audience); + when(manager.authenticate(any())).thenReturn(Uni.createFrom().item(identity)); + var context = context(Map.of("Authorization", "Bearer encoded-jwt")); + var metadata = mock(McpOAuthMetadata.class); + when(metadata.isMcpRequest(context)).thenReturn(true); + when(metadata.acceptsAudience(context, audience)).thenReturn(true); + var mechanism = + new HeaderBasedAuthenticationMechanism(authConfig(true, true), instance(), metadata); + + var authenticated = mechanism.authenticate(context, manager).await().indefinitely(); + assertThat(authenticated.getPrincipal()).isSameAs(identity.getPrincipal()); + } + + @Test + void legacyCredentialsSkipTheBearerAudienceCheck() { + var manager = mock(IdentityProviderManager.class); + var identity = legacyIdentity(); + when(manager.authenticate(any())).thenReturn(Uni.createFrom().item(identity)); + var metadata = mock(McpOAuthMetadata.class); + var mechanism = + new HeaderBasedAuthenticationMechanism(authConfig(true, true), instance(), metadata); + + var context = context(Map.of("Token", "legacy-token")); + var authenticated = mechanism.authenticate(context, manager).await().indefinitely(); + assertThat(authenticated.getPrincipal()).isSameAs(identity.getPrincipal()); + verify(metadata, never()).acceptsAudience(any(), any()); + } + + @Test + void disabledBearerAuthenticationPreservesLegacyHeaderPrecedence() { + var manager = mock(IdentityProviderManager.class); + var identity = legacyIdentity(); + when(manager.authenticate(any())).thenReturn(Uni.createFrom().item(identity)); + var context = context(Map.of("Authorization", "Bearer invalid-jwt", "Token", "legacy-token")); + + var authenticated = + mechanism(false, true).authenticate(context, manager).await().indefinitely(); + assertThat(authenticated.getPrincipal()).isSameAs(identity.getPrincipal()); + var request = ArgumentCaptor.forClass(AuthenticationRequest.class); + verify(manager).authenticate(request.capture()); + assertThat(request.getValue()).isInstanceOf(HeaderAuthenticationRequest.class); + } + + @Test + void disabledBearerAuthenticationStopsTheNativeJwtMechanism() { + var manager = mock(IdentityProviderManager.class); + var context = context(Map.of("Authorization", "Bearer encoded-jwt")); + + assertThatThrownBy( + () -> mechanism(false, true).authenticate(context, manager).await().indefinitely()) + .isInstanceOf(AuthenticationFailedException.class); + verifyNoInteractions(manager); + } + + @ParameterizedTest + @ValueSource(strings = {"Token", "token", "X-Cassandra-Token"}) + void enabledMcpOAuthRejectsLegacyCredentials(String header) { + var manager = mock(IdentityProviderManager.class); + var context = context(Map.of(header, "legacy-token")); + + assertThatThrownBy( + () -> mechanism(true, true).authenticate(context, manager).await().indefinitely()) + .isInstanceOf(AuthenticationFailedException.class); + verifyNoInteractions(manager); + } + + @Test + void enabledMcpOAuthRequiresBearerCredentials() { + var manager = mock(IdentityProviderManager.class); + + assertThatThrownBy( + () -> + mechanism(true, true) + .authenticate(context(Map.of()), manager) + .await() + .indefinitely()) + .isInstanceOf(AuthenticationFailedException.class); + verifyNoInteractions(manager); + } + + @Test + void enabledMcpOAuthPreservesLegacyHeaderPrecedenceOnRestPaths() { + var manager = mock(IdentityProviderManager.class); + var identity = legacyIdentity(); + when(manager.authenticate(any())).thenReturn(Uni.createFrom().item(identity)); + var context = context(Map.of("Authorization", "Bearer synthetic-jwt", "Token", "legacy-token")); + + var authenticated = + mechanism(true, true, false).authenticate(context, manager).await().indefinitely(); + assertThat(authenticated.getPrincipal()).isSameAs(identity.getPrincipal()); + var request = ArgumentCaptor.forClass(AuthenticationRequest.class); + verify(manager).authenticate(request.capture()); + assertThat(request.getValue()).isInstanceOf(HeaderAuthenticationRequest.class); + } + + @Test + void enabledMcpOAuthDoesNotEnableBearerAuthenticationOnRestPaths() { + var manager = mock(IdentityProviderManager.class); + var context = context(Map.of("Authorization", "Bearer encoded-jwt")); + + assertThatThrownBy( + () -> + mechanism(true, true, false).authenticate(context, manager).await().indefinitely()) + .isInstanceOf(AuthenticationFailedException.class); + verifyNoInteractions(manager); + } + + @Test + void disabledLegacyHeadersDoNotAuthenticate() { + var manager = mock(IdentityProviderManager.class); + + assertThat( + mechanism(true, false, false) + .authenticate(context(Map.of("Token", "legacy-token")), manager) + .await() + .indefinitely()) + .isNull(); + verifyNoInteractions(manager); + } + + @Test + void coordinatesTheChallengeAheadOfTheNativeJwtMechanism() { + var mechanism = mechanism(true, true); + assertThat(mechanism.getPriority()).isGreaterThan(1000); + assertThat(mechanism.getCredentialTypes()) + .contains(TokenAuthenticationRequest.class, HeaderAuthenticationRequest.class); + } + + @Test + void challengeUsesTheConfiguredMetadata() { + var config = authConfig(true, true); + var metadata = mock(McpOAuthMetadata.class); + var context = context(Map.of()); + var challenge = + "Bearer" + + " resource_metadata=\"https://data.example.test/.well-known/oauth-protected-resource\""; + when(metadata.challenge(context)).thenReturn(Optional.of(challenge)); + var mechanism = new HeaderBasedAuthenticationMechanism(config, instance(), metadata); + + var result = mechanism.getChallenge(context).await().indefinitely(); + assertThat(result.status).isEqualTo(401); + assertThat(result.getHeaders()).containsEntry(HttpHeaders.WWW_AUTHENTICATE, challenge); + } + + private static HeaderBasedAuthenticationMechanism mechanism(boolean bearer, boolean legacy) { + return mechanism(bearer, legacy, true); + } + + private static HeaderBasedAuthenticationMechanism mechanism( + boolean bearer, boolean legacy, boolean mcpRequest) { + var metadata = mock(McpOAuthMetadata.class); + when(metadata.isMcpRequest(any())).thenReturn(mcpRequest); + when(metadata.challenge(any())).thenReturn(Optional.empty()); + when(metadata.acceptsAudience(any(), any())).thenReturn(true); + return new HeaderBasedAuthenticationMechanism(authConfig(bearer, legacy), instance(), metadata); + } + + private static AuthConfig authConfig(boolean bearer, boolean legacy) { + var config = mock(AuthConfig.class); + var headerConfig = mock(AuthConfig.HeaderBasedAuthConfig.class); + var bearerConfig = mock(AuthConfig.BearerAuthConfig.class); + when(config.headerBased()).thenReturn(headerConfig); + when(headerConfig.enabled()).thenReturn(legacy); + when(headerConfig.headerName()).thenReturn("Token"); + when(config.bearer()).thenReturn(bearerConfig); + when(bearerConfig.enabled()).thenReturn(bearer); + return config; + } + + private static RoutingContext context(Map headers) { + var request = mock(HttpServerRequest.class); + when(request.getHeader(any(String.class))).thenAnswer(call -> headers.get(call.getArgument(0))); + var context = mock(RoutingContext.class); + when(context.request()).thenReturn(request); + return context; + } + + private static SecurityIdentity jwtIdentity(Set audience) { + var token = mock(JsonWebToken.class); + when(token.getAudience()).thenReturn(audience); + return QuarkusSecurityIdentity.builder().setPrincipal(token).build(); + } + + private static SecurityIdentity legacyIdentity() { + return QuarkusSecurityIdentity.builder().setPrincipal(() -> "legacy-token").build(); + } + + @SuppressWarnings("unchecked") + private static Instance instance() { + return mock(Instance.class); + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/security/McpOAuthMetadataTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/security/McpOAuthMetadataTest.java new file mode 100644 index 0000000000..acc90cfbb5 --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/security/McpOAuthMetadataTest.java @@ -0,0 +1,399 @@ +package io.stargate.sgv2.jsonapi.api.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.smallrye.jwt.auth.principal.JWTAuthContextInfo; +import io.stargate.sgv2.jsonapi.config.AuthConfig; +import io.stargate.sgv2.jsonapi.config.McpAuthConfig; +import io.stargate.sgv2.jsonapi.config.feature.ApiFeature; +import io.stargate.sgv2.jsonapi.config.feature.FeaturesConfig; +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.net.HostAndPort; +import io.vertx.ext.web.RoutingContext; +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +class McpOAuthMetadataTest { + private static final String PUBLIC_BASE = "https://data.example.test"; + private static final String AUTH_SERVER = "https://auth.example.test/oauth"; + private static final String ENDPOINT = "/v1/mcp"; + private static final String METADATA = ProtectedResourceMetadataResource.PATH; + private static final String HOST_SUFFIX = ".apps.example.test"; + private static final String DATABASE_HOST = "db-one-us-east-2.apps.example.test"; + private static final String DATABASE_RESOURCE = "https://" + DATABASE_HOST + ENDPOINT; + + @Test + void serializesConfiguredResourceAndOmitsUnconfiguredScopes() throws Exception { + var metadata = + metadata(config(PUBLIC_BASE), ENDPOINT, METADATA, true, true, PUBLIC_BASE + ENDPOINT); + var mapper = new ObjectMapper(); + JsonNode actual = mapper.valueToTree(metadata.document(request(ENDPOINT)).orElseThrow()); + assertThat(actual) + .isEqualTo( + mapper.readTree( + """ + { + "resource": "https://data.example.test/v1/mcp", + "authorization_servers": ["https://auth.example.test/oauth"], + "bearer_methods_supported": ["header"] + } + """)); + } + + @Test + void publishesOnlyConfiguredScopes() { + var config = config(PUBLIC_BASE); + when(config.scopesSupported()).thenReturn(Optional.of(List.of("db:read", "db:write"))); + assertThat( + metadata(config, ENDPOINT, METADATA, true, true, PUBLIC_BASE + ENDPOINT) + .document(request(ENDPOINT)) + .orElseThrow() + .scopesSupported()) + .containsExactly("db:read", "db:write"); + } + + @Test + void sharesTheEffectiveEndpointAndHttpRootWithChallenges() { + var metadata = + metadata( + config(PUBLIC_BASE), + "/service/tools", + "/service" + METADATA, + true, + true, + PUBLIC_BASE + "/service/tools"); + assertThat(metadata.document(request(ENDPOINT)).orElseThrow().resource()) + .isEqualTo(URI.create(PUBLIC_BASE + "/service/tools")); + assertThat(metadata.challenge(request("/service/tools"))) + .contains("Bearer resource_metadata=\"" + PUBLIC_BASE + "/service" + METADATA + "\""); + assertThat(metadata.challenge(request("/service/tools/sse"))).isPresent(); + assertThat(metadata.challenge(request("/service/tools/messages/session-id"))).isPresent(); + assertThat(metadata.challenge(request("/service/tools/collections"))).isEmpty(); + assertThat(metadata.challenge(request("/service/toolsmith"))).isEmpty(); + assertThat(metadata.challenge(request("/v1/collections"))).isEmpty(); + } + + @Test + void disabledFeaturesDoNotRequireOrAdvertiseAuthorizationConfiguration() { + var missing = mock(McpAuthConfig.class); + for (boolean bearerEnabled : List.of(false, true)) { + var metadata = metadata(missing, ENDPOINT, METADATA, bearerEnabled, false); + assertThat(metadata.document(request(ENDPOINT))).isEmpty(); + assertThat(metadata.challenge(mock(RoutingContext.class))).isEmpty(); + } + assertThat(metadata(missing, ENDPOINT, METADATA, false, true).document(request(ENDPOINT))) + .isEmpty(); + } + + @ParameterizedTest + @ValueSource(strings = {"/", "/service"}) + void oauthRejectsEndpointsAtTheHttpRootEvenWhenMcpIsDisabled(String endpoint) { + String metadataPath = (endpoint.equals("/") ? "" : endpoint) + METADATA; + var missing = mock(McpAuthConfig.class); + for (boolean mcpEnabled : List.of(false, true)) { + assertThatIllegalArgumentException() + .isThrownBy(() -> metadata(missing, endpoint, metadataPath, true, mcpEnabled)) + .withMessageContaining("quarkus.mcp.server.http.root-path") + .withMessageContaining("dedicated path below the HTTP root"); + assertThat( + metadata(missing, endpoint, metadataPath, false, mcpEnabled) + .document(request(ENDPOINT))) + .isEmpty(); + } + } + + @ParameterizedTest + @ValueSource(strings = {"/other/tools", "/service-sibling/tools"}) + void oauthRejectsEndpointsOutsideTheHttpRoot(String endpoint) { + var missing = mock(McpAuthConfig.class); + for (boolean mcpEnabled : List.of(false, true)) { + assertThatIllegalArgumentException() + .isThrownBy(() -> metadata(missing, endpoint, "/service" + METADATA, true, mcpEnabled)) + .withMessageContaining("below the HTTP root"); + } + assertThat( + metadata(missing, endpoint, "/service" + METADATA, false, true) + .document(request(ENDPOINT))) + .isEmpty(); + } + + @Test + void identifiesTransportPathsEvenWhenDiscoveryIsDisabled() { + var metadata = metadata(mock(McpAuthConfig.class), ENDPOINT, METADATA, false, false); + assertThat(metadata.document(request(ENDPOINT))).isEmpty(); + assertThat(metadata.isMcpRequest(request(ENDPOINT))).isTrue(); + assertThat(metadata.isMcpRequest(request("/v1/collections"))).isFalse(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "http://data.example.test", + "https://data.example.test/path", + "https://user:data@data.example.test", + "https://data.example.test?secret=value", + "https://data.example.test#fragment", + "/relative" + }) + void rejectsUntrustedPublicOriginsWithoutEchoingTheirValues(String publicBase) { + assertThatIllegalArgumentException() + .isThrownBy(() -> metadata(config(publicBase), ENDPOINT, METADATA, true, true)) + .withMessageContaining("stargate.mcp.auth.public-base-url") + .withMessageNotContaining(publicBase); + } + + @ParameterizedTest + @ValueSource(strings = {"http://localhost:8083", "http://127.0.0.1:8083", "http://[::1]:8083"}) + void acceptsLoopbackHttpForLocalDevelopment(String publicBase) { + assertThat( + metadata(config(publicBase), ENDPOINT, METADATA, true, true, publicBase + ENDPOINT) + .document(request(ENDPOINT)) + .orElseThrow() + .resource()) + .isEqualTo(URI.create(publicBase + ENDPOINT)); + } + + @Test + void requiresDiscoveryAndAudienceConfigurationWhenEnabled() { + var missingBase = config(PUBLIC_BASE); + when(missingBase.publicBaseUrl()).thenReturn(Optional.empty()); + assertThatIllegalArgumentException() + .isThrownBy(() -> metadata(missingBase, ENDPOINT, METADATA, true, true)) + .withMessageContaining( + "stargate.mcp.auth.public-base-url or stargate.mcp.auth.public-host-suffix is required"); + var missingServer = config(PUBLIC_BASE); + when(missingServer.serverUrl()).thenReturn(Optional.empty()); + assertThatIllegalArgumentException() + .isThrownBy(() -> metadata(missingServer, ENDPOINT, METADATA, true, true)) + .withMessageContaining("stargate.mcp.auth.server-url is required"); + assertThatIllegalArgumentException() + .isThrownBy(() -> metadata(config(PUBLIC_BASE), ENDPOINT, METADATA, true, true)) + .withMessageContaining("mp.jwt.verify.audiences"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + metadata( + config(PUBLIC_BASE), + ENDPOINT, + METADATA, + true, + true, + "https://other.example.test")) + .withMessageContaining("mp.jwt.verify.audiences"); + } + + @Test + void hostSuffixPublishesEachRequestHostAsItsOwnResource() throws Exception { + var metadata = metadata(hostConfig(HOST_SUFFIX), ENDPOINT, METADATA, true, true); + var mapper = new ObjectMapper(); + JsonNode actual = + mapper.valueToTree(metadata.document(request(METADATA, DATABASE_HOST, -1)).orElseThrow()); + assertThat(actual) + .isEqualTo( + mapper.readTree( + """ + { + "resource": "https://db-one-us-east-2.apps.example.test/v1/mcp", + "authorization_servers": ["https://auth.example.test/oauth"], + "bearer_methods_supported": ["header"] + } + """)); + assertThat(metadata.challenge(request(ENDPOINT, DATABASE_HOST, -1))) + .contains("Bearer resource_metadata=\"https://" + DATABASE_HOST + METADATA + "\""); + assertThat( + metadata + .document(request(METADATA, "db-two-eu-west-1.apps.example.test", -1)) + .orElseThrow() + .resource()) + .isEqualTo(URI.create("https://db-two-eu-west-1.apps.example.test/v1/mcp")); + } + + @Test + void hostSuffixUsesTheCanonicalHostAndKeepsANonDefaultPort() { + var metadata = metadata(hostConfig(HOST_SUFFIX), ENDPOINT, METADATA, true, true); + assertThat( + metadata + .document(request(METADATA, "DB-One-US-East-2.Apps.Example.Test", 443)) + .orElseThrow() + .resource()) + .isEqualTo(URI.create(DATABASE_RESOURCE)); + assertThat(metadata.document(request(METADATA, DATABASE_HOST, 8443)).orElseThrow().resource()) + .isEqualTo(URI.create("https://" + DATABASE_HOST + ":8443" + ENDPOINT)); + } + + @ParameterizedTest + @NullSource + @ValueSource( + strings = { + "data.example.test", + "apps.example.test", + ".apps.example.test", + "db-one.other.apps.example.test", + "db-one-us-east-2.apps.example.test.attacker.test", + "db-one-us-east-2.apps.example.test.", + "-db-one.apps.example.test", + "db-one-.apps.example.test", + "db_one.apps.example.test", + "db-one-us-east-2xapps.example.test" + }) + void hostSuffixRejectsHostsItDoesNotServe(String host) { + var metadata = metadata(hostConfig(HOST_SUFFIX), ENDPOINT, METADATA, true, true); + assertThat(metadata.document(request(METADATA, host, -1))).isEmpty(); + assertThat(metadata.challenge(request(ENDPOINT, host, -1))).isEmpty(); + assertThat( + metadata.acceptsAudience( + request(ENDPOINT, host, -1), Set.of("https://" + host + ENDPOINT))) + .isFalse(); + } + + @Test + void hostSuffixAcceptsOnlyTokensIssuedForTheRequestedDatabase() { + var metadata = metadata(hostConfig(HOST_SUFFIX), ENDPOINT, METADATA, true, true); + var request = request(ENDPOINT, DATABASE_HOST, -1); + assertThat(metadata.audienceFromRequestHost()).isTrue(); + assertThat(metadata.acceptsAudience(request, Set.of(DATABASE_RESOURCE))).isTrue(); + assertThat(metadata.acceptsAudience(request, Set.of("another-audience", DATABASE_RESOURCE))) + .isFalse(); + assertThat( + metadata.acceptsAudience( + request, Set.of("https://db-two-eu-west-1.apps.example.test/v1/mcp"))) + .isFalse(); + // The audience names the MCP endpoint, not only the database host. + assertThat(metadata.acceptsAudience(request, Set.of("https://" + DATABASE_HOST))).isFalse(); + assertThat(metadata.acceptsAudience(request, Set.of())).isFalse(); + assertThat(metadata.acceptsAudience(request, null)).isFalse(); + } + + @Test + void hostSuffixChecksTheAudienceWhenMcpIsNotEnabledInServerConfiguration() { + // A request header can still enable MCP, so the audience rule cannot depend on discovery. + var metadata = metadata(hostConfig(HOST_SUFFIX), ENDPOINT, METADATA, true, false); + var request = request(ENDPOINT, DATABASE_HOST, -1); + assertThat(metadata.document(request)).isEmpty(); + assertThat(metadata.challenge(request)).isEmpty(); + assertThat(metadata.acceptsAudience(request, Set.of(DATABASE_RESOURCE))).isTrue(); + assertThat(metadata.acceptsAudience(request, Set.of("https://other.example.test/v1/mcp"))) + .isFalse(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void fixedPublicBaseAcceptsOnlyItsMcpResource(boolean mcpEnabled) { + String resource = PUBLIC_BASE + ENDPOINT; + String otherAudience = "https://other.example.test/v1/mcp"; + var metadata = + metadata( + config(PUBLIC_BASE), ENDPOINT, METADATA, true, mcpEnabled, resource, otherAudience); + var request = request(ENDPOINT); + assertThat(metadata.audienceFromRequestHost()).isFalse(); + assertThat(metadata.acceptsAudience(request, Set.of(resource))).isTrue(); + assertThat(metadata.acceptsAudience(request, Set.of(otherAudience))).isFalse(); + assertThat(metadata.acceptsAudience(request, Set.of(resource, otherAudience))).isFalse(); + assertThat(metadata.acceptsAudience(request, null)).isFalse(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "apps.example.test", + "..", + ".test", + ".apps.example.test.", + ".Apps.Example.Test", + "*.apps.example.test", + ".apps..example.test", + ".apps.example.test:8443", + ".apps.example.test/path", + "https://.apps.example.test", + ".-apps.example.test" + }) + void rejectsMalformedHostSuffixesWithoutEchoingTheirValues(String suffix) { + for (boolean mcpEnabled : List.of(false, true)) { + assertThatIllegalArgumentException() + .isThrownBy(() -> metadata(hostConfig(suffix), ENDPOINT, METADATA, true, mcpEnabled)) + .withMessageContaining("stargate.mcp.auth.public-host-suffix") + .withMessageNotContaining(suffix); + } + } + + @Test + void rejectsAFixedPublicBaseTogetherWithAHostSuffix() { + var both = config(PUBLIC_BASE); + when(both.publicHostSuffix()).thenReturn(Optional.of(HOST_SUFFIX)); + assertThatIllegalArgumentException() + .isThrownBy(() -> metadata(both, ENDPOINT, METADATA, true, true, PUBLIC_BASE + ENDPOINT)) + .withMessageContaining("stargate.mcp.auth.public-base-url") + .withMessageContaining("stargate.mcp.auth.public-host-suffix"); + } + + @Test + void hostSuffixStillRequiresAnAuthorizationServer() { + var missingServer = hostConfig(HOST_SUFFIX); + when(missingServer.serverUrl()).thenReturn(Optional.empty()); + assertThatIllegalArgumentException() + .isThrownBy(() -> metadata(missingServer, ENDPOINT, METADATA, true, true)) + .withMessageContaining("stargate.mcp.auth.server-url is required"); + } + + private McpAuthConfig config(String publicBase) { + var config = mock(McpAuthConfig.class); + when(config.publicBaseUrl()).thenReturn(Optional.of(URI.create(publicBase))); + when(config.serverUrl()).thenReturn(Optional.of(URI.create(AUTH_SERVER))); + when(config.scopesSupported()).thenReturn(Optional.empty()); + return config; + } + + private McpAuthConfig hostConfig(String hostSuffix) { + var config = mock(McpAuthConfig.class); + when(config.publicBaseUrl()).thenReturn(Optional.empty()); + when(config.publicHostSuffix()).thenReturn(Optional.of(hostSuffix)); + when(config.serverUrl()).thenReturn(Optional.of(URI.create(AUTH_SERVER))); + when(config.scopesSupported()).thenReturn(Optional.empty()); + return config; + } + + private McpOAuthMetadata metadata( + McpAuthConfig config, + String endpoint, + String metadataPath, + boolean bearerEnabled, + boolean mcpEnabled, + String... audiences) { + var auth = mock(AuthConfig.class); + var bearer = mock(AuthConfig.BearerAuthConfig.class); + when(auth.bearer()).thenReturn(bearer); + when(bearer.enabled()).thenReturn(bearerEnabled); + var features = mock(FeaturesConfig.class); + when(features.flags()).thenReturn(Map.of(ApiFeature.MCP, Boolean.toString(mcpEnabled))); + var jwtConfig = new JWTAuthContextInfo(); + jwtConfig.setExpectedAudience(Set.of(audiences)); + return new McpOAuthMetadata(auth, features, config, endpoint, metadataPath, jwtConfig); + } + + private RoutingContext request(String path) { + var context = mock(RoutingContext.class); + when(context.normalizedPath()).thenReturn(path); + return context; + } + + /** A request whose Host header is {@code host}, or one without the header when it is null. */ + private RoutingContext request(String path, String host, int port) { + var context = request(path); + var request = mock(HttpServerRequest.class); + when(context.request()).thenReturn(request); + when(request.authority()).thenReturn(host == null ? null : HostAndPort.create(host, port)); + return context; + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/security/challenge/impl/ErrorChallengeSenderTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/security/challenge/impl/ErrorChallengeSenderTest.java new file mode 100644 index 0000000000..c668e07c5f --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/security/challenge/impl/ErrorChallengeSenderTest.java @@ -0,0 +1,64 @@ +package io.stargate.sgv2.jsonapi.api.security.challenge.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.vertx.http.runtime.security.ChallengeData; +import io.vertx.core.Future; +import io.vertx.core.MultiMap; +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.ext.web.RoutingContext; +import jakarta.ws.rs.core.HttpHeaders; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class ErrorChallengeSenderTest { + @Test + void rejectedBearerReportsInvalidCredentialsAndPreservesTheChallenge() throws Exception { + String body = sendChallenge("Bearer rejected-credential"); + + assertThat(new ObjectMapper().readTree(body).at("/errors/0/errorCode").asText()) + .isEqualTo("UNAUTHENTICATED_REQUEST"); + assertThat(body).contains("invalid token").doesNotContain("rejected-credential", "missing"); + } + + @Test + void missingCredentialsKeepTheExistingMissingTokenResponse() throws Exception { + String body = sendChallenge(null); + + assertThat(new ObjectMapper().readTree(body).at("/errors/0/errorCode").asText()) + .isEqualTo("MISSING_AUTHENTICATION_TOKEN"); + assertThat(body).contains("Token"); + } + + private static String sendChallenge(String authorization) { + var request = mock(HttpServerRequest.class); + when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(authorization); + var response = mock(HttpServerResponse.class); + var headers = MultiMap.caseInsensitiveMultiMap(); + when(response.headers()).thenReturn(headers); + when(response.write(anyString())).thenReturn(Future.succeededFuture()); + var context = mock(RoutingContext.class); + when(context.request()).thenReturn(request); + when(context.response()).thenReturn(response); + String challenge = "Bearer resource_metadata=\"https://data.example.test/metadata\""; + + assertThat( + new ErrorChallengeSender(new ObjectMapper()) + .apply(context, new ChallengeData(401, HttpHeaders.WWW_AUTHENTICATE, challenge)) + .await() + .indefinitely()) + .isTrue(); + + assertThat(headers.get(HttpHeaders.WWW_AUTHENTICATE)).isEqualTo(challenge); + verify(response).setStatusCode(401); + var body = ArgumentCaptor.forClass(String.class); + verify(response).write(body.capture()); + return body.getValue(); + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/security/configuration/HeaderBasedSecurityConfigurationTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/security/configuration/HeaderBasedSecurityConfigurationTest.java new file mode 100644 index 0000000000..4be664458c --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/security/configuration/HeaderBasedSecurityConfigurationTest.java @@ -0,0 +1,132 @@ +package io.stargate.sgv2.jsonapi.api.security.configuration; + +import static io.stargate.sgv2.jsonapi.api.security.configuration.HeaderBasedSecurityConfiguration.validateBearerConfiguration; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.quarkus.smallrye.jwt.runtime.auth.MpJwtValidator; +import io.smallrye.jwt.auth.principal.JWTAuthContextInfo; +import io.smallrye.jwt.config.JWTAuthContextInfoProvider; +import io.stargate.sgv2.jsonapi.config.AuthConfig; +import jakarta.enterprise.inject.Instance; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +class HeaderBasedSecurityConfigurationTest { + + @Test + void bearerAuthenticationRequiresAnInstalledJwtVerifier() { + var auth = mock(AuthConfig.class); + when(auth.bearer()).thenReturn(() -> true); + Instance verifier = mock(); + when(verifier.isUnsatisfied()).thenReturn(true); + + var startup = new HeaderBasedSecurityConfiguration(); + assertThatThrownBy( + () -> startup.httpAuthenticationMechanism(auth, mock(), mock(), jwtConfig(), verifier)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("quarkus.smallrye-jwt.enabled=true"); + } + + @Test + void verifiedBearerRequiresExplicitIssuerKeyAndAudience() { + assertThatCode(() -> validateBearerConfiguration(jwtConfig(), false)) + .doesNotThrowAnyException(); + } + + @Test + void inlinePublicKeysAreSupported() { + var config = jwtConfig(); + config.setPublicKeyLocation(null); + config.setPublicKeyContent("inline-test-public-key"); + assertThatCode(() -> validateBearerConfiguration(config, false)).doesNotThrowAnyException(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "mp.jwt.verify.issuer", + "mp.jwt.verify.publickey.location", + "mp.jwt.verify.audiences" + }) + void missingRequiredVerificationConfigurationFailsClosed(String missing) { + var config = jwtConfig(); + switch (missing) { + case "mp.jwt.verify.issuer" -> config.setIssuedBy(null); + case "mp.jwt.verify.publickey.location" -> config.setPublicKeyLocation(null); + case "mp.jwt.verify.audiences" -> config.setExpectedAudience(null); + default -> throw new IllegalArgumentException(missing); + } + assertThatThrownBy(() -> validateBearerConfiguration(config, false)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(missing); + } + + @Test + void emptyAudienceListFailsClosed() { + var config = jwtConfig(); + config.setExpectedAudience(Set.of("", " ")); + assertThatThrownBy(() -> validateBearerConfiguration(config, false)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mp.jwt.verify.audiences"); + } + + @Test + void requestHostAudiencesReplaceTheStaticAudienceList() { + var config = jwtConfig(); + config.setExpectedAudience(null); + assertThatCode(() -> validateBearerConfiguration(config, true)).doesNotThrowAnyException(); + } + + @ParameterizedTest + @ValueSource(strings = {"mp.jwt.verify.issuer", "mp.jwt.verify.publickey.location"}) + void requestHostAudiencesStillRequireIssuerAndKey(String missing) { + var config = jwtConfig(); + config.setExpectedAudience(null); + if (missing.equals("mp.jwt.verify.issuer")) { + config.setIssuedBy(null); + } else { + config.setPublicKeyLocation(null); + } + assertThatThrownBy(() -> validateBearerConfiguration(config, true)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(missing); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = {"Cookie", "X-Access-Token"}) + void tokensOutsideTheAuthorizationHeaderFailClosed(String tokenHeader) { + for (boolean audienceFromRequestHost : new boolean[] {false, true}) { + var config = jwtConfig(); + config.setTokenHeader(tokenHeader); + assertThatThrownBy(() -> validateBearerConfiguration(config, audienceFromRequestHost)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mp.jwt.token.header=Authorization"); + } + } + + @Test + void disabledIssuerVerificationFailsClosed() { + var config = + JWTAuthContextInfoProvider.createWithKeyLocation("https://auth.example.test/jwks", "NONE") + .getContextInfo(); + assertThatThrownBy(() -> validateBearerConfiguration(config, false)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mp.jwt.verify.issuer"); + } + + private static JWTAuthContextInfo jwtConfig() { + var config = new JWTAuthContextInfo(); + config.setIssuedBy("https://auth.example.test"); + config.setPublicKeyLocation("test-public-key.pem"); + config.setExpectedAudience(Set.of("https://data.example.test/v1/mcp")); + config.setTokenHeader("Authorization"); + return config; + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpEndpointConfigSourceFactoryTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpEndpointConfigSourceFactoryTest.java index 601b0c0726..c358e709a8 100644 --- a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpEndpointConfigSourceFactoryTest.java +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpEndpointConfigSourceFactoryTest.java @@ -5,6 +5,7 @@ import io.smallrye.config.PropertiesConfigSource; import io.smallrye.config.SmallRyeConfig; import io.smallrye.config.SmallRyeConfigBuilder; +import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.junit.jupiter.api.Test; @@ -32,6 +33,17 @@ void excludesOnlyTheNormalizedEndpointAndItsDescendants( "quarkus.mcp.server.http.root-path", mcpRoot)); assertThat(config.getValue(McpEndpointConfigSourceFactory.ENDPOINT_PATH, String.class)) .isEqualTo(expectedEndpoint); + assertThat(config.getValue("quarkus.http.auth.permission.mcp.paths", String.class)) + .isEqualTo( + String.join( + ",", + expectedEndpoint, + expectedEndpoint + "/", + expectedEndpoint + "/sse", + expectedEndpoint + "/sse/", + expectedEndpoint + "/messages/*")); + assertThat(config.getValue("quarkus.http.auth.permission.mcp.policy", String.class)) + .isEqualTo("authenticated"); var excluded = Pattern.compile(config.getValue("quarkus.http.access-log.exclude-pattern", String.class)); assertThat(excluded.matcher(expectedEndpoint).matches()).isTrue(); @@ -47,6 +59,64 @@ void rootEndpointExcludesAllDescendants() { Pattern.compile(config.getValue("quarkus.http.access-log.exclude-pattern", String.class)); assertThat(excluded.matcher("/").matches()).isTrue(); assertThat(excluded.matcher("/messages").matches()).isTrue(); + assertThat(config.getValue("quarkus.http.auth.permission.mcp.paths", String.class)) + .isEqualTo("/,/sse,/sse/,/messages/*"); + } + + @ParameterizedTest + @CsvSource({ + "/, /, /, ''", + "/service, /, /service, /service", + "/, /v1/mcp, /v1/mcp, /v1/mcp", + "/service, /tools, /service/tools, /service/tools" + }) + void protectsOnlySdkTransportRoutes( + String httpRoot, String mcpRoot, String endpoint, String childRoot) { + var config = + config( + Map.of( + "quarkus.http.root-path", httpRoot, + "quarkus.mcp.server.http.root-path", mcpRoot)); + var paths = McpEndpointConfigSourceFactory.transportPaths(endpoint); + assertThat(config.getValue("quarkus.http.auth.permission.mcp.paths", String.class)) + .isEqualTo(paths.permissionPaths()) + .doesNotContain(endpoint.equals("/") ? "/*," : endpoint + "/*"); + assertThat(paths.matches(endpoint)).isTrue(); + assertThat(paths.matches(endpoint.equals("/") ? "/" : endpoint + "/")).isTrue(); + assertThat(paths.matches(childRoot + "/sse")).isTrue(); + assertThat(paths.matches(childRoot + "/sse/")).isTrue(); + assertThat(paths.matches(childRoot + "/messages/session-id")).isTrue(); + for (String path : + List.of( + "/v1/collections", + "/stargate/health", + childRoot + "/v1/collections", + childRoot + "/stargate/health", + childRoot + "/collections", + childRoot + "/sse-other", + childRoot + "/messages-other/session-id", + endpoint + "-other", + childRoot + "/unknown")) { + assertThat(paths.matches(path)).as(path).isFalse(); + } + } + + @Test + void metadataRemainsPublicUnderTheConfiguredHttpRoot() { + var config = + config( + Map.of( + "quarkus.http.root-path", + "/service", + "quarkus.mcp.server.http.root-path", + "/tools")); + String path = "/service/.well-known/oauth-protected-resource"; + assertThat(config.getValue(McpEndpointConfigSourceFactory.METADATA_PATH, String.class)) + .isEqualTo(path); + assertThat(config.getValue("quarkus.http.auth.permission.mcp-metadata.paths", String.class)) + .isEqualTo(path); + assertThat(config.getValue("quarkus.http.auth.permission.mcp-metadata.policy", String.class)) + .isEqualTo("permit"); } @Test diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthCustomPathTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthCustomPathTest.java new file mode 100644 index 0000000000..e6584605ed --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthCustomPathTest.java @@ -0,0 +1,40 @@ +package io.stargate.sgv2.jsonapi.api.v1.mcp; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import java.util.HashMap; +import java.util.Map; + +@QuarkusTest +@TestProfile(McpOAuthCustomPathTest.CustomPathProfile.class) +class McpOAuthCustomPathTest extends McpOAuthRoutingTestBase { + @Override + protected String expectedResource() { + return McpOAuthTestSupport.PUBLIC_BASE + "/service/tools"; + } + + @Override + protected String expectedMetadataUrl() { + return McpOAuthTestSupport.PUBLIC_BASE + "/service" + McpOAuthTestSupport.METADATA_PATH; + } + + @Override + String expectedRestCredential() { + return "configured-database-credential"; + } + + public static class CustomPathProfile extends McpOAuthTest.OAuthProfile { + @Override + public Map getConfigOverrides() { + var overrides = new HashMap<>(super.getConfigOverrides()); + overrides.put("stargate.auth.token-resolver.type", "fixed"); + overrides.put("stargate.auth.token-resolver.fixed.token", "configured-database-credential"); + overrides.put("quarkus.http.root-path", "/service"); + overrides.put("quarkus.mcp.server.http.root-path", "/tools"); + overrides.put("quarkus.http.auth.inclusive", "true"); + overrides.put("quarkus.smallrye-jwt.priority", "900"); + overrides.put("mp.jwt.verify.audiences", McpOAuthTestSupport.PUBLIC_BASE + "/service/tools"); + return overrides; + } + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthDisabledTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthDisabledTest.java new file mode 100644 index 0000000000..38c660d0da --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthDisabledTest.java @@ -0,0 +1,95 @@ +package io.stargate.sgv2.jsonapi.api.v1.mcp; + +import static io.restassured.RestAssured.given; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.assertResponseComplete; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.request; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.rpcPayload; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.smallrye.mutiny.Uni; +import io.stargate.sgv2.jsonapi.api.model.command.CommandResult; +import io.stargate.sgv2.jsonapi.api.model.command.tracing.RequestTracing; +import io.stargate.sgv2.jsonapi.exception.APISecurityException; +import io.stargate.sgv2.jsonapi.service.processor.CommandProcessor; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +@QuarkusTest +@TestProfile(McpOAuthDisabledTest.DisabledProfile.class) +class McpOAuthDisabledTest { + @InjectMock CommandProcessor commandProcessor; + + @Test + void legacyDatabaseDenialRemainsAToolError() { + var denied = + APISecurityException.Code.UNAUTHORIZED_ACCESS.get( + Map.of("keyspace", "test", "table", "items")); + when(commandProcessor.processCommand(any(), any())) + .thenReturn( + Uni.createFrom() + .item( + CommandResult.statusOnlyBuilder(RequestTracing.NO_OP) + .addThrowable(denied) + .build())); + + var response = + request("tools/call") + .header("Mcp-Name", "findEmbeddingProviders") + .body(McpHttpTestSupport.toolPayload(1, "findEmbeddingProviders", Map.of())) + .header("Token", "legacy-credential") + .post("/v1/mcp"); + assertThat(assertResponseComplete(response, 1).getBoolean("isError")).isTrue(); + assertThat(response.header("WWW-Authenticate")).isNull(); + } + + @Test + void disabledBearerAuthenticationDoesNotAdvertiseOAuthMetadata() { + given().get(McpOAuthTestSupport.METADATA_PATH).then().statusCode(404); + } + + @Test + void aValidBearerTokenDoesNotEnableAuthenticationWithoutOptingIn() { + String credential = + McpOAuthTestSupport.token( + McpOAuthTestSupport.FIRST_SUBJECT, + McpOAuthTestSupport.FIRST_ORG, + "read-role", + McpOAuthTestSupport.PUBLIC_BASE + "/v1/mcp"); + request("tools/list") + .header("Authorization", "Bearer " + credential) + .body(rpcPayload(1, "tools/list", Map.of())) + .post("/v1/mcp") + .then() + .statusCode(401); + } + + @ParameterizedTest + @ValueSource(strings = {"Token", "X-Cassandra-Token"}) + void legacyMcpAuthenticationRemainsUsableWhenOAuthIsDisabled(String header) { + var response = + request("tools/list") + .header(header, "legacy-credential") + .body(rpcPayload(1, "tools/list", Map.of())) + .post("/v1/mcp"); + + assertResponseComplete(response, 1); + } + + public static class DisabledProfile extends McpOAuthTest.OAuthProfile { + @Override + public Map getConfigOverrides() { + var overrides = new HashMap<>(super.getConfigOverrides()); + overrides.put("stargate.auth.bearer.enabled", "false"); + overrides.put("quarkus.http.auth.inclusive", "true"); + return overrides; + } + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthFeatureDisabledTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthFeatureDisabledTest.java new file mode 100644 index 0000000000..c16af3f3a1 --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthFeatureDisabledTest.java @@ -0,0 +1,42 @@ +package io.stargate.sgv2.jsonapi.api.v1.mcp; + +import static io.restassured.RestAssured.given; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.request; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.rpcPayload; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +@QuarkusTest +@TestProfile(McpOAuthFeatureDisabledTest.DisabledProfile.class) +class McpOAuthFeatureDisabledTest { + @Test + void disabledMcpFeatureDoesNotAdvertiseOAuthMetadata() { + given().get(McpOAuthTestSupport.METADATA_PATH).then().statusCode(404); + } + + @ParameterizedTest + @ValueSource(strings = {"Token", "X-Cassandra-Token"}) + void disabledMetadataDoesNotReenableLegacyMcpAuthentication(String header) { + request("tools/list") + .header(header, "legacy-credential") + .body(rpcPayload(1, "tools/list", Map.of())) + .post("/v1/mcp") + .then() + .statusCode(401); + } + + public static class DisabledProfile extends McpOAuthTest.OAuthProfile { + @Override + public Map getConfigOverrides() { + var overrides = new HashMap<>(super.getConfigOverrides()); + overrides.put("stargate.feature.flags.mcp", "false"); + return overrides; + } + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthHostSuffixTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthHostSuffixTest.java new file mode 100644 index 0000000000..1fffa2f57b --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthHostSuffixTest.java @@ -0,0 +1,209 @@ +package io.stargate.sgv2.jsonapi.api.v1.mcp; + +import static io.restassured.RestAssured.given; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.assertResponseComplete; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.request; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.rpcPayload; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.AUTH_SERVER; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.FIRST_ORG; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.FIRST_SUBJECT; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.METADATA_PATH; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.token; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import io.stargate.sgv2.jsonapi.service.processor.CommandProcessor; +import io.stargate.sgv2.jsonapi.testresource.NoGlobalResourcesTestProfile; +import java.util.Locale; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** One deployment that serves a separate public host, and so a separate resource, per database. */ +@QuarkusTest +@TestProfile(McpOAuthHostSuffixTest.HostSuffixProfile.class) +class McpOAuthHostSuffixTest { + private static final String HOST_SUFFIX = ".apps.example.test"; + private static final String FIRST_HOST = "db-one-us-east-2" + HOST_SUFFIX; + private static final String SECOND_HOST = "db-two-us-east-2" + HOST_SUFFIX; + private static final String THIRD_HOST = "db-three-us-east-2" + HOST_SUFFIX; + private static final String MCP_PATH = "/v1/mcp"; + + @InjectMock CommandProcessor commandProcessor; + + @ParameterizedTest + @ValueSource(strings = {FIRST_HOST, SECOND_HOST}) + void discoveryNamesTheRequestedDatabaseHost(String host) { + var metadata = + given().header("Host", host).get(METADATA_PATH).then().statusCode(200).extract().jsonPath(); + + assertThat(metadata.getString("resource")).isEqualTo(resource(host)); + assertThat(metadata.getList("authorization_servers", String.class)) + .containsExactly(AUTH_SERVER); + } + + @Test + void discoveryPublishesTheCanonicalFormOfTheRequestHost() { + var metadata = + given() + .header("Host", FIRST_HOST.toUpperCase(Locale.ROOT) + ":443") + .get(METADATA_PATH) + .then() + .statusCode(200) + .extract() + .jsonPath(); + + assertThat(metadata.getString("resource")).isEqualTo(resource(FIRST_HOST)); + } + + @ParameterizedTest + @ValueSource( + strings = { + "data.attacker.test", + "db-one-us-east-2.apps.example.test.", + "db-one.other.apps.example.test" + }) + void discoveryIsAbsentOnAHostTheDeploymentDoesNotServe(String host) { + var response = given().header("Host", host).get(METADATA_PATH); + + assertThat(response.statusCode()).as(response.asString()).isEqualTo(404); + assertThat(response.asString()).doesNotContain(host); + } + + @Test + void unauthenticatedRequestsAreChallengedOnTheirOwnHost() { + assertChallenge(catalogRequest(FIRST_HOST).post(MCP_PATH), FIRST_HOST); + assertChallenge(catalogRequest(SECOND_HOST).post(MCP_PATH), SECOND_HOST); + } + + @Test + void aTokenIssuedForTheRequestedDatabaseListsTools() { + var response = + catalogRequest(FIRST_HOST) + .header("Authorization", "Bearer " + tokenFor(resource(FIRST_HOST))) + .post(MCP_PATH); + + assertResponseComplete(response, 1); + assertThat(response.jsonPath().getList("result.tools.name", String.class)).contains("findOne"); + } + + @ParameterizedTest + @ValueSource(strings = {FIRST_HOST, SECOND_HOST, THIRD_HOST}) + void aTokenWithMultipleDatabaseAudiencesIsRejected(String host) { + var response = + providerRequest(host) + .header( + "Authorization", "Bearer " + tokenFor(resource(FIRST_HOST), resource(SECOND_HOST))) + .post(MCP_PATH); + + assertChallenge(response, host); + verifyNoInteractions(commandProcessor); + } + + @Test + void aTokenIssuedForAnotherDatabaseCannotReachTheTool() { + var response = + providerRequest(FIRST_HOST) + .header("Authorization", "Bearer " + tokenFor(resource(SECOND_HOST))) + .post(MCP_PATH); + + assertChallenge(response, FIRST_HOST); + verifyNoInteractions(commandProcessor); + } + + @Test + void aTokenIssuedForTheHostWithoutTheMcpPathCannotReachTheTool() { + var response = + providerRequest(FIRST_HOST) + .header("Authorization", "Bearer " + tokenFor("https://" + FIRST_HOST)) + .post(MCP_PATH); + + assertChallenge(response, FIRST_HOST); + verifyNoInteractions(commandProcessor); + } + + @ParameterizedTest + @EnumSource( + value = McpOAuthTestSupport.InvalidToken.class, + names = {"WRONG_AUDIENCE", "MISSING_AUDIENCE"}) + void tokensWithoutTheRequestedAudienceCannotReachTheTool(McpOAuthTestSupport.InvalidToken kind) { + var response = + providerRequest(FIRST_HOST) + .header( + "Authorization", + "Bearer " + McpOAuthTestSupport.invalidToken(kind, resource(FIRST_HOST))) + .post(MCP_PATH); + + assertChallenge(response, FIRST_HOST); + verifyNoInteractions(commandProcessor); + } + + @Test + void aTokenNamingAnUnservedHostIsRejectedWithoutAChallenge() { + // A token another service received for its own audience must not work here, even when the + // request claims that service's host. + String host = "data.attacker.test"; + var response = + providerRequest(host) + .header("Authorization", "Bearer " + tokenFor(resource(host))) + .post(MCP_PATH); + + assertThat(response.statusCode()).as(response.asString()).isEqualTo(401); + assertThat(response.header("WWW-Authenticate")).isNull(); + assertThat(response.asString()).doesNotContain(host); + verifyNoInteractions(commandProcessor); + } + + private static String resource(String host) { + return "https://" + host + MCP_PATH; + } + + private static String tokenFor(String... audiences) { + return token(FIRST_SUBJECT, FIRST_ORG, "read-role", audiences); + } + + private static RequestSpecification catalogRequest(String host) { + return request("tools/list").header("Host", host).body(rpcPayload(1, "tools/list", Map.of())); + } + + private static RequestSpecification providerRequest(String host) { + return request("tools/call") + .header("Host", host) + .header("Mcp-Name", "findEmbeddingProviders") + .body(McpHttpTestSupport.toolPayload(1, "findEmbeddingProviders", Map.of())); + } + + private static void assertChallenge(Response response, String host) { + assertThat(response.statusCode()).as(response.asString()).isEqualTo(401); + assertThat(response.header("WWW-Authenticate")) + .as("HTTP headers: %s; body: %s", response.headers(), response.asString()) + .contains("Bearer", "resource_metadata=\"https://" + host + METADATA_PATH + "\""); + } + + public static class HostSuffixProfile implements NoGlobalResourcesTestProfile { + @Override + public Map getConfigOverrides() { + // mp.jwt.verify.audiences is left unset because each host is its own audience. + return Map.of( + "stargate.feature.flags.mcp", + "true", + "stargate.auth.bearer.enabled", + "true", + "stargate.mcp.auth.server-url", + AUTH_SERVER, + "stargate.mcp.auth.public-host-suffix", + HOST_SUFFIX, + "mp.jwt.verify.issuer", + AUTH_SERVER, + "mp.jwt.verify.publickey.location", + "mcp-oauth-public-key.pem"); + } + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthRoutingTestBase.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthRoutingTestBase.java new file mode 100644 index 0000000000..2442828a62 --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthRoutingTestBase.java @@ -0,0 +1,219 @@ +package io.stargate.sgv2.jsonapi.api.v1.mcp; + +import static io.restassured.RestAssured.config; +import static io.restassured.RestAssured.given; +import static io.restassured.config.HttpClientConfig.httpClientConfig; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.assertResponseComplete; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.request; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.rpcPayload; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.AUTH_SERVER; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.FIRST_ORG; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.FIRST_SUBJECT; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.METADATA_PATH; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.PUBLIC_BASE; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.token; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.quarkus.test.InjectMock; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import io.smallrye.mutiny.Uni; +import io.stargate.sgv2.jsonapi.api.model.command.CommandContext; +import io.stargate.sgv2.jsonapi.api.model.command.CommandResult; +import io.stargate.sgv2.jsonapi.api.request.EmbeddingCredentials; +import io.stargate.sgv2.jsonapi.api.request.RequestContext; +import io.stargate.sgv2.jsonapi.api.request.RerankingCredentials; +import io.stargate.sgv2.jsonapi.service.processor.CommandProcessor; +import jakarta.inject.Inject; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import org.eclipse.microprofile.config.ConfigProvider; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +abstract class McpOAuthRoutingTestBase { + static final String BROWSER_ORIGIN = "https://client.example.test"; + + @InjectMock CommandProcessor commandProcessor; + @Inject RequestContext injectedContext; + + @Test + void approvedBrowserOriginCanFollowTheChallengeToPublicMetadata() { + var challenge = catalogRequest(1).header("Origin", BROWSER_ORIGIN).post(mcpPath()); + assertChallenge(challenge); + assertThat(challenge.header("Access-Control-Allow-Origin")).isEqualTo(BROWSER_ORIGIN); + assertThat(challenge.header("Access-Control-Expose-Headers")).contains("WWW-Authenticate"); + + var response = given().header("Origin", BROWSER_ORIGIN).get(METADATA_PATH); + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Access-Control-Allow-Origin")).isEqualTo(BROWSER_ORIGIN); + assertThat(response.getHeaders().getValues("Vary")).contains("Origin"); + var metadata = response.jsonPath(); + + assertThat(metadata.getString("resource")).isEqualTo(expectedResource()); + assertThat(metadata.getList("authorization_servers", String.class)) + .containsExactly(AUTH_SERVER); + assertThat(metadata.getList("bearer_methods_supported", String.class)).contains("header"); + } + + @Test + void publicMetadataDoesNotGrantBrowserAccessToOtherOrigins() { + var response = given().header("Origin", "https://other.example.test").get(METADATA_PATH); + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Access-Control-Allow-Origin")).isNull(); + assertThat(response.getHeaders().getValues("Vary")).contains("Origin"); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = {"Token", "X-Cassandra-Token"}) + void commandContextReceivesTheVerifiedTokenRatherThanItsSubjectOrLegacyHeaders(String header) { + String credential = firstToken(); + var observed = captureCredentials(); + + var request = providerRequest(1).header("Authorization", "Bearer " + credential); + if (header != null) { + request.header(header, "legacy-credential"); + } + var response = request.post(mcpPath()); + + assertResponseComplete(response, 1); + var context = observed.get(); + assertThat(context.authToken()).isEqualTo(credential); + assertThat(context.providerAuthToken()).isNull(); + assertThat(context.injectedProviderToken()).isNull(); + assertThat(context.reranking().apiKey()).isEmpty(); + assertThat(context.embedding().authToken()).isEmpty(); + assertThat(response.asString()).doesNotContain(credential, "legacy-credential"); + } + + @ParameterizedTest + @ValueSource(strings = {"Token", "X-Cassandra-Token"}) + void legacyCredentialsCannotOpenTheSseTransport(String header) { + var response = + given() + // Bound the read if a regression incorrectly admits this streaming request. + .config(config().httpClient(httpClientConfig().setParam("http.socket.timeout", 5000))) + .header(header, "legacy-credential") + .accept("text/event-stream") + .get(mcpPath() + "/sse"); + + assertChallenge(response); + verifyNoInteractions(commandProcessor); + } + + @ParameterizedTest + @ValueSource(strings = {"Token", "X-Cassandra-Token"}) + void legacyCredentialsCannotPostToTheMessageTransport(String header) { + var response = + given() + .header(header, "legacy-credential") + .contentType("application/json") + .body(rpcPayload(1, "tools/list", Map.of())) + .post(mcpPath() + "/messages/synthetic-session-id"); + + assertChallenge(response); + verifyNoInteractions(commandProcessor); + } + + @ParameterizedTest + @ValueSource(strings = {"Token", "X-Cassandra-Token"}) + void ordinaryRestCallsRetainLegacyAuthentication(String header) { + var observed = captureCredentials(); + var response = + given() + .contentType("application/json") + .header(header, "legacy-credential") + .body(Map.of("findEmbeddingProviders", Map.of())) + .post("/v1"); + + assertThat(response.statusCode()).as(response.asString()).isEqualTo(200); + assertThat(observed.get().authToken()).isEqualTo(expectedRestCredential()); + assertThat(observed.get().providerAuthToken()).isEqualTo(expectedRestCredential()); + assertThat(observed.get().injectedProviderToken()).isEqualTo(expectedRestCredential()); + assertThat(observed.get().reranking().apiKey()).isEqualTo(expectedRestCredential()); + assertThat(response.asString()).doesNotContain("legacy-credential"); + } + + @Test + void ordinaryRestCallsDoNotAcceptBearerOnlyAuthentication() { + var response = + given() + .contentType("application/json") + .header("Authorization", "Bearer " + firstToken()) + .body(Map.of("findEmbeddingProviders", Map.of())) + .post("/v1"); + + assertThat(response.statusCode()).as(response.asString()).isEqualTo(401); + verifyNoInteractions(commandProcessor); + } + + record Credentials( + String authToken, + String providerAuthToken, + String injectedProviderToken, + EmbeddingCredentials embedding, + RerankingCredentials reranking) {} + + AtomicReference captureCredentials() { + var observed = new AtomicReference(); + when(commandProcessor.processCommand(any(), any())) + .thenAnswer( + invocation -> { + CommandContext context = invocation.getArgument(0); + var request = context.requestContext(); + observed.set( + new Credentials( + request.authToken(), + request.providerAuthToken(), + injectedContext.providerAuthToken(), + request.getEmbeddingCredentials(), + request.getRerankingCredentials())); + return Uni.createFrom() + .item(CommandResult.statusOnlyBuilder(context.requestTracing()).build()); + }); + return observed; + } + + String expectedRestCredential() { + return "legacy-credential"; + } + + String expectedResource() { + return PUBLIC_BASE + "/v1/mcp"; + } + + String expectedMetadataUrl() { + return PUBLIC_BASE + METADATA_PATH; + } + + String firstToken() { + return token(FIRST_SUBJECT, FIRST_ORG, "read-role", expectedResource()); + } + + String mcpPath() { + return ConfigProvider.getConfig().getValue("quarkus.mcp.server.http.root-path", String.class); + } + + RequestSpecification catalogRequest(int id) { + return request("tools/list").body(rpcPayload(id, "tools/list", Map.of())); + } + + RequestSpecification providerRequest(int id) { + return request("tools/call") + .header("Mcp-Name", "findEmbeddingProviders") + .body(McpHttpTestSupport.toolPayload(id, "findEmbeddingProviders", Map.of())); + } + + void assertChallenge(Response response) { + assertThat(response.statusCode()).as(response.asString()).isEqualTo(401); + assertThat(response.header("WWW-Authenticate")) + .as("HTTP headers: %s; body: %s", response.headers(), response.asString()) + .contains("Bearer", "resource_metadata=\"" + expectedMetadataUrl() + "\""); + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthTest.java new file mode 100644 index 0000000000..7b5b818a02 --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthTest.java @@ -0,0 +1,372 @@ +package io.stargate.sgv2.jsonapi.api.v1.mcp; + +import static io.restassured.RestAssured.given; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.CURRENT_PROTOCOL_VERSION; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.assertResponseComplete; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.assertRpcError; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpHttpTestSupport.request; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.AUTH_SERVER; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.FIRST_ORG; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.FIRST_SUBJECT; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.PUBLIC_BASE; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.SECOND_ORG; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.SECOND_SUBJECT; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.token; +import static io.stargate.sgv2.jsonapi.api.v1.mcp.McpOAuthTestSupport.tokenWithScope; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.quarkiverse.mcp.server.JsonRpcErrorCodes; +import io.quarkus.test.junit.QuarkusMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import io.smallrye.mutiny.Uni; +import io.stargate.sgv2.jsonapi.api.model.command.CommandContext; +import io.stargate.sgv2.jsonapi.api.model.command.CommandResult; +import io.stargate.sgv2.jsonapi.api.model.command.CommandStatus; +import io.stargate.sgv2.jsonapi.api.model.command.tracing.RequestTracing; +import io.stargate.sgv2.jsonapi.api.request.RequestContext; +import io.stargate.sgv2.jsonapi.exception.APISecurityException; +import io.stargate.sgv2.jsonapi.service.schema.SchemaObjectCache; +import io.stargate.sgv2.jsonapi.service.schema.SchemaObjectCacheSupplier; +import io.stargate.sgv2.jsonapi.testresource.NoGlobalResourcesTestProfile; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +@QuarkusTest +@TestProfile(McpOAuthTest.OAuthProfile.class) +class McpOAuthTest extends McpOAuthRoutingTestBase { + private static final int UNSUPPORTED_PROTOCOL_VERSION = -32022; + + @Test + void validJwtListsToolsWithoutAStoredSession() { + String credential = firstToken(); + for (int id = 1; id <= 2; id++) { + var response = + catalogRequest(id).header("Authorization", "Bearer " + credential).post(mcpPath()); + assertResponseComplete(response, id); + assertThat(response.header("Mcp-Session-Id")).isNull(); + assertThat(response.jsonPath().getList("result.tools.name", String.class)) + .contains("findKeyspaces", "findEmbeddingProviders", "findOne", "insertOne"); + } + } + + @Test + void oauthToolCallsKeepExplicitProviderKeysSeparateFromTheDatabaseToken() { + var context = captureCredentials(); + var response = + providerRequest(1) + .header("Authorization", "Bearer " + firstToken()) + .header("x-embedding-api-key", "embedding-key") + .header("reranking-api-key", "reranking-key") + .post(mcpPath()); + + assertResponseComplete(response, 1); + assertThat(context.get().embedding().apiKey()).contains("embedding-key"); + assertThat(context.get().reranking().apiKey()).isEqualTo("reranking-key"); + assertThat(context.get().providerAuthToken()).isNull(); + } + + @Test + void fixedBaseRejectsMultipleAudiences() { + String jwt = + token( + FIRST_SUBJECT, + FIRST_ORG, + "read-role", + expectedResource(), + "https://other.example.test/v1/mcp"); + + assertChallenge(providerRequest(1).header("Authorization", "Bearer " + jwt).post(mcpPath())); + verifyNoInteractions(commandProcessor); + } + + @Test + void readScopeCannotRunAWriteToolEvenWithAWriteRole() { + String jwt = + tokenWithScope(FIRST_SUBJECT, FIRST_ORG, "write-role", "astra:db:read", expectedResource()); + var response = + toolRequest( + "insertOne", + Map.of("keyspace", "test", "collection", "test", "document", Map.of("x", 1))) + .header("Authorization", "Bearer " + jwt) + .post(mcpPath()); + + assertInsufficientScope(response, "astra:db:write"); + verifyNoInteractions(commandProcessor); + } + + @Test + void databaseDenialDuringSchemaLookupReturnsForbidden() { + var cache = mock(SchemaObjectCache.class); + when(cache.getDatabase(any(), any(), any())) + .thenReturn(Uni.createFrom().failure(databaseDenial())); + + var supplier = mock(SchemaObjectCacheSupplier.class); + when(supplier.get()).thenReturn(cache); + QuarkusMock.installMockForType(supplier, SchemaObjectCacheSupplier.class); + assertDatabaseDenial(); + verifyNoInteractions(commandProcessor); + } + + @Test + void databaseDenialDuringExecutionReturnsForbidden() { + var denied = + CommandResult.statusOnlyBuilder(RequestTracing.NO_OP) + .addThrowable(databaseDenial()) + .build(); + when(commandProcessor.processCommand(any(), any())) + .thenReturn(Uni.createFrom().item(denied).emitOn(ForkJoinPool.commonPool())); + assertDatabaseDenial(); + } + + private APISecurityException databaseDenial() { + return APISecurityException.Code.UNAUTHORIZED_ACCESS.get( + Map.of("keyspace", "test", "table", "items")); + } + + private void assertDatabaseDenial() { + var response = + providerRequest(1).header("Authorization", "Bearer " + firstToken()).post(mcpPath()); + assertThat(response.statusCode()).isEqualTo(403); + assertThat(response.header("WWW-Authenticate")) + .isEqualTo("Bearer resource_metadata=\"" + expectedMetadataUrl() + "\""); + assertThat(response.jsonPath().getBoolean("result.isError")).isTrue(); + assertThat( + response.jsonPath().getList("result.structuredContent.errors.errorCode", String.class)) + .containsExactly("UNAUTHORIZED_ACCESS"); + } + + @Test + void writeScopeCannotRunSchemaChanges() { + String jwt = + tokenWithScope( + FIRST_SUBJECT, FIRST_ORG, "admin-role", "astra:db:write", expectedResource()); + var response = + toolRequest("createKeyspace", Map.of("name", "test")) + .header("Authorization", "Bearer " + jwt) + .post(mcpPath()); + + assertInsufficientScope(response, "astra:db:admin"); + verifyNoInteractions(commandProcessor); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = {"astra:db:read-extra", "astra:db:admin"}) + void readToolsRequireReadOrWriteScope(String scope) { + String jwt = tokenWithScope(FIRST_SUBJECT, FIRST_ORG, "admin-role", scope, expectedResource()); + + assertInsufficientScope( + providerRequest(1).header("Authorization", "Bearer " + jwt).post(mcpPath()), + "astra:db:read"); + verifyNoInteractions(commandProcessor); + } + + @Test + void validJwtDoesNotAdmitAnOlderProtocol() { + // OAuth admits the caller; it does not widen the supported protocol revisions. + var response = + given() + .contentType("application/json") + .accept("application/json, text/event-stream") + .header("Authorization", "Bearer " + firstToken()) + .header("MCP-Protocol-Version", "2025-11-25") + .header("Mcp-Method", "initialize") + .body( + Map.of( + "jsonrpc", + "2.0", + "id", + 1, + "method", + "initialize", + "params", + Map.of( + "protocolVersion", "2025-11-25", + "capabilities", Map.of(), + "clientInfo", Map.of("name", "oauth-compatibility-test", "version", "1")))) + .post(mcpPath()); + + var error = assertRpcError(response, 400, UNSUPPORTED_PROTOCOL_VERSION); + assertThat(error.getJsonObject("data").getString("requested")).isEqualTo("2025-11-25"); + assertThat(error.getJsonObject("data").getJsonArray("supported").getList()) + .containsExactly(CURRENT_PROTOCOL_VERSION); + assertThat(response.header("Mcp-Session-Id")).isNull(); + verifyNoInteractions(commandProcessor); + } + + @ParameterizedTest + @EnumSource(McpOAuthTestSupport.InvalidToken.class) + void invalidBearerTokensCannotReachTheTool(McpOAuthTestSupport.InvalidToken kind) { + var response = + providerRequest(1) + .header( + "Authorization", + "Bearer " + McpOAuthTestSupport.invalidToken(kind, expectedResource())) + .post(mcpPath()); + + assertChallenge(response); + verifyNoInteractions(commandProcessor); + } + + @Test + void invalidBearerDoesNotFallBackToAnExistingLegacyToken() { + var response = + providerRequest(1) + .header("Authorization", "Bearer malformed-access-token") + .header("Token", "legacy-credential") + .post(mcpPath()); + + assertChallenge(response); + assertThat(response.jsonPath().getInt("error.code")) + .isEqualTo(JsonRpcErrorCodes.SECURITY_ERROR); + assertThat(response.asString()) + .doesNotContain( + "MISSING_AUTHENTICATION_TOKEN", "legacy-credential", "malformed-access-token"); + verifyNoInteractions(commandProcessor); + } + + @ParameterizedTest + @ValueSource(strings = {"Token", "X-Cassandra-Token"}) + void legacyTokenHeadersCannotAuthenticateOAuthOnlyMcp(String header) { + var response = catalogRequest(1).header(header, "legacy-credential").post(mcpPath()); + + assertChallenge(response); + verifyNoInteractions(commandProcessor); + } + + @Test + void overlappingJwtRequestsKeepSeparateCredentialsWhenCompletedInReverseOrder() throws Exception { + String firstToken = firstToken(); + String secondToken = + tokenWithScope( + SECOND_SUBJECT, SECOND_ORG, "write-role", "astra:db:write", expectedResource()); + var firstCompletion = new CompletableFuture(); + var secondCompletion = new CompletableFuture(); + var completions = Map.of(firstToken, firstCompletion, secondToken, secondCompletion); + var started = new LinkedBlockingQueue(); + when(commandProcessor.processCommand(any(), any())) + .thenAnswer( + invocation -> { + CommandContext context = invocation.getArgument(0); + return Uni.createFrom() + .emitter( + emitter -> { + started.add(context.requestContext()); + var completion = completions.get(context.requestContext().authToken()); + if (completion == null) { + emitter.fail( + new IllegalStateException("Expected the encoded access token")); + } else { + completion.thenAccept(emitter::complete); + } + }) + .map( + value -> + CommandResult.statusOnlyBuilder(context.requestTracing()) + .addStatus(CommandStatus.OK, value) + .build()); + }); + + try (var clients = Executors.newFixedThreadPool(2); + var worker = Executors.newSingleThreadExecutor()) { + worker.submit(() -> {}).get(); + try { + var firstResponse = + clients.submit( + () -> + providerRequest(1) + .header("Authorization", "Bearer " + firstToken) + .post(mcpPath())); + var firstContext = started.poll(10, TimeUnit.SECONDS); + assertThat(firstContext).isNotNull(); + var secondResponse = + clients.submit( + () -> + providerRequest(2) + .header("Authorization", "Bearer " + secondToken) + .post(mcpPath())); + var secondContext = started.poll(10, TimeUnit.SECONDS); + assertThat(secondContext).isNotNull(); + + assertThat(firstContext).isNotSameAs(secondContext); + assertThat(firstContext.authToken()).isEqualTo(firstToken); + assertThat(secondContext.authToken()).isEqualTo(secondToken); + assertThat(firstContext.requestId()).isNotEqualTo(secondContext.requestId()); + worker.submit(() -> secondCompletion.complete(2)).get(10, TimeUnit.SECONDS); + assertThat( + assertResponseComplete(secondResponse.get(10, TimeUnit.SECONDS), 2) + .getJsonObject("_meta") + .getJsonObject("status") + .getInteger("ok")) + .isEqualTo(2); + assertThat(firstResponse.isDone()).isFalse(); + worker.submit(() -> firstCompletion.complete(1)).get(10, TimeUnit.SECONDS); + assertThat( + assertResponseComplete(firstResponse.get(10, TimeUnit.SECONDS), 1) + .getJsonObject("_meta") + .getJsonObject("status") + .getInteger("ok")) + .isEqualTo(1); + } finally { + firstCompletion.complete(1); + secondCompletion.complete(2); + } + } + } + + private RequestSpecification toolRequest(String name, Map args) { + return request("tools/call") + .header("Mcp-Name", name) + .body(McpHttpTestSupport.toolPayload(1, name, args)); + } + + private void assertInsufficientScope(Response response, String requiredScope) { + assertThat(assertRpcError(response, 403, JsonRpcErrorCodes.SECURITY_ERROR).getString("message")) + .isEqualTo("Insufficient OAuth scope"); + assertThat(response.header("WWW-Authenticate")) + .contains( + "Bearer", + "error=\"insufficient_scope\"", + "scope=\"" + requiredScope + "\"", + "resource_metadata=\"" + expectedMetadataUrl() + "\""); + } + + public static class OAuthProfile implements NoGlobalResourcesTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "stargate.feature.flags.mcp", + "true", + "stargate.auth.bearer.enabled", + "true", + McpOriginFilter.ALLOWED_ORIGINS, + BROWSER_ORIGIN, + "stargate.mcp.auth.server-url", + AUTH_SERVER, + "stargate.mcp.auth.public-base-url", + PUBLIC_BASE, + "mp.jwt.verify.issuer", + AUTH_SERVER, + "mp.jwt.verify.audiences", + PUBLIC_BASE + "/v1/mcp", + "mp.jwt.verify.publickey.location", + "mcp-oauth-public-key.pem"); + } + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthTestSupport.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthTestSupport.java new file mode 100644 index 0000000000..48ffbc3652 --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpOAuthTestSupport.java @@ -0,0 +1,141 @@ +package io.stargate.sgv2.jsonapi.api.v1.mcp; + +import io.vertx.core.json.JsonObject; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.spec.PKCS8EncodedKeySpec; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Objects; + +final class McpOAuthTestSupport { + static final String AUTH_SERVER = "https://auth.example.test"; + static final String PUBLIC_BASE = "https://data.example.test"; + static final String METADATA_PATH = "/.well-known/oauth-protected-resource"; + static final String FIRST_SUBJECT = "oauth-client-one"; + static final String SECOND_SUBJECT = "oauth-client-two"; + static final String FIRST_ORG = "11111111-1111-4111-8111-111111111111"; + static final String SECOND_ORG = "22222222-2222-4222-8222-222222222222"; + private static final Base64.Encoder BASE64 = Base64.getUrlEncoder().withoutPadding(); + + private McpOAuthTestSupport() {} + + static String token(String subject, String org, String role, String... audiences) { + return tokenWithScope(subject, org, role, "astra:db:read", audiences); + } + + static String tokenWithScope( + String subject, String org, String role, String scope, String... audiences) { + var claims = claims(subject, org, role, List.of(audiences)); + if (scope != null) { + claims.put("scope", scope); + } + return sign(claims, fixturePrivateKey()); + } + + static String invalidToken(InvalidToken kind, String audience) { + if (kind == InvalidToken.MALFORMED) { + return "malformed-access-token"; + } + if (kind == InvalidToken.EMPTY) { + return ""; + } + var claims = claims(FIRST_SUBJECT, FIRST_ORG, "read-role", List.of(audience)); + switch (kind) { + case UNSIGNED -> { + return BASE64.encodeToString( + "{\"alg\":\"none\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8)) + + "." + + BASE64.encodeToString(claims.encode().getBytes(StandardCharsets.UTF_8)) + + "."; + } + case EXPIRED -> { + long now = Instant.now().getEpochSecond(); + claims.put("iat", now - 900).put("nbf", now - 900).put("exp", now - 300); + } + case WRONG_AUDIENCE -> claims.put("aud", List.of("https://another-resource.example.test")); + case MISSING_AUDIENCE -> claims.remove("aud"); + case MISSING_EXPIRATION -> claims.remove("exp"); + case WRONG_ISSUER -> claims.put("iss", "https://another-issuer.example.test"); + case NOT_YET_VALID -> claims.put("nbf", Instant.now().plusSeconds(300).getEpochSecond()); + case WRONG_SIGNATURE -> { + try { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return sign(claims, generator.generateKeyPair().getPrivate()); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("Unable to generate a synthetic signing key", exception); + } + } + default -> throw new IllegalArgumentException("Unsupported invalid-token case: " + kind); + } + return sign(claims, fixturePrivateKey()); + } + + private static JsonObject claims( + String subject, String org, String role, List audiences) { + long now = Instant.now().getEpochSecond(); + return new JsonObject() + .put("iss", AUTH_SERVER) + .put("sub", subject) + .put("aud", audiences) + .put("iat", now - 60) + .put("nbf", now - 60) + .put("exp", now + 300) + .put("org", org) + .put("groups", List.of(role)); + } + + private static String sign(JsonObject claims, PrivateKey privateKey) { + var header = new JsonObject().put("alg", "RS256").put("typ", "JWT"); + String input = encode(header.encode()) + "." + encode(claims.encode()); + try { + var signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(privateKey); + signer.update(input.getBytes(StandardCharsets.US_ASCII)); + return input + "." + BASE64.encodeToString(signer.sign()); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("Unable to sign a synthetic JWT", exception); + } + } + + private static String encode(String value) { + return BASE64.encodeToString(value.getBytes(StandardCharsets.UTF_8)); + } + + private static PrivateKey fixturePrivateKey() { + // These checked-in synthetic keys are only used by authentication tests. + try (var stream = + Objects.requireNonNull( + McpOAuthTestSupport.class.getResourceAsStream("/mcp-oauth-private-key.pem"))) { + String pem = new String(stream.readAllBytes(), StandardCharsets.US_ASCII); + String contents = + pem.replace("-----BEGIN PRIVATE KEY-----", "") + .replace("-----END PRIVATE KEY-----", "") + .replaceAll("\\s", ""); + return KeyFactory.getInstance("RSA") + .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(contents))); + } catch (IOException | GeneralSecurityException exception) { + throw new IllegalStateException("Unable to read the synthetic JWT signing key", exception); + } + } + + enum InvalidToken { + MALFORMED, + UNSIGNED, + EMPTY, + EXPIRED, + WRONG_AUDIENCE, + MISSING_AUDIENCE, + MISSING_EXPIRATION, + WRONG_ISSUER, + WRONG_SIGNATURE, + NOT_YET_VALID + } +} diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpResourceTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpResourceTest.java index 7ea1cc554b..b437f3824a 100644 --- a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpResourceTest.java +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpResourceTest.java @@ -25,6 +25,8 @@ import io.stargate.sgv2.jsonapi.api.request.EmbeddingCredentialsResolver; import io.stargate.sgv2.jsonapi.api.request.RequestContext; import io.stargate.sgv2.jsonapi.api.request.tenant.RequestTenantResolver; +import io.stargate.sgv2.jsonapi.api.request.token.PrincipalTokenResolver; +import io.stargate.sgv2.jsonapi.api.security.McpOAuthMetadata; import io.stargate.sgv2.jsonapi.config.feature.ApiFeature; import io.stargate.sgv2.jsonapi.config.feature.ApiFeatures; import io.stargate.sgv2.jsonapi.metrics.JsonProcessingMetricsReporter; @@ -250,6 +252,7 @@ private McpResource mcpResource() { return new McpResource( mock(ObjectMapper.class), mock(Validator.class), + mock(McpOAuthMetadata.class), commandProcessor, mock(MeterRegistry.class), mock(JsonProcessingMetricsReporter.class), @@ -260,6 +263,7 @@ private McpResource mcpResource() { () -> routingContext, () -> securityIdentity, instanceOf(tenantResolver), + instanceOf(new PrincipalTokenResolver()), instanceOf(mock(EmbeddingCredentialsResolver.class))); } diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSetupErrorsTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSetupErrorsTest.java index 636045ff94..a444dc0032 100644 --- a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSetupErrorsTest.java +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSetupErrorsTest.java @@ -45,6 +45,8 @@ import io.stargate.sgv2.jsonapi.api.request.EmbeddingCredentialsResolver; import io.stargate.sgv2.jsonapi.api.request.RequestContext; import io.stargate.sgv2.jsonapi.api.request.tenant.RequestTenantResolver; +import io.stargate.sgv2.jsonapi.api.request.token.PrincipalTokenResolver; +import io.stargate.sgv2.jsonapi.api.security.McpOAuthMetadata; import io.stargate.sgv2.jsonapi.config.feature.ApiFeature; import io.stargate.sgv2.jsonapi.config.feature.FeaturesConfig; import io.stargate.sgv2.jsonapi.exception.APIException; @@ -144,6 +146,7 @@ void setUp() { new McpResource( objectMapper, mock(Validator.class), + mock(McpOAuthMetadata.class), commandProcessor, mock(MeterRegistry.class), mock(JsonProcessingMetricsReporter.class), @@ -154,6 +157,7 @@ void setUp() { () -> routingContext, () -> securityIdentity, instanceOf(tenantResolver), + instanceOf(new PrincipalTokenResolver()), instanceOf(credentialsResolver)); } diff --git a/src/test/java/io/stargate/sgv2/jsonapi/service/embedding/operation/EmbeddingGatewayClientTest.java b/src/test/java/io/stargate/sgv2/jsonapi/service/embedding/operation/EmbeddingGatewayClientTest.java index 93de4cf017..976e31c7bf 100644 --- a/src/test/java/io/stargate/sgv2/jsonapi/service/embedding/operation/EmbeddingGatewayClientTest.java +++ b/src/test/java/io/stargate/sgv2/jsonapi/service/embedding/operation/EmbeddingGatewayClientTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.quarkus.test.junit.QuarkusTest; @@ -30,6 +31,7 @@ import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; @QuarkusTest @TestProfile(NoGlobalResourcesTestProfile.Impl.class) @@ -151,7 +153,7 @@ void handleValidResponse() { 1536, Map.of(), tenant, - "default", + null, embeddingService, Map.of(), TESTING_COMMAND_NAME); @@ -162,13 +164,22 @@ void handleValidResponse() { 1, List.of("data 1", "data 2"), new EmbeddingCredentials( - tenant, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()), + tenant, + Optional.of("embedding-key"), + Optional.empty(), + Optional.empty(), + Optional.empty()), EmbeddingGatewayClient.EmbeddingRequestType.INDEX) .subscribe() .withSubscriber(UniAssertSubscriber.create()) .awaitItem() .getItem(); + var request = ArgumentCaptor.forClass(EmbeddingGateway.ProviderEmbedRequest.class); + verify(embeddingService).embed(request.capture()); + assertThat(request.getValue().getProviderContext().getAuthTokensMap()) + .isEqualTo(Map.of("EMBEDDING_API_KEY", "embedding-key")); + assertThat(response).isNotNull(); assertThat(response.batchId()).isEqualTo(1); assertThat(response.embeddings()).isNotEmpty(); diff --git a/src/test/java/io/stargate/sgv2/jsonapi/service/embedding/operation/SyncServiceCredentialResolvingProviderTest.java b/src/test/java/io/stargate/sgv2/jsonapi/service/embedding/operation/SyncServiceCredentialResolvingProviderTest.java index ec6fbc9b2b..2f9bddd2f4 100644 --- a/src/test/java/io/stargate/sgv2/jsonapi/service/embedding/operation/SyncServiceCredentialResolvingProviderTest.java +++ b/src/test/java/io/stargate/sgv2/jsonapi/service/embedding/operation/SyncServiceCredentialResolvingProviderTest.java @@ -1,6 +1,7 @@ package io.stargate.sgv2.jsonapi.service.embedding.operation; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; @@ -57,6 +58,25 @@ private EmbeddingCredentials captureResolvedCredentials() { @Nested class Vectorize { + @Test + void storedCredentialLookupRequiresAServiceCredential() { + authToken = null; + var provider = createProvider(Map.of("providerKey", "stored-key")); + + assertThatThrownBy( + () -> + provider + .vectorize( + 1, + List.of("text"), + emptyCreds, + EmbeddingProvider.EmbeddingRequestType.INDEX) + .await() + .indefinitely()) + .hasMessageContaining("separate service token"); + verifyNoInteractions(syncServiceClient); + } + @Test void shouldResolveProviderKeyAndPassToDelegate() { Map authentication = Map.of("providerKey", "my-openai-cred"); diff --git a/src/test/java/io/stargate/sgv2/jsonapi/service/reranking/gateway/RerankingGatewayClientTest.java b/src/test/java/io/stargate/sgv2/jsonapi/service/reranking/gateway/RerankingGatewayClientTest.java index 3e319dbd2a..c786bb5dfe 100644 --- a/src/test/java/io/stargate/sgv2/jsonapi/service/reranking/gateway/RerankingGatewayClientTest.java +++ b/src/test/java/io/stargate/sgv2/jsonapi/service/reranking/gateway/RerankingGatewayClientTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.quarkus.test.junit.QuarkusTest; @@ -27,6 +28,7 @@ import java.util.Optional; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; /** * Tests for the RerankEGWClient class. Mocking the embedding gateway service to test the grpc @@ -104,7 +106,7 @@ void handleValidResponse() { ModelProvider.NVIDIA, MODEL_CONFIG, tenant, - "default", + null, rerankService, Map.of(), TESTING_COMMAND_NAME); @@ -121,6 +123,11 @@ void handleValidResponse() { .awaitItem() .getItem(); + var request = ArgumentCaptor.forClass(EmbeddingGateway.ProviderRerankingRequest.class); + verify(rerankService).rerank(request.capture()); + assertThat(request.getValue().getProviderContext().getAuthTokensMap()) + .isEqualTo(Map.of("RERANKING_API_KEY", RERANK_CREDENTIALS.apiKey())); + assertThat(response).isNotNull(); assertThat(response.batchId()).isEqualTo(1); assertThat(response.ranks()).isNotEmpty(); diff --git a/src/test/resources/mcp-oauth-private-key.pem b/src/test/resources/mcp-oauth-private-key.pem new file mode 100644 index 0000000000..311549b99e --- /dev/null +++ b/src/test/resources/mcp-oauth-private-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCJhhXz1GbDfaSz +KzyOlpxePcpL1QNmixIOej1JB3tNcy+2BlhYEOa6mL0I0vHz4/yKsDLk+S26NOds +kIfsEqHdD/hh3zGisfRhcng/MrGgJ+Zy/GLflVvLLpZYJ5IMtN+SRUEGTShqRVJE +3U1kby6slIEfJi+9TuOjuY+cN26pHqSc2VhZG9dzpR+mlkAISg3QcYilo7/XwEWW +NlnJiP5rRh4hkBJggC1NWhBQE/H2iDrC20GuhyP5MMRhZBvMuu4KxzPvQSt2bWCy +48hLotnynYL6Jc7ehAOWwJb0nCzLD0Q8FK6HcvvhY26JZYhX2fnh0fNAwrZwoQjh +IPWk3CXHAgMBAAECggEANPHxW6knUxX5JZ18t+yWENY7HszIfV8HOZmoJIiD2QKC +mNKCio0fNzF8fXww+FOKs544Sd0A1NJvUmWmXqWhuWjfmFaEVn2qdyXJ05LhvaX+ +27/9FNT8vRGXgiLh4JB2DmspKJLl/1vm22pT1FnVn02hFGvwLzLDAxJ6jorsyKDZ +/si1BLKt3eUb+9/Q5Ky3lZVn/KWvr+UXd2O6lR/GAwo8vhsQ1IHtzFLkmOHt19Kw +C51dRW8rk/RGny3065Aw079L/Ffs7Mq49zXml9H5WwFb/sfVYRQoszdVGu7jD9Gn +OLeca8qRfM2kMQqPJTKl4pA3s+xNy4OrV7sG4v9S2QKBgQC/v0DGZrtdv0bAQZ0x +e5Mr5/zJ1GNpt86eNvXid8z7p89ys2Gg9XS2iRvlcuErkqkf/IUIBrHsJ9BCbZp1 +/BaK07M9WDHkQkIrzuJNhBFngG1Q6tE6Ng9JbBuYoT6AdmJ7weGfIIvOIcg9FL4R +sK5taATRB/zAfQTR3hWBUWse5QKBgQC3m11B0/DxLlOo0Ba/QwvilbQNW+SZzfRR +j3RlFoRtoserWxvBGdjHwvJ/XUJKlo6I2SybQSDJhEmKc0JgfZV1Xg8BIrvc9IPJ +Kymrv4lmOFO847vTyfQTNMzyNVVFqfJoAMfvRl03oyUKSMOWRWxaG4/Y/q+Z7U3/ +uI6wmsR7OwKBgEFNsZHgiw9yhXYU4qRnocfiSoWyf+kRYJ0hurxWcMmEbXJzBVz8 +O7OvHoEWjvl4CYGLTwNcxFvZc2QsT96+7C57yx+pWdSTfFXPL+OWhxbo9lIIpxlc +L/ihiQSCZfb6WrArZ9v6CaM6fifPWKxNsBoywvEt9zbXXTzclhZk1EbBAoGAYemL +WOByO9utp3eYudRCUUnuI7WeedrX8Gqk8oeIhYLqIdpLObXT4et3MC6GfIo/ZoES +BZU8q9pM8XU3r4cpHdbT/5ILRvBqGuxWo41X81gUZ8W2U2H+NAPTS1Lfr2/KomXQ +OSx354Sr6wkUrF1HQ+Iw2tIuyNJA5x7/kPRn1SMCgYBtSLQAWKn3eX2GfgZmyzxq +K4TxgD894QQa4C3OsuzqbO4X3MFpwdhIOhUQ3saQFF7VBxEyKTK7IJgUDY3GIZ6w +D0chuAOwIDhvr/uT7nahLHdJCrlBM8k80XM9zVH0A81cj7HcCDOGoYjVXm9RWKxS +2vVEFeEiUyKMd7xzZru/+w== +-----END PRIVATE KEY----- diff --git a/src/test/resources/mcp-oauth-public-key.pem b/src/test/resources/mcp-oauth-public-key.pem new file mode 100644 index 0000000000..a1221471c4 --- /dev/null +++ b/src/test/resources/mcp-oauth-public-key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiYYV89Rmw32ksys8jpac +Xj3KS9UDZosSDno9SQd7TXMvtgZYWBDmupi9CNLx8+P8irAy5PktujTnbJCH7BKh +3Q/4Yd8xorH0YXJ4PzKxoCfmcvxi35Vbyy6WWCeSDLTfkkVBBk0oakVSRN1NZG8u +rJSBHyYvvU7jo7mPnDduqR6knNlYWRvXc6UfppZACEoN0HGIpaO/18BFljZZyYj+ +a0YeIZASYIAtTVoQUBPx9og6wttBrocj+TDEYWQbzLruCscz70Erdm1gsuPIS6LZ +8p2C+iXO3oQDlsCW9Jwsyw9EPBSuh3L74WNuiWWIV9n54dHzQMK2cKEI4SD1pNwl +xwIDAQAB +-----END PUBLIC KEY-----