mz_environmentd/http/oauth_metadata.rs
1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! OAuth 2.0 Protected Resource Metadata for the MCP endpoints.
11//!
12//! Implements [RFC 9728] so MCP-aware clients (e.g. Claude Desktop's Custom
13//! Connectors, ChatGPT remote MCP) can discover the authorization server
14//! they need to authenticate against in order to call our MCP endpoints.
15//!
16//! The discovery document is published at
17//! `/.well-known/oauth-protected-resource` and is **public** (no auth).
18//! Clients reach it either by following the `resource_metadata` parameter
19//! emitted in a `WWW-Authenticate` challenge from a 401 on `/api/mcp/*`
20//! (see [`crate::http::AuthError`]), or by probing the well-known URI
21//! directly.
22//!
23//! ## Host derivation
24//!
25//! The `resource` field and the `resource_metadata` URL embedded in the
26//! 401 challenge are both absolute URLs and therefore depend on knowing
27//! the externally-visible host of this environment. We resolve that in
28//! this order:
29//!
30//! 1. `HttpConfig::http_host_name` (set by the operator).
31//! 2. The request's `Host` header.
32//!
33//! We deliberately do **not** consult `X-Forwarded-Host` or
34//! `X-Forwarded-Proto`: environmentd has no proxy-trust configuration,
35//! and trusting those headers blind would let any client reaching
36//! the server directly poison the published metadata URLs (a host-header
37//! injection on the OAuth flow). Deployments behind a load balancer that
38//! rewrites `Host` are expected to set `http_host_name` explicitly.
39//!
40//! ## When the document is published
41//!
42//! The handler returns 404 when no OAuth flow is meaningful for the
43//! listener: its authenticator validates no bearer token (see
44//! [`McpOAuthDiscovery`]), or it is an OIDC listener with `oidc_issuer`
45//! unset. Returning an empty or fake document instead would mislead
46//! clients into starting an OAuth dance they cannot complete.
47//!
48//! [RFC 9728]: https://datatracker.ietf.org/doc/html/rfc9728
49
50use std::sync::Arc;
51use std::time::Duration;
52
53use axum::Extension;
54use axum::extract::Request;
55use axum::response::{IntoResponse, Response};
56use http::{HeaderValue, StatusCode};
57use mz_adapter::Client;
58use mz_adapter_types::dyncfgs::{OIDC_AUDIENCE, OIDC_ISSUER};
59use mz_ore::metric;
60use mz_ore::metrics::MetricsRegistry;
61use mz_server_core::listeners;
62use prometheus::IntCounterVec;
63use serde::Serialize;
64use tracing::warn;
65use url::Url;
66
67use crate::http::Delayed;
68
69/// Bounds how long the unauthenticated discovery handler waits for the
70/// adapter client. Without this, a wedged adapter could pin connections
71/// indefinitely from any caller on the network.
72const ADAPTER_WAIT_TIMEOUT: Duration = Duration::from_secs(2);
73
74/// OAuth 2.1 §3.1 requires `https` for all OAuth endpoints.
75const PUBLISHED_SCHEME: &str = "https";
76
77/// The well-known path served by this module.
78///
79/// Per [RFC 9728 §3] this is the OAuth 2.0 Protected Resource Metadata
80/// well-known URI; MCP clients probe it as a fallback when no
81/// `resource_metadata` parameter is present in a 401's `WWW-Authenticate`.
82///
83/// [RFC 9728 §3]: https://datatracker.ietf.org/doc/html/rfc9728#section-3
84pub(crate) const PROTECTED_RESOURCE_METADATA_PATH: &str = "/.well-known/oauth-protected-resource";
85
86/// Path-suffixed aliases of [`PROTECTED_RESOURCE_METADATA_PATH`] per
87/// RFC 9728 §3.1. Every path serves the same document, whose `resource`
88/// is `/api/mcp`.
89///
90/// NOTE: only the `/api/mcp` alias matches that `resource` as §3.3
91/// requires. A strict client that probes the agent or developer alias
92/// rejects the document.
93pub(crate) const PROTECTED_RESOURCE_METADATA_PATH_UNIFIED: &str =
94 "/.well-known/oauth-protected-resource/api/mcp";
95pub(crate) const PROTECTED_RESOURCE_METADATA_PATH_AGENT: &str =
96 "/.well-known/oauth-protected-resource/api/mcp/agent";
97pub(crate) const PROTECTED_RESOURCE_METADATA_PATH_DEVELOPER: &str =
98 "/.well-known/oauth-protected-resource/api/mcp/developer";
99
100/// OAuth scope advertised for the MCP endpoints. Not enforced
101/// server-side (authorization is at the SQL layer via RBAC).
102pub(crate) const MCP_SCOPE: &str = "mcp.read";
103
104/// `private` (not the RFC-default `public`): the document varies by host,
105/// so shared caches must not serve one listener's document to another.
106const METADATA_CACHE_CONTROL: &str = "private, max-age=3600";
107
108/// JSON shape returned by [`PROTECTED_RESOURCE_METADATA_PATH`]. A
109/// strict subset of [RFC 9728 §2]; further fields can be added without
110/// breaking clients per the RFC's extensibility guidance.
111///
112/// [RFC 9728 §2]: https://datatracker.ietf.org/doc/html/rfc9728#section-2
113#[derive(Debug, Serialize, PartialEq, Eq)]
114pub(crate) struct ProtectedResourceMetadata {
115 /// Canonical URL of this resource server. Clients use this as the
116 /// `resource` parameter in their token request (RFC 8707).
117 pub resource: String,
118 /// Authorization servers a client may use to obtain a token. Each
119 /// entry is an issuer URL whose metadata document is fetchable at
120 /// `<issuer>/.well-known/oauth-authorization-server` (RFC 8414)
121 /// or `<issuer>/.well-known/openid-configuration` (OIDC Discovery).
122 pub authorization_servers: Vec<String>,
123 /// Mechanisms by which the client may present the bearer token.
124 /// We accept the `Authorization` header only.
125 pub bearer_methods_supported: Vec<String>,
126 /// Scopes a client may request a token for; see [`MCP_SCOPE`].
127 pub scopes_supported: Vec<String>,
128}
129
130/// Closed set of outcomes recorded by [`OauthMetadataMetrics`]. Keeping
131/// these as an enum (rather than free-form strings at the call sites) pins
132/// the metric's label cardinality and stops typos from silently creating
133/// new label values.
134#[derive(Debug, Clone, Copy)]
135enum MetricStatus {
136 Ok,
137 Disabled,
138 NoIssuer,
139 InvalidIssuer,
140 NoHost,
141 AdapterUnavailable,
142}
143
144impl MetricStatus {
145 fn as_str(self) -> &'static str {
146 match self {
147 Self::Ok => "ok",
148 Self::Disabled => "disabled",
149 Self::NoIssuer => "no_issuer",
150 Self::InvalidIssuer => "invalid_issuer",
151 Self::NoHost => "no_host",
152 Self::AdapterUnavailable => "adapter_unavailable",
153 }
154 }
155}
156
157/// Prometheus counter for the discovery endpoint, labeled by the
158/// [`MetricStatus`] of each request so dashboards key off names rather
159/// than HTTP status codes.
160#[derive(Debug, Clone)]
161pub struct OauthMetadataMetrics {
162 requests: IntCounterVec,
163}
164
165impl OauthMetadataMetrics {
166 pub fn register_into(registry: &MetricsRegistry) -> Self {
167 Self {
168 requests: registry.register(metric!(
169 name: "mz_oauth_protected_resource_metadata_requests_total",
170 help: "Total number of requests to the OAuth Protected Resource Metadata endpoint.",
171 var_labels: ["status"],
172 )),
173 }
174 }
175
176 fn inc(&self, status: MetricStatus) {
177 self.requests.with_label_values(&[status.as_str()]).inc();
178 }
179}
180
181/// Whether and how an HTTP listener advertises OAuth 2.0 for its MCP
182/// routes. Derived once per listener from its authenticator and consulted
183/// by both the 401 `WWW-Authenticate` challenge and this discovery handler,
184/// so the two never disagree about whether OAuth is on offer.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub(crate) enum McpOAuthDiscovery {
187 /// The listener validates no OAuth bearer token, so there is no flow to
188 /// advertise. Covers `None`, `Password`, and `Sasl`, plus `Frontegg`
189 /// when no valid issuer URL is configured.
190 Disabled,
191 /// Self-managed OIDC: the authorization server is the `oidc_issuer`
192 /// dyncfg, read at request time so an operator can change it without a
193 /// restart.
194 Oidc,
195 /// Frontegg (cloud): the authorization server is the workspace URL
196 /// supplied at startup via `--frontegg-oauth-issuer-url`.
197 Frontegg { issuer: String },
198}
199
200impl McpOAuthDiscovery {
201 /// The single mapping from a listener's authenticator to its OAuth
202 /// advertisement behavior. Frontegg requires a valid issuer URL;
203 /// otherwise falls back to `Disabled`.
204 pub(crate) fn for_authenticator(
205 kind: listeners::AuthenticatorKind,
206 frontegg_oauth_issuer_url: Option<&str>,
207 ) -> Self {
208 match (kind, frontegg_oauth_issuer_url) {
209 (listeners::AuthenticatorKind::Oidc, _) => Self::Oidc,
210 (listeners::AuthenticatorKind::Frontegg, Some(issuer)) => {
211 if let Err(err) = validate_issuer_url(issuer) {
212 warn!(
213 error = %err,
214 "frontegg-oauth-issuer-url is invalid; MCP OAuth discovery disabled"
215 );
216 Self::Disabled
217 } else {
218 Self::Frontegg {
219 issuer: issuer.to_string(),
220 }
221 }
222 }
223 _ => Self::Disabled,
224 }
225 }
226
227 pub(crate) fn is_enabled(&self) -> bool {
228 !matches!(self, Self::Disabled)
229 }
230}
231
232/// Per-listener config shared by the OAuth discovery handler and the auth
233/// middleware's `WWW-Authenticate` builder. Carried as an axum `Extension`
234/// because one environmentd process can serve listeners with different
235/// authenticators and `http_host_name`s.
236///
237/// Wrapping both consumers in one struct keeps them in lockstep: the 401
238/// challenge and the discovery document are computed from the same
239/// `discovery` value and the same `http_host_name`, so a client that
240/// follows the `resource_metadata` URL from a 401 reaches a document with
241/// matching host and matching authorization server.
242#[derive(Debug, Clone)]
243pub(crate) struct McpOAuthConfig {
244 /// Operator-configured external host (without scheme). Beats the
245 /// `Host` header when set.
246 pub http_host_name: Option<String>,
247 /// How (or whether) this listener advertises OAuth.
248 pub discovery: Arc<McpOAuthDiscovery>,
249}
250
251impl McpOAuthConfig {
252 /// OAuth scope advertised in the `Bearer` challenge's `scope=`
253 /// parameter on 401 responses. A method so the auth middleware does not
254 /// need [`MCP_SCOPE`].
255 pub(crate) fn scope(&self) -> &'static str {
256 MCP_SCOPE
257 }
258}
259
260/// HTTP handler for [`PROTECTED_RESOURCE_METADATA_PATH`].
261///
262/// Always public: no authentication is performed, by design. RFC 9728
263/// places no auth requirements on this endpoint; clients must be able to
264/// fetch it before they have a token.
265///
266/// Returns 404 when this listener does not advertise OAuth (see
267/// [`McpOAuthDiscovery`]) or has no issuer configured, 503 if the adapter
268/// client is not yet available (a brief window at startup) or `oidc_issuer`
269/// is invalid, 400 if the request has no host information to construct a URL
270/// with, and 200 with the JSON document otherwise.
271pub(crate) async fn handle_protected_resource_metadata(
272 Extension(adapter_client_rx): Extension<Delayed<Client>>,
273 Extension(config): Extension<McpOAuthConfig>,
274 Extension(metrics): Extension<OauthMetadataMetrics>,
275 req: Request,
276) -> Response {
277 // Early-return for listeners that don't advertise OAuth, before we touch
278 // request headers. Keeps the response 404 even when `Host` is malformed,
279 // so probes can't distinguish "Disabled listener" from "non-existent
280 // listener" by the status code.
281 if !config.discovery.is_enabled() {
282 metrics.inc(MetricStatus::Disabled);
283 return StatusCode::NOT_FOUND.into_response();
284 }
285
286 let Some(host) = resolve_host(&req, config.http_host_name.as_deref()) else {
287 warn!(
288 "oauth-protected-resource: no http_host_name configured and request has no Host header"
289 );
290 metrics.inc(MetricStatus::NoHost);
291 return (StatusCode::BAD_REQUEST, "no host available").into_response();
292 };
293 let resource = format!("{PUBLISHED_SCHEME}://{host}/api/mcp");
294
295 let issuer = match &*config.discovery {
296 McpOAuthDiscovery::Disabled => unreachable!("handled above"),
297 McpOAuthDiscovery::Frontegg { issuer } => {
298 // Validated once at startup in `for_authenticator`; trusted here.
299 issuer.clone()
300 }
301 McpOAuthDiscovery::Oidc => {
302 let adapter_client =
303 match tokio::time::timeout(ADAPTER_WAIT_TIMEOUT, adapter_client_rx.clone()).await {
304 Ok(Ok(client)) => client,
305 Ok(Err(_)) | Err(_) => {
306 metrics.inc(MetricStatus::AdapterUnavailable);
307 return (StatusCode::SERVICE_UNAVAILABLE, "adapter not ready")
308 .into_response();
309 }
310 };
311 let system_vars = adapter_client.get_system_vars().await;
312 let Some(issuer) = OIDC_ISSUER.get(system_vars.dyncfgs()) else {
313 // No OAuth authorization server is configured. Per RFC 9728 the
314 // document MUST contain at least one entry in
315 // `authorization_servers`, so the honest response is 404 rather
316 // than an empty document that misleads the client.
317 warn!("oauth-protected-resource: oidc_issuer is unset; cannot publish");
318 metrics.inc(MetricStatus::NoIssuer);
319 return StatusCode::NOT_FOUND.into_response();
320 };
321 if let Err(err) = validate_issuer_url(&issuer) {
322 // Don't echo the issuer into the WARN: a userinfo-bearing value
323 // would turn this log line into a credential dump. The error
324 // reason is specific enough.
325 warn!(error = %err, "oauth-protected-resource: refusing to publish invalid oidc_issuer");
326 metrics.inc(MetricStatus::InvalidIssuer);
327 return (StatusCode::SERVICE_UNAVAILABLE, err).into_response();
328 }
329
330 // We still publish when no audience is configured (mirroring the
331 // authenticator, which warns and skips `aud` validation), but a resource
332 // server that does not bind tokens to its own audience is exposed to
333 // same-issuer token reuse, so make the gap visible to operators.
334 if OIDC_AUDIENCE
335 .get(system_vars.dyncfgs())
336 .as_array()
337 .is_none_or(|audiences| audiences.is_empty())
338 {
339 warn!(
340 "oauth-protected-resource: publishing with oidc_audience unset; tokens from \
341 this issuer are not audience-bound to this resource"
342 );
343 }
344 issuer.to_string()
345 }
346 };
347
348 let metadata = ProtectedResourceMetadata {
349 resource,
350 authorization_servers: vec![issuer],
351 bearer_methods_supported: vec!["header".to_string()],
352 scopes_supported: vec![MCP_SCOPE.to_string()],
353 };
354
355 let mut response = axum::Json(metadata).into_response();
356 response.headers_mut().insert(
357 http::header::CACHE_CONTROL,
358 HeaderValue::from_static(METADATA_CACHE_CONTROL),
359 );
360 metrics.inc(MetricStatus::Ok);
361 response
362}
363
364/// Validates `oidc_issuer` before it is published. Required: parses as
365/// a URL, scheme is `https` or `http`, no userinfo (we publish it on a
366/// public endpoint), no query or fragment (RFC 8414 §2). The `http`
367/// scheme is permitted to ease local dev; OAuth 2.1 §3.1 forbids it in
368/// production but enforcement is the operator's responsibility.
369///
370/// The caller publishes the **original** value (not a re-serialised
371/// `Url`) because `url::Url` silently normalises some forms (e.g. adds
372/// a trailing slash to a bare authority), and a mutated issuer would
373/// not match the `iss` claim in tokens minted by the IdP.
374fn validate_issuer_url(issuer: &str) -> Result<(), &'static str> {
375 let url = Url::parse(issuer).map_err(|_| "oidc_issuer is not a parseable URL")?;
376 if !matches!(url.scheme(), "https" | "http") {
377 return Err("oidc_issuer must use the https or http scheme");
378 }
379 if !url.username().is_empty() || url.password().is_some() {
380 return Err("oidc_issuer must not contain userinfo");
381 }
382 if url.query().is_some() || url.fragment().is_some() {
383 return Err("oidc_issuer must not contain a query or fragment");
384 }
385 Ok(())
386}
387
388/// Builds the absolute URL of the protected resource metadata document
389/// for use as the `resource_metadata` parameter in a `WWW-Authenticate`
390/// challenge. Returns `None` if the request lacks enough host information
391/// to construct a URL; the caller is expected to skip the Bearer challenge
392/// in that case rather than emit a malformed value.
393pub(crate) fn metadata_url(req: &Request, http_host_name: Option<&str>) -> Option<String> {
394 let host = resolve_host(req, http_host_name)?;
395 Some(format!(
396 "{PUBLISHED_SCHEME}://{host}{PROTECTED_RESOURCE_METADATA_PATH}"
397 ))
398}
399
400/// Resolves the host string to embed in published absolute URLs.
401///
402/// Prefers the operator-configured `http_host_name`; falls back to the
403/// request's `Host` header. **Never consults `X-Forwarded-*`**. See the
404/// module-level "Host derivation" notes.
405///
406/// The returned value is parsed through [`http::uri::Authority`] before
407/// it is returned, so it is guaranteed to be a syntactically valid
408/// `host[:port]` per RFC 3986. This is the second layer of defense
409/// against header-smuggling attacks: even if a future change accepts a
410/// malicious value as input, the parser rejects anything containing
411/// characters outside the URI host grammar (notably `"`, whitespace,
412/// `;`, etc.) so the value cannot break out of the quoted
413/// `resource_metadata="..."` parameter in a `WWW-Authenticate` challenge
414/// or smuggle additional fields into the published `resource` URL.
415fn resolve_host(req: &Request, http_host_name: Option<&str>) -> Option<String> {
416 let candidate = http_host_name
417 .map(str::trim)
418 .filter(|s| !s.is_empty())
419 .map(str::to_string)
420 .or_else(|| {
421 req.headers()
422 .get(http::header::HOST)
423 .and_then(|v| v.to_str().ok())
424 .map(str::trim)
425 .filter(|s| !s.is_empty())
426 .map(str::to_string)
427 })?;
428 // Reject `user@host` explicitly. `Authority::as_str()` keeps userinfo,
429 // so the round-trip below would pass it through, letting an attacker
430 // poison the published URLs via a forged `Host: bobby@evil...`.
431 if candidate.contains('@') {
432 return None;
433 }
434 // Round-trip through `http::uri::Authority` to confirm the value is
435 // a syntactically valid `host[:port]`. This rejects header-smuggling
436 // payloads (quotes, whitespace, control chars, parameter-delimiters)
437 // that `HeaderValue::from_str` lets through.
438 let authority = candidate.parse::<http::uri::Authority>().ok()?;
439 if authority.as_str() != candidate {
440 return None;
441 }
442 Some(candidate)
443}
444
445#[cfg(test)]
446mod tests {
447 use super::*;
448
449 use axum::body::Body;
450 use http::Request;
451
452 fn req_with_host(host: &str) -> Request<Body> {
453 Request::builder()
454 .header(http::header::HOST, host)
455 .body(Body::empty())
456 .unwrap()
457 }
458
459 /// Pin the serialized field names; clients key off them.
460 #[mz_ore::test]
461 fn test_metadata_serialization_matches_rfc9728_field_names() {
462 let metadata = ProtectedResourceMetadata {
463 resource: "https://mcp.example.com/api/mcp".to_string(),
464 authorization_servers: vec!["https://auth.example.com".to_string()],
465 bearer_methods_supported: vec!["header".to_string()],
466 scopes_supported: vec!["mcp.read".to_string()],
467 };
468 let json = serde_json::to_value(&metadata).unwrap();
469 assert_eq!(
470 json,
471 serde_json::json!({
472 "resource": "https://mcp.example.com/api/mcp",
473 "authorization_servers": ["https://auth.example.com"],
474 "bearer_methods_supported": ["header"],
475 "scopes_supported": ["mcp.read"],
476 }),
477 );
478 }
479
480 /// The well-known path is part of the public contract with clients.
481 #[mz_ore::test]
482 fn test_well_known_path_is_rfc9728_canonical() {
483 assert_eq!(
484 PROTECTED_RESOURCE_METADATA_PATH,
485 "/.well-known/oauth-protected-resource",
486 );
487 }
488
489 /// `http_host_name` beats the request's Host header.
490 #[mz_ore::test]
491 fn test_resolve_host_prefers_http_host_name() {
492 let req = req_with_host("internal.local:6876");
493 assert_eq!(
494 resolve_host(&req, Some("public.example.com")).as_deref(),
495 Some("public.example.com"),
496 );
497 }
498
499 /// Empty or whitespace-only `http_host_name` falls back to `Host`.
500 #[mz_ore::test]
501 fn test_resolve_host_ignores_blank_config() {
502 let req = req_with_host("public.example.com");
503 for blank in ["", " ", "\t"] {
504 assert_eq!(
505 resolve_host(&req, Some(blank)).as_deref(),
506 Some("public.example.com"),
507 "blank http_host_name = {blank:?} should fall back to Host",
508 );
509 }
510 }
511
512 /// Host header is the final fallback; port must be preserved.
513 #[mz_ore::test]
514 fn test_resolve_host_falls_back_to_host_header_with_port() {
515 let req = req_with_host("example.com:8080");
516 assert_eq!(
517 resolve_host(&req, None).as_deref(),
518 Some("example.com:8080"),
519 );
520 }
521
522 /// Security regression guard: `X-Forwarded-Host` is never trusted
523 /// (see module-level "Host derivation" notes).
524 #[mz_ore::test]
525 fn test_resolve_host_ignores_x_forwarded_host() {
526 let req = Request::builder()
527 .header(http::header::HOST, "honest.example.com")
528 .header("x-forwarded-host", "evil.example.com")
529 .body(Body::empty())
530 .unwrap();
531 assert_eq!(
532 resolve_host(&req, None).as_deref(),
533 Some("honest.example.com"),
534 "X-Forwarded-Host must not influence the resolved host",
535 );
536 }
537
538 /// No host config and no `Host` header → `None`.
539 #[mz_ore::test]
540 fn test_resolve_host_returns_none_when_unavailable() {
541 let req = Request::builder().body(Body::empty()).unwrap();
542 assert_eq!(resolve_host(&req, None), None);
543 }
544
545 /// Defense in depth against Host-header smuggling: per-payload
546 /// comments below describe the specific failure each one would cause.
547 #[mz_ore::test]
548 fn test_resolve_host_rejects_smuggled_characters() {
549 for malicious in [
550 // The headline regression: closes the quoted
551 // resource_metadata parameter and injects a second one.
552 "attacker.example.net\" foo=bar",
553 // Whitespace splits the `host:port` token.
554 "host with space.example.com",
555 // Semicolons inside a quoted parameter still terminate
556 // `auth-param` values in some lenient parsers.
557 "host\";evil=1",
558 // Backslash is reserved in URI host grammar.
559 "host\\backslash",
560 // Quote alone is enough to terminate the parameter.
561 "host\"quote",
562 ] {
563 let req = req_with_host(malicious);
564 assert_eq!(
565 resolve_host(&req, None),
566 None,
567 "smuggling payload via Host header must be rejected: {malicious:?}",
568 );
569 assert_eq!(
570 resolve_host(&req, Some(malicious)),
571 None,
572 "smuggling payload via http_host_name must be rejected: {malicious:?}",
573 );
574 }
575 }
576
577 /// `http::uri::Authority` accepts a `userinfo@host` form, but the
578 /// round-trip check in `resolve_host` must reject it: if we accepted
579 /// it, an attacker could send `Host: bobby@evil.example.com` and
580 /// poison the published `resource` URL with their own prefix.
581 #[mz_ore::test]
582 fn test_resolve_host_rejects_userinfo() {
583 for malicious in [
584 "user@host.example.com",
585 "user:pass@host.example.com",
586 "@host.example.com",
587 "user@host.example.com:8080",
588 "user:pass@host.example.com:8080",
589 ] {
590 let req = req_with_host(malicious);
591 assert_eq!(
592 resolve_host(&req, None),
593 None,
594 "userinfo in Host header must be rejected: {malicious:?}",
595 );
596 assert_eq!(
597 resolve_host(&req, Some(malicious)),
598 None,
599 "userinfo in http_host_name must be rejected: {malicious:?}",
600 );
601 }
602 }
603
604 /// Pin the assembled URL: accidental path drift (extra slashes,
605 /// dropped suffix) breaks every connected client.
606 #[mz_ore::test]
607 fn test_metadata_url_assembles_canonical_suffix() {
608 let req = req_with_host("example.com");
609 assert_eq!(
610 metadata_url(&req, Some("public.example.com")).as_deref(),
611 Some("https://public.example.com/.well-known/oauth-protected-resource"),
612 );
613 }
614
615 /// Pin the path-suffixed aliases; strict RFC 9728 §3.1 clients
616 /// probe these before the bare URI.
617 #[mz_ore::test]
618 fn test_path_suffixed_alias_paths_are_correct() {
619 assert_eq!(
620 PROTECTED_RESOURCE_METADATA_PATH_UNIFIED,
621 "/.well-known/oauth-protected-resource/api/mcp",
622 );
623 assert_eq!(
624 PROTECTED_RESOURCE_METADATA_PATH_AGENT,
625 "/.well-known/oauth-protected-resource/api/mcp/agent",
626 );
627 assert_eq!(
628 PROTECTED_RESOURCE_METADATA_PATH_DEVELOPER,
629 "/.well-known/oauth-protected-resource/api/mcp/developer",
630 );
631 }
632
633 /// Pin the wire-visible scope string; clients ask the IdP for a
634 /// token with this exact value.
635 #[mz_ore::test]
636 fn test_mcp_scope_constant() {
637 assert_eq!(MCP_SCOPE, "mcp.read");
638 }
639
640 /// Counter families only appear in `gather()` after a label
641 /// combination is observed, so each status value is touched first.
642 #[mz_ore::test]
643 fn test_metric_registers() {
644 let registry = MetricsRegistry::new();
645 let metrics = OauthMetadataMetrics::register_into(®istry);
646 for status in [
647 MetricStatus::Ok,
648 MetricStatus::Disabled,
649 MetricStatus::NoIssuer,
650 MetricStatus::InvalidIssuer,
651 MetricStatus::NoHost,
652 MetricStatus::AdapterUnavailable,
653 ] {
654 metrics.inc(status);
655 }
656 let names: Vec<String> = registry
657 .gather()
658 .iter()
659 .map(|m| m.name().to_string())
660 .collect();
661 assert!(
662 names
663 .iter()
664 .any(|n| n == "mz_oauth_protected_resource_metadata_requests_total"),
665 "metric should be registered, got: {names:?}",
666 );
667 }
668
669 /// IPv6 literals (`[::1]:8080`) are valid `Authority` syntax and
670 /// must round-trip. A regression silently breaks IPv6 deployments.
671 #[mz_ore::test]
672 fn test_resolve_host_accepts_ipv6_literal() {
673 for host in ["[::1]", "[::1]:8080", "[2001:db8::1]:443"] {
674 let req = req_with_host(host);
675 assert_eq!(
676 resolve_host(&req, None).as_deref(),
677 Some(host),
678 "IPv6 literal must round-trip through Authority: {host:?}",
679 );
680 }
681 }
682
683 /// Well-formed issuers pass through unchanged; normalisation
684 /// would break byte-for-byte match against the `iss` token claim.
685 #[mz_ore::test]
686 fn test_validate_issuer_url_accepts_well_formed() {
687 for issuer in [
688 "https://issuer.example.com",
689 "https://issuer.example.com/realms/main",
690 "http://localhost:8080",
691 ] {
692 assert_eq!(
693 validate_issuer_url(issuer),
694 Ok(()),
695 "expected {issuer:?} to pass validation",
696 );
697 }
698 }
699
700 /// Pin the authenticator-to-discovery mapping so a refactor doesn't
701 /// silently steer MCP clients into a flow the listener can't honour.
702 #[mz_ore::test]
703 fn test_mcp_oauth_discovery_for_authenticator() {
704 use listeners::AuthenticatorKind;
705 // Oidc always advertises, regardless of the Frontegg issuer URL.
706 for issuer in [None, Some("https://ignored.example.com")] {
707 assert_eq!(
708 McpOAuthDiscovery::for_authenticator(AuthenticatorKind::Oidc, issuer),
709 McpOAuthDiscovery::Oidc,
710 );
711 }
712 // Frontegg requires a valid issuer URL; absent or invalid → Disabled.
713 assert_eq!(
714 McpOAuthDiscovery::for_authenticator(AuthenticatorKind::Frontegg, None),
715 McpOAuthDiscovery::Disabled,
716 );
717 assert_eq!(
718 McpOAuthDiscovery::for_authenticator(AuthenticatorKind::Frontegg, Some("not a url"),),
719 McpOAuthDiscovery::Disabled,
720 );
721 assert_eq!(
722 McpOAuthDiscovery::for_authenticator(
723 AuthenticatorKind::Frontegg,
724 Some("https://acme.frontegg.com"),
725 ),
726 McpOAuthDiscovery::Frontegg {
727 issuer: "https://acme.frontegg.com".to_string(),
728 },
729 );
730 // Non-token authenticators stay disabled even with an issuer URL set.
731 for kind in [
732 AuthenticatorKind::None,
733 AuthenticatorKind::Password,
734 AuthenticatorKind::Sasl,
735 ] {
736 for issuer in [None, Some("https://acme.frontegg.com")] {
737 assert_eq!(
738 McpOAuthDiscovery::for_authenticator(kind, issuer),
739 McpOAuthDiscovery::Disabled,
740 "{kind:?} must not advertise OAuth",
741 );
742 }
743 }
744 assert!(McpOAuthDiscovery::Oidc.is_enabled());
745 assert!(!McpOAuthDiscovery::Disabled.is_enabled());
746 assert!(
747 McpOAuthDiscovery::Frontegg {
748 issuer: "https://acme.frontegg.com".to_string(),
749 }
750 .is_enabled()
751 );
752 }
753
754 /// Rejects values that would confuse clients downstream or leak
755 /// embedded secrets in a public document.
756 #[mz_ore::test]
757 fn test_validate_issuer_url_rejects_invalid() {
758 // Format: (issuer, expected substring of the error reason).
759 let cases: &[(&str, &str)] = &[
760 ("not a url", "parseable"),
761 ("issuer.example.com", "parseable"),
762 ("ftp://issuer.example.com", "scheme"),
763 ("https://user:pass@issuer.example.com", "userinfo"),
764 ("https://user@issuer.example.com", "userinfo"),
765 ("https://issuer.example.com?foo=bar", "query"),
766 ("https://issuer.example.com#frag", "query"),
767 ];
768 for (issuer, expected_substr) in cases {
769 let err = validate_issuer_url(issuer)
770 .expect_err(&format!("expected {issuer:?} to be rejected as invalid",));
771 assert!(
772 err.contains(expected_substr),
773 "for {issuer:?}, expected reason to contain {expected_substr:?}, got {err:?}",
774 );
775 }
776 }
777}