Skip to main content

mz_environmentd/
http.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//! Embedded HTTP server.
11//!
12//! environmentd embeds an HTTP server for introspection into the running
13//! process. At the moment, its primary exports are Prometheus metrics, heap
14//! profiles, and catalog dumps.
15//!
16//! ## Authentication/Authorization flow
17//!
18//! The server supports several authentication modes, controlled by the
19//! configured [`listeners::AuthenticatorKind`]. The general flow is:
20//!
21//! 1. **Authentication.** An authentication middleware runs on every
22//!    protected request and resolves the caller's identity via one of:
23//!    - **Credentials in headers.** The caller supplies a username/password or
24//!      token in the request headers. Supported by all [`listeners::AuthenticatorKind`]s.
25//!    - **Session reuse.** If the caller has an active authenticated session
26//!      (established via `POST /api/login`) and has not supplied credentials
27//!      in the request headers, the session is reused. Only available for
28//!      [`listeners::AuthenticatorKind::Password`] and [`listeners::AuthenticatorKind::Oidc`].
29//!    - **Trusted header injection.** A trusted upstream proxy (e.g. Teleport)
30//!      may inject the caller's identity into the request headers. Only available
31//!      for [`listeners::AuthenticatorKind::None`].
32//!
33//! 2. **Authorization.** The authentication middleware is followed by an authorization
34//!    middleware that checks if the caller's identity is allowed to access the route based on
35//!    its [`listeners::AllowedRoles`].
36//!
37//! 3. **Session initialization.** Once the caller's identity is known, an
38//!    adapter session is opened on their behalf. This happens as part of
39//!    request processing, after all middleware has run.
40//!
41//! 4. **Request handling.** The handler executes the request (e.g. runs SQL)
42//!    using the initialized adapter session.
43//!
44//! ### WebSocket
45//!
46//! The WebSocket flow is identical to the HTTP flow with two differences:
47//!
48//! - Credentials are not read from request headers. Instead, the first
49//!   message sent by the client is treated as the authentication message.
50//! - Authorization and session initialization (step 2 and 3) happen inside
51//!   the WebSocket handler itself, rather than as separate middleware steps.
52
53// Axum handlers must use async, but often don't actually use `await`.
54#![allow(clippy::unused_async)]
55
56use std::borrow::Cow;
57use std::collections::BTreeMap;
58use std::fmt::Debug;
59use std::net::{IpAddr, SocketAddr};
60use std::pin::Pin;
61use std::sync::Arc;
62use std::time::{Duration, SystemTime};
63
64use anyhow::Context;
65use axum::error_handling::HandleErrorLayer;
66use axum::extract::ws::{Message, WebSocket};
67use axum::extract::{ConnectInfo, DefaultBodyLimit, FromRequestParts, Query, Request, State};
68use axum::middleware::{self, Next};
69use axum::response::{IntoResponse, Redirect, Response};
70use axum::{Extension, Json, Router, routing};
71use futures::future::{Shared, TryFutureExt};
72use headers::authorization::{Authorization, Basic, Bearer};
73use headers::{HeaderMapExt, HeaderName};
74use http::header::{AUTHORIZATION, CONTENT_TYPE};
75use http::uri::Scheme;
76use http::{HeaderMap, HeaderValue, Method, StatusCode, Uri};
77use hyper_openssl::SslStream;
78use hyper_openssl::client::legacy::MaybeHttpsStream;
79use hyper_util::rt::TokioIo;
80use mz_adapter::session::{Session as AdapterSession, SessionConfig as AdapterSessionConfig};
81use mz_adapter::{AdapterError, AdapterNotice, Client, SessionClient, WebhookAppenderCache};
82use mz_adapter_types::dyncfgs::OIDC_GROUP_CLAIM;
83use mz_auth::Authenticated;
84use mz_auth::password::Password;
85use mz_auth::user::ExternalUserMetadata;
86use mz_authenticator::Authenticator;
87use mz_controller::ReplicaHttpLocator;
88use mz_dyncfg::ConfigSet;
89use mz_frontegg_auth::Error as FronteggError;
90use mz_http_util::DynamicFilterTarget;
91use mz_ore::cast::u64_to_usize;
92use mz_ore::metrics::MetricsRegistry;
93use mz_ore::now::{NowFn, SYSTEM_TIME, epoch_to_uuid_v7};
94use mz_ore::str::StrExt;
95use mz_pgwire_common::{ConnectionCounter, ConnectionHandle};
96use mz_server_core::listeners::{self, AllowedRoles, HttpRoutesEnabled, RouteGroup};
97use mz_server_core::{Connection, ConnectionHandler, ReloadingSslContext, Server};
98use mz_sql::session::metadata::SessionMetadata;
99use mz_sql::session::user::{
100    HTTP_DEFAULT_USER, INTERNAL_USER_NAMES, SUPPORT_USER_NAME, SYSTEM_USER_NAME,
101};
102use mz_sql::session::vars::{Value, Var, VarInput, WELCOME_MESSAGE};
103use openssl::ssl::Ssl;
104use prometheus::{
105    COMPUTE_METRIC_QUERIES, FRONTIER_METRIC_QUERIES, STORAGE_METRIC_QUERIES, USAGE_METRIC_QUERIES,
106};
107use serde::{Deserialize, Serialize};
108use serde_json::json;
109use thiserror::Error;
110use tokio::io::AsyncWriteExt;
111use tokio::sync::oneshot::Receiver;
112use tokio::sync::{oneshot, watch};
113use tokio_metrics::TaskMetrics;
114use tower::limit::GlobalConcurrencyLimitLayer;
115use tower::{Service, ServiceBuilder};
116use tower_http::cors::{AllowOrigin, Any, CorsLayer};
117use tower_sessions::{
118    MemoryStore as TowerSessionMemoryStore, Session as TowerSession,
119    SessionManagerLayer as TowerSessionManagerLayer,
120};
121use tracing::warn;
122
123use crate::BUILD_INFO;
124use crate::deployment::state::DeploymentStateHandle;
125use crate::http::sql::{ExistingUser, SqlError};
126
127mod catalog;
128mod cluster;
129mod console;
130mod mcp;
131pub mod mcp_metrics;
132mod memory;
133mod metrics;
134mod metrics_public;
135mod metrics_viz;
136pub(crate) mod oauth_metadata;
137mod probe;
138mod prometheus;
139mod root;
140mod sql;
141mod webhook;
142
143pub use metrics::Metrics;
144pub use sql::{SqlResponse, WebSocketAuth, WebSocketResponse};
145
146/// Maximum allowed size for a request.
147pub const MAX_REQUEST_SIZE: usize = u64_to_usize(5 * bytesize::MIB);
148
149const SESSION_DURATION: Duration = Duration::from_secs(8 * 3600); // 8 hours
150
151const PROFILING_API_ENDPOINTS: &[&str] = &["/memory", "/hierarchical-memory", "/prof/"];
152
153#[derive(Debug)]
154pub struct HttpConfig {
155    pub source: &'static str,
156    pub tls: Option<ReloadingSslContext>,
157    pub authenticator_kind: listeners::AuthenticatorKind,
158    pub frontegg: Option<mz_frontegg_auth::Authenticator>,
159    pub oidc_rx: Delayed<mz_authenticator::GenericOidcAuthenticator>,
160    pub adapter_client_rx: Shared<Receiver<Client>>,
161    pub allowed_origin: AllowOrigin,
162    /// Raw list of allowed CORS origins, used by the MCP endpoints for
163    /// server-side Origin validation to defend against DNS rebinding.
164    pub allowed_origin_list: Vec<HeaderValue>,
165    pub active_connection_counter: ConnectionCounter,
166    pub helm_chart_version: Option<String>,
167    /// Externally-visible host name for this environment (without scheme).
168    ///
169    /// Used as the canonical host when constructing absolute URLs that the
170    /// server needs to publish (e.g. the OAuth Protected Resource Metadata
171    /// `resource` field, RFC 9728). When `None`, callers fall back to the
172    /// request's `Host` header, which is correct for unproxied dev setups
173    /// but loses fidelity behind a load balancer that rewrites Host.
174    /// `X-Forwarded-*` headers are never consulted, see the
175    /// `oauth_metadata` module docs.
176    pub http_host_name: Option<String>,
177    pub frontegg_oauth_issuer_url: Option<String>,
178    pub concurrent_webhook_req: Arc<tokio::sync::Semaphore>,
179    pub dyncfgs: Arc<ConfigSet>,
180    pub metrics: Metrics,
181    pub metrics_registry: MetricsRegistry,
182    pub mcp_metrics: mcp_metrics::McpMetrics,
183    pub oauth_metadata_metrics: oauth_metadata::OauthMetadataMetrics,
184    pub internal_route_config: Arc<InternalRouteConfig>,
185    pub routes_enabled: HttpRoutesEnabled,
186    /// Locator for cluster replica HTTP addresses, used for proxying requests.
187    pub replica_http_locator: Arc<ReplicaHttpLocator>,
188}
189
190#[derive(Debug, Clone)]
191pub struct InternalRouteConfig {
192    pub deployment_state_handle: DeploymentStateHandle,
193    pub internal_console_redirect_url: Option<String>,
194}
195
196#[derive(Clone)]
197pub struct WsState {
198    frontegg: Option<mz_frontegg_auth::Authenticator>,
199    oidc_rx: Delayed<mz_authenticator::GenericOidcAuthenticator>,
200    authenticator_kind: listeners::AuthenticatorKind,
201    adapter_client_rx: Delayed<mz_adapter::Client>,
202    active_connection_counter: ConnectionCounter,
203    helm_chart_version: Option<String>,
204    allowed_roles: AllowedRoles,
205}
206
207#[derive(Clone)]
208pub struct WebhookState {
209    adapter_client_rx: Delayed<mz_adapter::Client>,
210    webhook_cache: WebhookAppenderCache,
211    dyncfgs: Arc<ConfigSet>,
212}
213
214#[derive(Clone, Debug)]
215struct HelmChartVersion(Option<String>);
216
217#[derive(Debug)]
218pub struct HttpServer {
219    tls: Option<ReloadingSslContext>,
220    router: Router,
221}
222
223impl HttpServer {
224    pub fn new(
225        HttpConfig {
226            source,
227            tls,
228            authenticator_kind,
229            frontegg,
230            oidc_rx,
231            adapter_client_rx,
232            allowed_origin,
233            allowed_origin_list,
234            active_connection_counter,
235            helm_chart_version,
236            http_host_name,
237            frontegg_oauth_issuer_url,
238            concurrent_webhook_req,
239            dyncfgs,
240            metrics,
241            metrics_registry,
242            mcp_metrics,
243            oauth_metadata_metrics,
244            internal_route_config,
245            routes_enabled,
246            replica_http_locator,
247        }: HttpConfig,
248    ) -> HttpServer {
249        let tls_enabled = tls.is_some();
250        let webhook_cache = WebhookAppenderCache::new();
251
252        // Compute OAuth discovery once per listener so the Bearer challenge
253        // and the discovery handler always agree, and the middleware doesn't
254        // re-derive (and re-allocate the Frontegg issuer) on each request.
255        let oauth_discovery = Arc::new(oauth_metadata::McpOAuthDiscovery::for_authenticator(
256            authenticator_kind,
257            frontegg_oauth_issuer_url.as_deref(),
258        ));
259
260        // Create secure session store and manager
261        let session_store = TowerSessionMemoryStore::default();
262        let session_layer = TowerSessionManagerLayer::new(session_store)
263            .with_secure(tls_enabled) // Enforce HTTPS
264            .with_same_site(tower_sessions::cookie::SameSite::Strict) // Prevent CSRF
265            .with_http_only(true) // Prevent XSS
266            .with_name("mz_session") // Custom cookie name
267            .with_path("/"); // Set cookie path
268
269        let frontegg_middleware = frontegg.clone();
270        let oidc_middleware_rx = oidc_rx.clone();
271        let adapter_client_middleware_rx = adapter_client_rx.clone();
272        let auth_middleware = middleware::from_fn(move |req, next| {
273            let frontegg = frontegg_middleware.clone();
274            let oidc_rx = oidc_middleware_rx.clone();
275            let adapter_client_rx = adapter_client_middleware_rx.clone();
276            async move {
277                http_auth(
278                    req,
279                    next,
280                    tls_enabled,
281                    authenticator_kind,
282                    frontegg,
283                    oidc_rx,
284                    adapter_client_rx,
285                )
286                .await
287            }
288        });
289        let mut router = Router::new();
290        let mut base_router = Router::new();
291        let cluster_proxy_config = Arc::new(cluster::ClusterProxyConfig::new(Arc::clone(
292            &replica_http_locator,
293        )));
294        if let RouteGroup::Enabled(base_roles) = routes_enabled.base {
295            let base_group = Router::new()
296                .route(
297                    "/",
298                    routing::get(move || async move { root::handle_home(routes_enabled).await }),
299                )
300                .route("/api/sql", routing::post(sql::handle_sql))
301                .route("/memory", routing::get(memory::handle_memory))
302                .route(
303                    "/hierarchical-memory",
304                    routing::get(memory::handle_hierarchical_memory),
305                )
306                .route(
307                    "/metrics-viz",
308                    routing::get(metrics_viz::handle_metrics_viz),
309                )
310                .route("/static/{*path}", routing::get(root::handle_static))
311                .route(
312                    "/metrics/public",
313                    routing::get(metrics_public::handle_public_metrics),
314                )
315                .layer(Extension(metrics_registry.clone()))
316                .layer(Extension(Arc::clone(&cluster_proxy_config)))
317                .authorize(base_roles);
318            base_router = base_router.merge(base_group);
319
320            let mut ws_router = Router::new()
321                .route("/api/experimental/sql", routing::get(sql::handle_sql_ws))
322                .with_state(WsState {
323                    frontegg,
324                    oidc_rx: oidc_rx.clone(),
325                    authenticator_kind,
326                    adapter_client_rx: adapter_client_rx.clone(),
327                    active_connection_counter: active_connection_counter.clone(),
328                    helm_chart_version: helm_chart_version.clone(),
329                    // WS is gated by the base route group, so it enforces the
330                    // base group's roles
331                    allowed_roles: base_roles,
332                });
333            if let listeners::AuthenticatorKind::None = authenticator_kind {
334                ws_router = ws_router.layer(middleware::from_fn(x_materialize_user_header_auth));
335            }
336            router = router.merge(ws_router);
337        }
338        if let RouteGroup::Enabled(profiling_roles) = routes_enabled.profiling {
339            let profiling_group = Router::new()
340                .nest("/prof/", mz_prof_http::router(&BUILD_INFO))
341                .authorize(profiling_roles);
342            base_router = base_router.merge(profiling_group);
343        }
344
345        if routes_enabled.webhook.is_enabled() {
346            let webhook_router = Router::new()
347                .route(
348                    "/api/webhook/{:database}/{:schema}/{:id}",
349                    routing::post(webhook::handle_webhook),
350                )
351                .with_state(WebhookState {
352                    adapter_client_rx: adapter_client_rx.clone(),
353                    webhook_cache,
354                    dyncfgs,
355                })
356                .layer(
357                    tower_http::decompression::RequestDecompressionLayer::new()
358                        .gzip(true)
359                        .deflate(true)
360                        .br(true)
361                        .zstd(true),
362                )
363                // The webhook handler enforces WEBHOOK_MAX_REQUEST_SIZE_BYTES
364                // itself via to_bytes on a raw Body. This disable is defense-in-depth:
365                // it only matters if the handler ever returns to a Bytes extractor,
366                // which would otherwise inherit the global 5 MiB limit.
367                .layer(DefaultBodyLimit::disable())
368                .layer(
369                    CorsLayer::new()
370                        .allow_methods(Method::POST)
371                        .allow_origin(AllowOrigin::mirror_request())
372                        .allow_headers(Any),
373                )
374                .layer(
375                    ServiceBuilder::new()
376                        .layer(HandleErrorLayer::new(handle_load_error))
377                        .load_shed()
378                        .layer(GlobalConcurrencyLimitLayer::with_semaphore(
379                            concurrent_webhook_req,
380                        )),
381                );
382            router = router.merge(webhook_router);
383        }
384
385        if let RouteGroup::Enabled(internal_roles) = routes_enabled.internal {
386            let console_config = Arc::new(console::ConsoleProxyConfig::new(
387                internal_route_config.internal_console_redirect_url.clone(),
388                "/internal-console".to_string(),
389            ));
390            let internal_group = Router::new()
391                .route(
392                    "/api/opentelemetry/config",
393                    routing::put({
394                        move |_: axum::Json<DynamicFilterTarget>| async {
395                            (
396                                StatusCode::BAD_REQUEST,
397                                "This endpoint has been replaced. \
398                            Use the `opentelemetry_filter` system variable."
399                                    .to_string(),
400                            )
401                        }
402                    }),
403                )
404                .route(
405                    "/api/stderr/config",
406                    routing::put({
407                        move |_: axum::Json<DynamicFilterTarget>| async {
408                            (
409                                StatusCode::BAD_REQUEST,
410                                "This endpoint has been replaced. \
411                            Use the `log_filter` system variable."
412                                    .to_string(),
413                            )
414                        }
415                    }),
416                )
417                .route("/api/tracing", routing::get(mz_http_util::handle_tracing))
418                .route(
419                    "/api/catalog/dump",
420                    routing::get(catalog::handle_catalog_dump),
421                )
422                .route(
423                    "/api/catalog/check",
424                    routing::get(catalog::handle_catalog_check),
425                )
426                .route(
427                    "/api/catalog/inject-audit-events",
428                    routing::post(catalog::handle_inject_audit_events),
429                )
430                .route(
431                    "/api/coordinator/check",
432                    routing::get(catalog::handle_coordinator_check),
433                )
434                .route(
435                    "/api/coordinator/dump",
436                    routing::get(catalog::handle_coordinator_dump),
437                )
438                .route(
439                    "/internal-console",
440                    routing::get(|| async { Redirect::temporary("/internal-console/") }),
441                )
442                .route(
443                    "/internal-console/{*path}",
444                    routing::get(console::handle_internal_console)
445                        .post(console::handle_internal_console),
446                )
447                .route(
448                    "/internal-console/",
449                    routing::get(console::handle_internal_console)
450                        .post(console::handle_internal_console),
451                )
452                // Cluster HTTP proxy routes.
453                .route("/clusters", routing::get(cluster::handle_clusters))
454                .route(
455                    "/api/cluster/{:cluster_id}/replica/{:replica_id}/process/{:process}/",
456                    routing::any(cluster::handle_cluster_proxy_root),
457                )
458                .route(
459                    "/api/cluster/{:cluster_id}/replica/{:replica_id}/process/{:process}/{*path}",
460                    routing::any(cluster::handle_cluster_proxy),
461                )
462                .layer(Extension(console_config))
463                .layer(Extension(Arc::clone(&cluster_proxy_config)))
464                .authorize(internal_roles);
465            base_router = base_router.merge(internal_group);
466
467            let leader_router = Router::new()
468                .route("/api/leader/status", routing::get(handle_leader_status))
469                .route("/api/leader/promote", routing::post(handle_leader_promote))
470                .route(
471                    "/api/leader/skip-catchup",
472                    routing::post(handle_leader_skip_catchup),
473                )
474                .authorize(internal_roles)
475                .layer(auth_middleware.clone())
476                .with_state(internal_route_config.deployment_state_handle.clone());
477            router = router.merge(leader_router);
478        }
479
480        if let RouteGroup::Enabled(metrics_roles) = routes_enabled.metrics {
481            // Clone into the closure so the outer `metrics_registry` binding
482            // stays available for other route blocks below (e.g. MCP metric
483            // registration).
484            let metrics_registry_for_handler = metrics_registry.clone();
485            let metrics_router = Router::new()
486                .route(
487                    "/metrics",
488                    routing::get(move |headers: HeaderMap| async move {
489                        mz_http_util::handle_prometheus(&metrics_registry_for_handler, headers)
490                            .await
491                    }),
492                )
493                .route(
494                    "/metrics/mz_usage",
495                    routing::get(|client: AuthedClient, headers: HeaderMap| async move {
496                        let registry = sql::handle_promsql(client, USAGE_METRIC_QUERIES).await;
497                        mz_http_util::handle_prometheus(&registry, headers).await
498                    }),
499                )
500                .route(
501                    "/metrics/mz_frontier",
502                    routing::get(|client: AuthedClient, headers: HeaderMap| async move {
503                        let registry = sql::handle_promsql(client, FRONTIER_METRIC_QUERIES).await;
504                        mz_http_util::handle_prometheus(&registry, headers).await
505                    }),
506                )
507                .route(
508                    "/metrics/mz_compute",
509                    routing::get(|client: AuthedClient, headers: HeaderMap| async move {
510                        let registry = sql::handle_promsql(client, COMPUTE_METRIC_QUERIES).await;
511                        mz_http_util::handle_prometheus(&registry, headers).await
512                    }),
513                )
514                .route(
515                    "/metrics/mz_storage",
516                    routing::get(|client: AuthedClient, headers: HeaderMap| async move {
517                        let registry = sql::handle_promsql(client, STORAGE_METRIC_QUERIES).await;
518                        mz_http_util::handle_prometheus(&registry, headers).await
519                    }),
520                )
521                .route(
522                    "/api/livez",
523                    routing::get(mz_http_util::handle_liveness_check),
524                )
525                .route("/api/readyz", routing::get(probe::handle_ready))
526                .authorize(metrics_roles)
527                .layer(auth_middleware.clone())
528                .layer(Extension(adapter_client_rx.clone()))
529                .layer(Extension(active_connection_counter.clone()))
530                .layer(Extension(HelmChartVersion(helm_chart_version.clone())));
531            router = router.merge(metrics_router);
532        }
533
534        if routes_enabled.console_config.is_enabled() {
535            let console_config_router = Router::new()
536                .route(
537                    "/api/console/config",
538                    routing::get(console::handle_console_config),
539                )
540                .layer(Extension(adapter_client_rx.clone()))
541                .layer(Extension(active_connection_counter.clone()));
542            router = router.merge(console_config_router);
543        }
544
545        // MCP (Model Context Protocol) endpoints
546        if routes_enabled.mcp_agent.is_enabled()
547            || routes_enabled.mcp_developer.is_enabled()
548            || routes_enabled.mcp.is_enabled()
549        {
550            use tracing::info;
551
552            // RFC 9728 Protected Resource Metadata. Public route: MCP
553            // clients fetch it before they have a token. Sits on its own
554            // router so the auth middleware never runs on it. The handler
555            // 404s when the listener does not advertise OAuth (see
556            // `McpOAuthDiscovery`) or `oidc_issuer` is unset, so it is safe
557            // to enable unconditionally whenever MCP is enabled.
558            // RFC 9728 ยง3.1 lets clients look up per-resource metadata
559            // via a path-suffixed well-known URI before falling back to
560            // the bare one. The MCP endpoints share an identical
561            // metadata view, so we serve the same handler at every path.
562            let oauth_metadata_router = Router::new()
563                .route(
564                    oauth_metadata::PROTECTED_RESOURCE_METADATA_PATH,
565                    routing::get(oauth_metadata::handle_protected_resource_metadata),
566                )
567                .route(
568                    oauth_metadata::PROTECTED_RESOURCE_METADATA_PATH_UNIFIED,
569                    routing::get(oauth_metadata::handle_protected_resource_metadata),
570                )
571                .route(
572                    oauth_metadata::PROTECTED_RESOURCE_METADATA_PATH_AGENT,
573                    routing::get(oauth_metadata::handle_protected_resource_metadata),
574                )
575                .route(
576                    oauth_metadata::PROTECTED_RESOURCE_METADATA_PATH_DEVELOPER,
577                    routing::get(oauth_metadata::handle_protected_resource_metadata),
578                )
579                .layer(Extension(adapter_client_rx.clone()))
580                .layer(Extension(oauth_metadata::McpOAuthConfig {
581                    http_host_name: http_host_name.clone(),
582                    discovery: Arc::clone(&oauth_discovery),
583                }))
584                .layer(Extension(oauth_metadata_metrics.clone()));
585            router = router.merge(oauth_metadata_router);
586
587            let mut mcp_router = Router::new();
588
589            if let RouteGroup::Enabled(mcp_agent_roles) = routes_enabled.mcp_agent {
590                info!("Enabling MCP agent endpoint: /api/mcp/agent");
591                let agent_router = Router::new()
592                    .route(
593                        "/api/mcp/agent",
594                        routing::post(mcp::handle_mcp_agent)
595                            .get(mcp::handle_mcp_method_not_allowed),
596                    )
597                    .authorize(mcp_agent_roles);
598                mcp_router = mcp_router.merge(agent_router);
599            }
600
601            if let RouteGroup::Enabled(mcp_developer_roles) = routes_enabled.mcp_developer {
602                info!("Enabling MCP developer endpoint: /api/mcp/developer");
603                let developer_router = Router::new()
604                    .route(
605                        "/api/mcp/developer",
606                        routing::post(mcp::handle_mcp_developer)
607                            .get(mcp::handle_mcp_method_not_allowed),
608                    )
609                    .authorize(mcp_developer_roles);
610                mcp_router = mcp_router.merge(developer_router);
611            }
612
613            if let RouteGroup::Enabled(mcp_roles) = routes_enabled.mcp {
614                info!("Enabling MCP endpoint: /api/mcp");
615                let unified_router = Router::new()
616                    .route(
617                        "/api/mcp",
618                        routing::post(mcp::handle_mcp_unified)
619                            .get(mcp::handle_mcp_method_not_allowed),
620                    )
621                    .authorize(mcp_roles);
622                mcp_router = mcp_router.merge(unified_router);
623            }
624
625            // The MCP handlers perform a server-side Origin check against this
626            // allowlist to defend against DNS rebinding attacks (see
627            // database-issues#11311). The CorsLayer alone is not enough: in a
628            // DNS rebinding attack the browser considers the request
629            // same-origin, so no preflight fires and CORS enforcement is
630            // bypassed.
631            let mcp_allowed_origins = Arc::new(allowed_origin_list.clone());
632            mcp_router = mcp_router
633                .layer(auth_middleware.clone())
634                .layer(Extension(oauth_metadata::McpOAuthConfig {
635                    http_host_name: http_host_name.clone(),
636                    discovery: Arc::clone(&oauth_discovery),
637                }))
638                .layer(Extension(adapter_client_rx.clone()))
639                .layer(Extension(active_connection_counter.clone()))
640                .layer(Extension(HelmChartVersion(helm_chart_version.clone())))
641                .layer(Extension(mcp_allowed_origins))
642                .layer(Extension(mcp_metrics))
643                .layer(
644                    CorsLayer::new()
645                        .allow_methods(Method::POST)
646                        .allow_origin(allowed_origin.clone())
647                        // The transport's own request headers, which a browser
648                        // client on an allowed origin must be able to send.
649                        .allow_headers([
650                            AUTHORIZATION,
651                            CONTENT_TYPE,
652                            HeaderName::from_static("mcp-protocol-version"),
653                            HeaderName::from_static("mcp-method"),
654                            HeaderName::from_static("mcp-name"),
655                        ]),
656                );
657            // Trust `x-materialize-user` injected by an upstream proxy on
658            // listeners without HTTP auth, matching `base_router` and
659            // `ws_router` (CLO-158).
660            if let listeners::AuthenticatorKind::None = authenticator_kind {
661                mcp_router = mcp_router.layer(middleware::from_fn(x_materialize_user_header_auth));
662            }
663            router = router.merge(mcp_router);
664        }
665
666        base_router = base_router
667            .layer(auth_middleware.clone())
668            .layer(Extension(adapter_client_rx.clone()))
669            .layer(Extension(active_connection_counter.clone()))
670            .layer(Extension(HelmChartVersion(helm_chart_version)))
671            .layer(
672                CorsLayer::new()
673                    .allow_credentials(false)
674                    .allow_headers([
675                        AUTHORIZATION,
676                        CONTENT_TYPE,
677                        HeaderName::from_static("x-materialize-version"),
678                    ])
679                    .allow_methods(Any)
680                    .allow_origin(allowed_origin)
681                    .expose_headers(Any)
682                    .max_age(Duration::from_secs(60) * 60),
683            );
684
685        match authenticator_kind {
686            listeners::AuthenticatorKind::Password | listeners::AuthenticatorKind::Oidc => {
687                base_router = base_router.layer(session_layer.clone());
688
689                let login_router = Router::new()
690                    .route("/api/login", routing::post(handle_login))
691                    .route("/api/logout", routing::post(handle_logout))
692                    .layer(Extension(adapter_client_rx));
693                router = router.merge(login_router).layer(session_layer);
694            }
695            listeners::AuthenticatorKind::None => {
696                base_router =
697                    base_router.layer(middleware::from_fn(x_materialize_user_header_auth));
698            }
699            _ => {}
700        }
701
702        router = router
703            .merge(base_router)
704            .apply_default_layers(source, metrics);
705
706        HttpServer { tls, router }
707    }
708}
709
710impl Server for HttpServer {
711    const NAME: &'static str = "http";
712
713    fn handle_connection(
714        &self,
715        conn: Connection,
716        _tokio_metrics_intervals: impl Iterator<Item = TaskMetrics> + Send + 'static,
717    ) -> ConnectionHandler {
718        let router = self.router.clone();
719        let tls_context = self.tls.clone();
720        let mut conn = TokioIo::new(conn);
721
722        Box::pin(async {
723            let direct_peer_addr = conn.inner().peer_addr().context("fetching peer addr")?;
724            let peer_addr = conn
725                .inner_mut()
726                .take_proxy_header_address()
727                .await
728                .map(|a| a.source)
729                .unwrap_or(direct_peer_addr);
730
731            let (conn, conn_protocol) = match tls_context {
732                Some(tls_context) => {
733                    let mut ssl_stream = SslStream::new(Ssl::new(&tls_context.get())?, conn)?;
734                    if let Err(e) = Pin::new(&mut ssl_stream).accept().await {
735                        let _ = ssl_stream.get_mut().inner_mut().shutdown().await;
736                        return Err(e.into());
737                    }
738                    (MaybeHttpsStream::Https(ssl_stream), ConnProtocol::Https)
739                }
740                _ => (MaybeHttpsStream::Http(conn), ConnProtocol::Http),
741            };
742            let mut make_tower_svc = router
743                .layer(Extension(conn_protocol))
744                .into_make_service_with_connect_info::<SocketAddr>();
745            let tower_svc = make_tower_svc.call(peer_addr).await.unwrap();
746            let hyper_svc = hyper::service::service_fn(|req| tower_svc.clone().call(req));
747            let http = hyper::server::conn::http1::Builder::new();
748            http.serve_connection(conn, hyper_svc)
749                .with_upgrades()
750                .err_into()
751                .await
752        })
753    }
754}
755
756pub async fn handle_leader_status(
757    State(deployment_state_handle): State<DeploymentStateHandle>,
758) -> impl IntoResponse {
759    let status = deployment_state_handle.status();
760    (StatusCode::OK, Json(json!({ "status": status })))
761}
762
763pub async fn handle_leader_promote(
764    State(deployment_state_handle): State<DeploymentStateHandle>,
765) -> impl IntoResponse {
766    match deployment_state_handle.try_promote() {
767        Ok(()) => {
768            // TODO(benesch): the body here is redundant. Should just return
769            // 204.
770            let status = StatusCode::OK;
771            let body = Json(json!({
772                "result": "Success",
773            }));
774            (status, body)
775        }
776        Err(()) => {
777            // TODO(benesch): the nesting here is redundant given the error
778            // code. Should just return the `{"message": "..."}` object.
779            let status = StatusCode::BAD_REQUEST;
780            let body = Json(json!({
781                "result": {"Failure": {"message": "cannot promote leader while initializing"}},
782            }));
783            (status, body)
784        }
785    }
786}
787
788pub async fn handle_leader_skip_catchup(
789    State(deployment_state_handle): State<DeploymentStateHandle>,
790) -> impl IntoResponse {
791    match deployment_state_handle.try_skip_catchup() {
792        Ok(()) => StatusCode::NO_CONTENT.into_response(),
793        Err(()) => {
794            let status = StatusCode::BAD_REQUEST;
795            let body = Json(json!({
796                "message": "cannot skip catchup in this phase of initialization; try again later",
797            }));
798            (status, body).into_response()
799        }
800    }
801}
802
803async fn x_materialize_user_header_auth(mut req: Request, next: Next) -> impl IntoResponse {
804    // TODO migrate teleport to basic auth and remove this.
805    if let Some(username) = req.headers().get("x-materialize-user").map(|h| h.to_str()) {
806        let username = match username {
807            Ok(name @ (SUPPORT_USER_NAME | SYSTEM_USER_NAME)) => name.to_string(),
808            _ => {
809                return Err(AuthError::MismatchedUser(format!(
810                    "user specified in x-materialize-user must be {SUPPORT_USER_NAME} or {SYSTEM_USER_NAME}"
811                )));
812            }
813        };
814        // Authorization runs later: for HTTP routes
815        // in the `http_authz` middleware, and for WebSocket connections inside
816        // `init_ws`. This middleware only resolves the injected identity.
817        req.extensions_mut().insert(AuthedUser {
818            name: username,
819            external_metadata_rx: None,
820            authenticated: Authenticated,
821            authenticator_kind: mz_auth::AuthenticatorKind::None,
822            groups: None,
823        });
824    }
825    Ok(next.run(req).await)
826}
827
828pub(crate) type Delayed<T> = Shared<oneshot::Receiver<T>>;
829
830/// Resolve the dyncfg-configured group claim path from a delayed adapter
831/// client. Callers must already have driven `adapter_client_rx` to readiness
832/// (e.g. via `get_authenticator`), so the await here is non-blocking.
833async fn group_claim_for(adapter_client_rx: &Delayed<Client>) -> String {
834    let client = adapter_client_rx
835        .clone()
836        .await
837        .expect("adapter client receiver dropped");
838    OIDC_GROUP_CLAIM.get(client.get_system_vars().await.dyncfgs())
839}
840
841#[derive(Clone)]
842enum ConnProtocol {
843    Http,
844    Https,
845}
846
847/// The `allowed_roles` policy for a route group, attached as a request
848/// extension on each authenticated route group and read by [`http_authz`].
849#[derive(Clone, Copy)]
850struct RouteAllowedRoles(AllowedRoles);
851
852/// Router extension for attaching the authorization middleware.
853trait AuthzRouterExt {
854    fn authorize(self, roles: AllowedRoles) -> Self;
855}
856
857impl<S> AuthzRouterExt for Router<S>
858where
859    S: Clone + Send + Sync + 'static,
860{
861    fn authorize(self, roles: AllowedRoles) -> Router<S> {
862        // Adds the `RouteAllowedRoles` extension to the request such that
863        // `http_authz` knows which roles to check for a RouteGroup.
864        self.layer(middleware::from_fn(http_authz))
865            .layer(Extension(RouteAllowedRoles(roles)))
866    }
867}
868
869#[derive(Clone, Debug)]
870pub struct AuthedUser {
871    name: String,
872    external_metadata_rx: Option<watch::Receiver<ExternalUserMetadata>>,
873    authenticated: Authenticated,
874    authenticator_kind: mz_auth::AuthenticatorKind,
875    /// Groups from JWT claims for OIDC group-to-role sync.
876    groups: Option<Vec<String>>,
877}
878
879pub struct AuthedClient {
880    pub client: SessionClient,
881    pub connection_guard: Option<ConnectionHandle>,
882}
883
884impl AuthedClient {
885    async fn new<F>(
886        adapter_client: &Client,
887        user: AuthedUser,
888        peer_addr: IpAddr,
889        active_connection_counter: ConnectionCounter,
890        helm_chart_version: Option<String>,
891        session_config: F,
892        options: BTreeMap<String, String>,
893        now: NowFn,
894    ) -> Result<Self, AdapterError>
895    where
896        F: FnOnce(&mut AdapterSession),
897    {
898        let conn_id = adapter_client.new_conn_id()?;
899        let mut session = adapter_client.new_session(
900            AdapterSessionConfig {
901                conn_id,
902                uuid: epoch_to_uuid_v7(&(now)()),
903                user: user.name,
904                client_ip: Some(peer_addr),
905                external_metadata_rx: user.external_metadata_rx,
906                helm_chart_version,
907                authenticator_kind: user.authenticator_kind,
908                groups: user.groups,
909            },
910            user.authenticated,
911        );
912        let connection_guard = active_connection_counter.allocate_connection(session.user())?;
913
914        session_config(&mut session);
915        if !options.is_empty() {
916            let system_vars = adapter_client.get_system_vars().await;
917            for (key, val) in options {
918                const LOCAL: bool = false;
919                if let Err(err) =
920                    session
921                        .vars_mut()
922                        .set(&system_vars, &key, VarInput::Flat(&val), LOCAL)
923                {
924                    session.add_notice(AdapterNotice::BadStartupSetting {
925                        name: key.to_string(),
926                        reason: err.to_string(),
927                    })
928                }
929            }
930        }
931        let adapter_client = adapter_client.startup(session).await?;
932        Ok(AuthedClient {
933            client: adapter_client,
934            connection_guard,
935        })
936    }
937}
938
939impl<S> FromRequestParts<S> for AuthedClient
940where
941    S: Send + Sync,
942{
943    type Rejection = Response;
944
945    async fn from_request_parts(
946        req: &mut http::request::Parts,
947        state: &S,
948    ) -> Result<Self, Self::Rejection> {
949        #[derive(Debug, Default, Deserialize)]
950        struct Params {
951            #[serde(default)]
952            options: String,
953        }
954        let params: Query<Params> = Query::from_request_parts(req, state)
955            .await
956            .unwrap_or_default();
957
958        let peer_addr = req
959            .extensions
960            .get::<ConnectInfo<SocketAddr>>()
961            .expect("ConnectInfo extension guaranteed to exist")
962            .0
963            .ip();
964
965        let user = req.extensions.get::<AuthedUser>().unwrap();
966        let adapter_client = req
967            .extensions
968            .get::<Delayed<mz_adapter::Client>>()
969            .unwrap()
970            .clone();
971        let adapter_client = adapter_client.await.map_err(|_| {
972            (StatusCode::INTERNAL_SERVER_ERROR, "adapter client missing").into_response()
973        })?;
974        let active_connection_counter = req.extensions.get::<ConnectionCounter>().unwrap();
975        let helm_chart_version = req
976            .extensions
977            .get::<HelmChartVersion>()
978            .map(|h| h.0.clone())
979            .unwrap_or(None);
980
981        let options = if params.options.is_empty() {
982            // It's possible 'options' simply wasn't provided, we don't want that to
983            // count as a failure to deserialize
984            BTreeMap::<String, String>::default()
985        } else {
986            match serde_json::from_str(&params.options) {
987                Ok(options) => options,
988                Err(_e) => {
989                    // If we fail to deserialize options, fail the request.
990                    let code = StatusCode::BAD_REQUEST;
991                    let msg = format!("Failed to deserialize {} map", "options".quoted());
992                    return Err((code, msg).into_response());
993                }
994            }
995        };
996
997        let client = AuthedClient::new(
998            &adapter_client,
999            user.clone(),
1000            peer_addr,
1001            active_connection_counter.clone(),
1002            helm_chart_version,
1003            |session| {
1004                session
1005                    .vars_mut()
1006                    .set_default(WELCOME_MESSAGE.name(), VarInput::Flat(&false.format()))
1007                    .expect("known to exist")
1008            },
1009            options,
1010            SYSTEM_TIME.clone(),
1011        )
1012        .await
1013        .map_err(|e| {
1014            let status = match e {
1015                AdapterError::UserSessionsDisallowed | AdapterError::NetworkPolicyDenied(_) => {
1016                    StatusCode::FORBIDDEN
1017                }
1018                _ => StatusCode::INTERNAL_SERVER_ERROR,
1019            };
1020            (status, Json(SqlError::from(e))).into_response()
1021        })?;
1022
1023        Ok(client)
1024    }
1025}
1026
1027/// Per-request decision about which `WWW-Authenticate` challenges to emit
1028/// on a 401, computed by the auth middleware.
1029///
1030/// Carries both the `Basic` toggle, which the SQL HTTP layer also uses, and
1031/// an optional `Bearer` challenge with a
1032/// `resource_metadata` URL per RFC 9728. The Bearer challenge is only set on
1033/// routes that attach an [`oauth_metadata::McpOAuthConfig`] extension; other
1034/// routes emit only `Basic` so their behavior is unchanged.
1035#[derive(Debug, Clone, Default)]
1036pub(crate) struct WwwAuthenticateChallenges {
1037    /// Whether to emit `WWW-Authenticate: Basic realm=Materialize`.
1038    pub include_basic: bool,
1039    /// If `Some`, also emit `WWW-Authenticate: Bearer
1040    /// resource_metadata="<url>"`. The URL points at this server's RFC 9728
1041    /// Protected Resource Metadata document, which advertises the
1042    /// authorization server the client should use.
1043    pub bearer_resource_metadata: Option<String>,
1044    /// If `Some`, also emit `scope="<scope>"` inside the Bearer challenge.
1045    /// Tells clients which OAuth scope to request a token with for this
1046    /// resource. Only set in conjunction with `bearer_resource_metadata`
1047    /// (a scope challenge with no resource hint would be confusing).
1048    pub bearer_scope: Option<&'static str>,
1049}
1050
1051#[derive(Debug, Error)]
1052pub(crate) enum AuthError {
1053    #[error("role dissallowed")]
1054    RoleDisallowed(String),
1055    #[error("{0}")]
1056    Frontegg(#[from] FronteggError),
1057    #[error("missing authorization header")]
1058    MissingHttpAuthentication {
1059        challenges: WwwAuthenticateChallenges,
1060    },
1061    #[error("{0}")]
1062    MismatchedUser(String),
1063    #[error("session expired")]
1064    SessionExpired,
1065    #[error("failed to update session")]
1066    FailedToUpdateSession,
1067    #[error("invalid credentials")]
1068    InvalidCredentials,
1069    /// Payload is `OidcError`'s sanitized `Display` (no expected-values leaks).
1070    #[error("{0}")]
1071    OidcFailed(String),
1072}
1073
1074impl IntoResponse for AuthError {
1075    fn into_response(self) -> Response {
1076        warn!("HTTP request failed authentication: {}", self);
1077        let mut headers = HeaderMap::new();
1078        // We omit most detail from the error message we send to the client, to
1079        // avoid giving attackers unnecessary information. `OidcFailed` is the
1080        // exception: its payload is a sanitized `OidcError::Display` that the
1081        // console embeds in the login-page error.
1082        let body = match &self {
1083            // Bearer goes first so OAuth-aware clients see it before the
1084            // Basic fallback. RFC 7235 allows emitting multiple
1085            // `WWW-Authenticate` headers; we use one per scheme so each
1086            // challenge is unambiguously framed; some parsers struggle
1087            // with multiple schemes on a single header value.
1088            AuthError::MissingHttpAuthentication { challenges } => {
1089                if let Some(resource_metadata) = &challenges.bearer_resource_metadata {
1090                    // `scope` is hard-coded to a vetted constant
1091                    // (`MCP_SCOPE`); only `resource_metadata` is derived
1092                    // from a header value, and `resolve_host` has already
1093                    // round-tripped it through the URI grammar. The quoted
1094                    // form follows RFC 6749 ยง3.3 / RFC 6750 ยง3.
1095                    let value = match &challenges.bearer_scope {
1096                        Some(scope) => format!(
1097                            "Bearer scope=\"{scope}\", resource_metadata=\"{resource_metadata}\"",
1098                        ),
1099                        None => format!("Bearer resource_metadata=\"{resource_metadata}\""),
1100                    };
1101                    match HeaderValue::from_str(&value) {
1102                        Ok(v) => {
1103                            headers.append(http::header::WWW_AUTHENTICATE, v);
1104                        }
1105                        Err(e) => {
1106                            warn!(
1107                                "skipping Bearer WWW-Authenticate challenge: invalid header \
1108                                 value derived from resource_metadata={resource_metadata:?}: {e}",
1109                            );
1110                        }
1111                    }
1112                }
1113                if challenges.include_basic {
1114                    headers.append(
1115                        http::header::WWW_AUTHENTICATE,
1116                        HeaderValue::from_static("Basic realm=Materialize"),
1117                    );
1118                }
1119                "unauthorized".to_string()
1120            }
1121            AuthError::OidcFailed(message) => message.clone(),
1122            _ => "unauthorized".to_string(),
1123        };
1124        (StatusCode::UNAUTHORIZED, headers, body).into_response()
1125    }
1126}
1127
1128// Simplified login handler
1129pub async fn handle_login(
1130    session: Option<Extension<TowerSession>>,
1131    Extension(adapter_client_rx): Extension<Delayed<Client>>,
1132    Json(LoginCredentials { username, password }): Json<LoginCredentials>,
1133) -> impl IntoResponse {
1134    // The listener's `allowed_roles` policy is not enforced here. Login only
1135    // mints a session. Authorization runs per request in the `http_authz`
1136    // middleware (and in `init_ws` for WebSocket), so a session for a
1137    // disallowed role cannot actually reach any route.
1138    let Ok(adapter_client) = adapter_client_rx.clone().await else {
1139        return StatusCode::INTERNAL_SERVER_ERROR;
1140    };
1141    let authenticated = match adapter_client.authenticate(&username, &password).await {
1142        Ok(authenticated) => authenticated,
1143        Err(err) => {
1144            warn!(?err, "HTTP login failed authentication");
1145            return StatusCode::UNAUTHORIZED;
1146        }
1147    };
1148    // Create session data
1149    let session_data = TowerSessionData {
1150        username,
1151        created_at: SystemTime::now(),
1152        last_activity: SystemTime::now(),
1153        authenticated,
1154        authenticator_kind: mz_auth::AuthenticatorKind::Password,
1155    };
1156    // Store session data
1157    let session = session.and_then(|Extension(session)| Some(session));
1158    let Some(session) = session else {
1159        return StatusCode::INTERNAL_SERVER_ERROR;
1160    };
1161    match session.insert("data", &session_data).await {
1162        Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
1163        Ok(_) => StatusCode::OK,
1164    }
1165}
1166
1167// Simplified logout handler
1168pub async fn handle_logout(session: Option<Extension<TowerSession>>) -> impl IntoResponse {
1169    let session = session.and_then(|Extension(session)| Some(session));
1170    let Some(session) = session else {
1171        return StatusCode::INTERNAL_SERVER_ERROR;
1172    };
1173    // Delete session
1174    match session.delete().await {
1175        Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
1176        Ok(_) => StatusCode::OK,
1177    }
1178}
1179
1180/// Authentication middleware.
1181async fn http_auth(
1182    mut req: Request,
1183    next: Next,
1184    tls_enabled: bool,
1185    authenticator_kind: listeners::AuthenticatorKind,
1186    frontegg: Option<mz_frontegg_auth::Authenticator>,
1187    oidc_rx: Delayed<mz_authenticator::GenericOidcAuthenticator>,
1188    adapter_client_rx: Delayed<Client>,
1189) -> Result<impl IntoResponse, AuthError> {
1190    let creds = if let Some(basic) = req.headers().typed_get::<Authorization<Basic>>() {
1191        Some(Credentials::Password {
1192            username: basic.username().to_owned(),
1193            password: Password(basic.password().to_owned()),
1194        })
1195    } else if let Some(bearer) = req.headers().typed_get::<Authorization<Bearer>>() {
1196        Some(Credentials::Token {
1197            token: bearer.token().to_owned(),
1198        })
1199    } else {
1200        None
1201    };
1202
1203    // Reuses an authenticated session if one already exists.
1204    // If credentials are provided, we perform a new authentication,
1205    // separate from the existing session.
1206    if creds.is_none()
1207        && let Some((session, session_data)) =
1208            maybe_get_authenticated_session(req.extensions().get::<TowerSession>()).await
1209    {
1210        let user = ensure_session_unexpired(session, session_data).await?;
1211        // Authorization runs next in the `http_authz` middleware, which reads
1212        // this `AuthedUser` and the route's `RouteAllowedRoles`.
1213        req.extensions_mut().insert(user);
1214        return Ok(next.run(req).await);
1215    }
1216
1217    // First, extract the username from the certificate, validating that the
1218    // connection matches the TLS configuration along the way.
1219    // Fall back to existing authentication methods.
1220    let conn_protocol = req.extensions().get::<ConnProtocol>().unwrap();
1221    match (tls_enabled, &conn_protocol) {
1222        (false, ConnProtocol::Http) => {}
1223        (false, ConnProtocol::Https { .. }) => unreachable!(),
1224        (true, ConnProtocol::Http) => {
1225            let mut parts = req.uri().clone().into_parts();
1226            parts.scheme = Some(Scheme::HTTPS);
1227            return Ok(Redirect::permanent(
1228                &Uri::from_parts(parts)
1229                    .expect("it was already a URI, just changed the scheme")
1230                    .to_string(),
1231            )
1232            .into_response());
1233        }
1234        (true, ConnProtocol::Https { .. }) => {}
1235    }
1236    // If we've already passed some other auth, just use that.
1237    if req.extensions().get::<AuthedUser>().is_some() {
1238        return Ok(next.run(req).await);
1239    }
1240
1241    let path = req.uri().path();
1242    // Routes that advertise OAuth opt in by attaching an `McpOAuthConfig`
1243    // extension; the middleware stays path-agnostic. Routes that opt in also
1244    // get a `Basic` challenge so existing curl/Bearer-already users still see
1245    // a usable challenge. See `crate::http::oauth_metadata` for the discovery
1246    // document; the challenge and the discovery handler read the same
1247    // `McpOAuthConfig`, so they emit the same authorization server and the
1248    // same host for a given listener.
1249    let oauth_config = req
1250        .extensions()
1251        .get::<oauth_metadata::McpOAuthConfig>()
1252        .cloned();
1253    let include_basic = path == "/"
1254        || PROFILING_API_ENDPOINTS
1255            .iter()
1256            .any(|prefix| path.starts_with(prefix))
1257        || oauth_config.is_some();
1258    let (bearer_resource_metadata, bearer_scope) = if let Some(config) = &oauth_config
1259        && config.discovery.is_enabled()
1260    {
1261        (
1262            oauth_metadata::metadata_url(&req, config.http_host_name.as_deref()),
1263            Some(config.scope()),
1264        )
1265    } else {
1266        (None, None)
1267    };
1268    let challenges = WwwAuthenticateChallenges {
1269        include_basic,
1270        bearer_resource_metadata,
1271        bearer_scope,
1272    };
1273    let authenticator = get_authenticator(
1274        authenticator_kind,
1275        creds.as_ref(),
1276        frontegg,
1277        &oidc_rx,
1278        &adapter_client_rx,
1279    )
1280    .await;
1281
1282    // Only the Frontegg arm consumes `group_claim`; resolving it requires a
1283    // coordinator round-trip (`Command::GetSystemVars`), so skip it for
1284    // None/Password/OIDC paths. Otherwise unauth'd probes like `/api/livez`,
1285    // `/api/readyz`, and `/metrics` on a `None`-auth listener would couple
1286    // liveness to coordinator health. Mirrors the pgwire path.
1287    let group_claim = if matches!(authenticator, Authenticator::Frontegg(_)) {
1288        Some(group_claim_for(&adapter_client_rx).await)
1289    } else {
1290        None
1291    };
1292    let user = auth(&authenticator, creds, &challenges, group_claim.as_deref()).await?;
1293
1294    // Add the authenticated user as an extension so downstream handlers can
1295    // inspect it if necessary.
1296    req.extensions_mut().insert(user);
1297
1298    // Run the request.
1299    Ok(next.run(req).await)
1300}
1301
1302/// Authorization middleware. Enforces the route group's `allowed_roles` policy
1303/// against the authenticated user.
1304///
1305/// Layered immediately inside [`http_auth`] on every authenticated route group,
1306/// always paired with a [`RouteAllowedRoles`] extension. By that wiring both the
1307/// `AuthedUser` (from `http_auth`) and the `RouteAllowedRoles` extension are
1308/// present whenever this runs. A missing extension is a wiring bug, so we fail
1309/// closed rather than skip the check.
1310async fn http_authz(req: Request, next: Next) -> Result<impl IntoResponse, AuthError> {
1311    match (
1312        req.extensions().get::<AuthedUser>(),
1313        req.extensions().get::<RouteAllowedRoles>().copied(),
1314    ) {
1315        (Some(user), Some(RouteAllowedRoles(allowed_roles))) => {
1316            check_role_allowed(&user.name, allowed_roles)?;
1317            Ok(next.run(req).await)
1318        }
1319        _ => {
1320            warn!("http_authz missing AuthedUser or RouteAllowedRoles extension; denying request");
1321            Err(AuthError::RoleDisallowed("<unknown>".to_string()))
1322        }
1323    }
1324}
1325
1326async fn init_ws(
1327    WsState {
1328        frontegg,
1329        oidc_rx,
1330        authenticator_kind,
1331        adapter_client_rx,
1332        active_connection_counter,
1333        helm_chart_version,
1334        allowed_roles,
1335    }: WsState,
1336    existing_user: Option<ExistingUser>,
1337    peer_addr: IpAddr,
1338    ws: &mut WebSocket,
1339) -> Result<AuthedClient, anyhow::Error> {
1340    // TODO: Add a timeout here to prevent resource leaks by clients that
1341    // connect then never send a message.
1342    let ws_auth: WebSocketAuth = loop {
1343        let init_msg = ws.recv().await.ok_or_else(|| anyhow::anyhow!("closed"))??;
1344        match init_msg {
1345            Message::Text(data) => break serde_json::from_str(&data)?,
1346            Message::Binary(data) => break serde_json::from_slice(&data)?,
1347            // Handled automatically by the server.
1348            Message::Ping(_) => {
1349                continue;
1350            }
1351            Message::Pong(_) => {
1352                continue;
1353            }
1354            Message::Close(_) => {
1355                anyhow::bail!("closed");
1356            }
1357        }
1358    };
1359
1360    // If credentials are provided, we perform a new authentication,
1361    // separate from the existing session.
1362    let (creds, options) = match ws_auth {
1363        WebSocketAuth::Basic {
1364            user,
1365            password,
1366            options,
1367        } => {
1368            let creds = Credentials::Password {
1369                username: user,
1370                password,
1371            };
1372            (Some(creds), options)
1373        }
1374        WebSocketAuth::Bearer { token, options } => {
1375            let creds = Credentials::Token { token };
1376            (Some(creds), options)
1377        }
1378        WebSocketAuth::OptionsOnly { options } => (None, options),
1379    };
1380
1381    let user = match (existing_user, creds) {
1382        (Some(ExistingUser::XMaterializeUserHeader(_)), Some(_creds)) => {
1383            warn!("Unexpected bearer or basic auth provided when using user header");
1384            anyhow::bail!("unexpected")
1385        }
1386        (Some(ExistingUser::Session(user)), None) => user,
1387        (Some(ExistingUser::XMaterializeUserHeader(user)), None) => user,
1388        (_, Some(creds)) => {
1389            let authenticator = get_authenticator(
1390                authenticator_kind,
1391                Some(&creds),
1392                frontegg,
1393                &oidc_rx,
1394                &adapter_client_rx,
1395            )
1396            .await;
1397            // WebSocket init: no 401-with-challenge contract, the
1398            // client is reading WS frames, not parsing HTTP headers, so
1399            // we just suppress challenge emission entirely.
1400            let no_challenges = WwwAuthenticateChallenges::default();
1401            // See `http_auth`: only Frontegg uses `group_claim`, and the
1402            // fetch costs a coordinator round-trip.
1403            let group_claim = if matches!(authenticator, Authenticator::Frontegg(_)) {
1404                Some(group_claim_for(&adapter_client_rx).await)
1405            } else {
1406                None
1407            };
1408            let user = auth(
1409                &authenticator,
1410                Some(creds),
1411                &no_challenges,
1412                group_claim.as_deref(),
1413            )
1414            .await?;
1415            user
1416        }
1417        (None, None) => anyhow::bail!("expected auth information"),
1418    };
1419
1420    // Authorization. WebSocket connections authenticate after the HTTP upgrade
1421    // (by reading the first frame), so the `http_authz` middleware cannot cover
1422    // them. Enforce the authorization here instead, once, for every way
1423    // the user was resolved above (session, injected header, or credentials).
1424    check_role_allowed(&user.name, allowed_roles)?;
1425
1426    let client = AuthedClient::new(
1427        &adapter_client_rx.clone().await?,
1428        user,
1429        peer_addr,
1430        active_connection_counter.clone(),
1431        helm_chart_version.clone(),
1432        |_session| (),
1433        options,
1434        SYSTEM_TIME.clone(),
1435    )
1436    .await?;
1437
1438    Ok(client)
1439}
1440
1441enum Credentials {
1442    Password {
1443        username: String,
1444        password: Password,
1445    },
1446    Token {
1447        token: String,
1448    },
1449}
1450
1451async fn get_authenticator(
1452    kind: listeners::AuthenticatorKind,
1453    creds: Option<&Credentials>,
1454    frontegg: Option<mz_frontegg_auth::Authenticator>,
1455    oidc_rx: &Delayed<mz_authenticator::GenericOidcAuthenticator>,
1456    adapter_client_rx: &Delayed<Client>,
1457) -> Authenticator {
1458    match kind {
1459        listeners::AuthenticatorKind::Frontegg => Authenticator::Frontegg(frontegg.expect(
1460            "Frontegg authenticator should exist with listeners::AuthenticatorKind::Frontegg",
1461        )),
1462        listeners::AuthenticatorKind::Password | listeners::AuthenticatorKind::Sasl => {
1463            let client = adapter_client_rx.clone().await.expect("sender not dropped");
1464            Authenticator::Password(client)
1465        }
1466        listeners::AuthenticatorKind::Oidc => match creds {
1467            // Use the password authenticator if the credentials are password-based
1468            Some(Credentials::Password { .. }) => {
1469                let client = adapter_client_rx.clone().await.expect("sender not dropped");
1470                Authenticator::Password(client)
1471            }
1472            _ => Authenticator::Oidc(oidc_rx.clone().await.expect("sender not dropped")),
1473        },
1474        listeners::AuthenticatorKind::None => Authenticator::None,
1475    }
1476}
1477
1478/// Attempts to retrieve session data from a [`TowerSession`], if available.
1479/// Session data is present only if an authenticated session has been
1480/// established via [`handle_login`].
1481pub(crate) async fn maybe_get_authenticated_session(
1482    session: Option<&TowerSession>,
1483) -> Option<(&TowerSession, TowerSessionData)> {
1484    if let Some(session) = session {
1485        if let Ok(Some(session_data)) = session.get::<TowerSessionData>("data").await {
1486            return Some((session, session_data));
1487        }
1488    }
1489    None
1490}
1491
1492/// Ensures the session is still valid by checking for expiration,
1493/// and returns the associated user if the session remains active.
1494pub(crate) async fn ensure_session_unexpired(
1495    session: &TowerSession,
1496    session_data: TowerSessionData,
1497) -> Result<AuthedUser, AuthError> {
1498    if session_data
1499        .last_activity
1500        .elapsed()
1501        .unwrap_or(Duration::MAX)
1502        > SESSION_DURATION
1503    {
1504        let _ = session.delete().await;
1505        return Err(AuthError::SessionExpired);
1506    }
1507    let mut updated_data = session_data.clone();
1508    updated_data.last_activity = SystemTime::now();
1509    session
1510        .insert("data", &updated_data)
1511        .await
1512        .map_err(|_| AuthError::FailedToUpdateSession)?;
1513
1514    Ok(AuthedUser {
1515        name: session_data.username,
1516        external_metadata_rx: None,
1517        authenticated: session_data.authenticated,
1518        authenticator_kind: session_data.authenticator_kind,
1519        groups: None,
1520    })
1521}
1522
1523async fn auth(
1524    authenticator: &Authenticator,
1525    creds: Option<Credentials>,
1526    challenges: &WwwAuthenticateChallenges,
1527    group_claim: Option<&str>,
1528) -> Result<AuthedUser, AuthError> {
1529    let (name, external_metadata_rx, authenticated, groups) = match authenticator {
1530        Authenticator::Frontegg(frontegg) => match creds {
1531            Some(Credentials::Password { username, password }) => {
1532                let (auth_session, authenticated) = frontegg
1533                    .authenticate(&username, password.as_str(), group_claim)
1534                    .await?;
1535                let name = auth_session.user().into();
1536                let groups = auth_session.groups();
1537                let external_metadata_rx = Some(auth_session.external_metadata_rx());
1538                (name, external_metadata_rx, authenticated, groups)
1539            }
1540            Some(Credentials::Token { token }) => {
1541                let (claims, authenticated) =
1542                    frontegg.validate_access_token(&token, None, group_claim)?;
1543                let (_, external_metadata_rx) = watch::channel(ExternalUserMetadata {
1544                    user_id: claims.user_id,
1545                    admin: claims.is_admin,
1546                });
1547                (
1548                    claims.user,
1549                    Some(external_metadata_rx),
1550                    authenticated,
1551                    claims.groups,
1552                )
1553            }
1554            None => {
1555                return Err(AuthError::MissingHttpAuthentication {
1556                    challenges: challenges.clone(),
1557                });
1558            }
1559        },
1560        Authenticator::Password(adapter_client) => match creds {
1561            Some(Credentials::Password { username, password }) => {
1562                let authenticated = adapter_client
1563                    .authenticate(&username, &password)
1564                    .await
1565                    .map_err(|_| AuthError::InvalidCredentials)?;
1566                (username, None, authenticated, None)
1567            }
1568            _ => {
1569                return Err(AuthError::MissingHttpAuthentication {
1570                    challenges: challenges.clone(),
1571                });
1572            }
1573        },
1574        Authenticator::Sasl(_) => {
1575            // We shouldn't ever end up here as the configuration is validated at startup.
1576            // If we do, it's a server misconfiguration.
1577            // Just in case, we return a 401 rather than panic.
1578            return Err(AuthError::MissingHttpAuthentication {
1579                challenges: challenges.clone(),
1580            });
1581        }
1582        Authenticator::Oidc(oidc) => match creds {
1583            Some(Credentials::Token { token }) => {
1584                let (mut claims, authenticated) = oidc
1585                    .authenticate(&token, None)
1586                    .await
1587                    .map_err(|e| AuthError::OidcFailed(e.to_string()))?;
1588                let name = std::mem::take(&mut claims.user);
1589                let groups = claims.groups.take();
1590                (name, None, authenticated, groups)
1591            }
1592            _ => {
1593                return Err(AuthError::MissingHttpAuthentication {
1594                    challenges: challenges.clone(),
1595                });
1596            }
1597        },
1598        Authenticator::None => {
1599            // If no authentication, use whatever is in the HTTP auth
1600            // header (without checking the password), or fall back to the
1601            // default user.
1602            let name = match creds {
1603                Some(Credentials::Password { username, .. }) => username,
1604                _ => HTTP_DEFAULT_USER.name.to_owned(),
1605            };
1606            (name, None, Authenticated, None)
1607        }
1608    };
1609
1610    Ok(AuthedUser {
1611        name,
1612        external_metadata_rx,
1613        authenticated,
1614        authenticator_kind: authenticator.kind(),
1615        groups,
1616    })
1617}
1618
1619// TODO move this somewhere it can be shared with PGWIRE
1620fn check_role_allowed(name: &str, allowed_roles: AllowedRoles) -> Result<(), AuthError> {
1621    let is_internal_user = INTERNAL_USER_NAMES.contains(name);
1622    // this is a superset of internal users
1623    let is_reserved_user = mz_adapter::catalog::is_reserved_role_name(name);
1624    let role_allowed = match allowed_roles {
1625        AllowedRoles::Normal => !is_reserved_user,
1626        AllowedRoles::Internal => is_internal_user,
1627        AllowedRoles::NormalAndInternal => !is_reserved_user || is_internal_user,
1628    };
1629    if role_allowed {
1630        Ok(())
1631    } else {
1632        Err(AuthError::RoleDisallowed(name.to_owned()))
1633    }
1634}
1635
1636/// Default layers that should be applied to all routes, and should get applied to both the
1637/// internal http and external http routers.
1638trait DefaultLayers {
1639    fn apply_default_layers(self, source: &'static str, metrics: Metrics) -> Self;
1640}
1641
1642impl DefaultLayers for Router {
1643    fn apply_default_layers(self, source: &'static str, metrics: Metrics) -> Self {
1644        self.layer(DefaultBodyLimit::max(MAX_REQUEST_SIZE))
1645            .layer(metrics::PrometheusLayer::new(source, metrics))
1646    }
1647}
1648
1649/// Glue code to make [`tower`] work with [`axum`].
1650///
1651/// `axum` requires `Layer`s not return Errors, i.e. they must be `Result<_, Infallible>`,
1652/// instead you must return a type that can be converted into a response. `tower` on the other
1653/// hand does return Errors, so to make the two work together we need to convert our `tower` errors
1654/// into responses.
1655async fn handle_load_error(error: tower::BoxError) -> impl IntoResponse {
1656    if error.is::<tower::load_shed::error::Overloaded>() {
1657        return (
1658            StatusCode::TOO_MANY_REQUESTS,
1659            Cow::from("too many requests, try again later"),
1660        );
1661    }
1662
1663    // Note: This should be unreachable because at the time of writing our only use case is a
1664    // layer that emits `tower::load_shed::error::Overloaded`, which is handled above.
1665    (
1666        StatusCode::INTERNAL_SERVER_ERROR,
1667        Cow::from(format!("Unhandled internal error: {}", error)),
1668    )
1669}
1670
1671#[derive(Debug, Deserialize, Serialize, PartialEq)]
1672pub struct LoginCredentials {
1673    username: String,
1674    password: Password,
1675}
1676
1677#[derive(Debug, Clone, Serialize, Deserialize)]
1678pub struct TowerSessionData {
1679    username: String,
1680    created_at: SystemTime,
1681    last_activity: SystemTime,
1682    authenticated: Authenticated,
1683    authenticator_kind: mz_auth::AuthenticatorKind,
1684}
1685
1686#[cfg(test)]
1687mod tests {
1688    use super::{AllowedRoles, check_role_allowed};
1689
1690    #[mz_ore::test]
1691    fn test_check_role_allowed() {
1692        // Internal user
1693        assert!(check_role_allowed("mz_system", AllowedRoles::Internal).is_ok());
1694        assert!(check_role_allowed("mz_system", AllowedRoles::NormalAndInternal).is_ok());
1695        assert!(check_role_allowed("mz_system", AllowedRoles::Normal).is_err());
1696
1697        // Internal user
1698        assert!(check_role_allowed("mz_support", AllowedRoles::Internal).is_ok());
1699        assert!(check_role_allowed("mz_support", AllowedRoles::NormalAndInternal).is_ok());
1700        assert!(check_role_allowed("mz_support", AllowedRoles::Normal).is_err());
1701
1702        // Internal user
1703        assert!(check_role_allowed("mz_analytics", AllowedRoles::Internal).is_ok());
1704        assert!(check_role_allowed("mz_analytics", AllowedRoles::NormalAndInternal).is_ok());
1705        assert!(check_role_allowed("mz_analytics", AllowedRoles::Normal).is_err());
1706
1707        // Normal user
1708        assert!(check_role_allowed("materialize", AllowedRoles::Internal).is_err());
1709        assert!(check_role_allowed("materialize", AllowedRoles::NormalAndInternal).is_ok());
1710        assert!(check_role_allowed("materialize", AllowedRoles::Normal).is_ok());
1711
1712        // Normal user
1713        assert!(check_role_allowed("anonymous_http_user", AllowedRoles::Internal).is_err());
1714        assert!(check_role_allowed("anonymous_http_user", AllowedRoles::NormalAndInternal).is_ok());
1715        assert!(check_role_allowed("anonymous_http_user", AllowedRoles::Normal).is_ok());
1716
1717        // Normal user
1718        assert!(check_role_allowed("alex", AllowedRoles::Internal).is_err());
1719        assert!(check_role_allowed("alex", AllowedRoles::NormalAndInternal).is_ok());
1720        assert!(check_role_allowed("alex", AllowedRoles::Normal).is_ok());
1721
1722        // Denied by reserved role prefix
1723        assert!(check_role_allowed("external_asdf", AllowedRoles::Internal).is_err());
1724        assert!(check_role_allowed("external_asdf", AllowedRoles::NormalAndInternal).is_err());
1725        assert!(check_role_allowed("external_asdf", AllowedRoles::Normal).is_err());
1726
1727        // Denied by reserved role prefix
1728        assert!(check_role_allowed("pg_somebody", AllowedRoles::Internal).is_err());
1729        assert!(check_role_allowed("pg_somebody", AllowedRoles::NormalAndInternal).is_err());
1730        assert!(check_role_allowed("pg_somebody", AllowedRoles::Normal).is_err());
1731
1732        // Denied by reserved role prefix
1733        assert!(check_role_allowed("mz_unknown", AllowedRoles::Internal).is_err());
1734        assert!(check_role_allowed("mz_unknown", AllowedRoles::NormalAndInternal).is_err());
1735        assert!(check_role_allowed("mz_unknown", AllowedRoles::Normal).is_err());
1736
1737        // Denied by literal PUBLIC
1738        assert!(check_role_allowed("PUBLIC", AllowedRoles::Internal).is_err());
1739        assert!(check_role_allowed("PUBLIC", AllowedRoles::NormalAndInternal).is_err());
1740        assert!(check_role_allowed("PUBLIC", AllowedRoles::Normal).is_err());
1741    }
1742}