Skip to main content

mz_environmentd/http/
console.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 Apach
9
10//! HTTP endpoints for the web console.
11
12use std::collections::BTreeMap;
13use std::sync::{Arc, LazyLock};
14
15use axum::Extension;
16use axum::Json;
17use axum::body::Body;
18use axum::http::{Request, StatusCode};
19use axum::response::{IntoResponse, Response};
20use http::header::{CONTENT_TYPE, COOKIE, HOST, LOCATION, ORIGIN, SET_COOKIE};
21use http::{HeaderMap, HeaderValue, Method};
22use hyper::Uri;
23use hyper_rustls::HttpsConnector;
24use hyper_util::client::legacy::Client;
25use hyper_util::client::legacy::connect::HttpConnector;
26use hyper_util::rt::TokioExecutor;
27use mz_adapter_types::dyncfgs::{CONSOLE_OIDC_CLIENT_ID, CONSOLE_OIDC_SCOPES, OIDC_ISSUER};
28
29use crate::http::Delayed;
30
31/// Query parameter that selects (or, with an empty value, clears) the console
32/// preview build this proxy serves to the requesting browser.
33const PREVIEW_BUILD_PARAM: &str = "preview_build";
34
35/// Cookie storing the selected preview build label.
36const PREVIEW_BUILD_COOKIE: &str = "mz_console_preview_build";
37
38/// Preview selections expire after a day so stale cookies drift back to the
39/// default build.
40const PREVIEW_BUILD_COOKIE_MAX_AGE_SECS: u64 = 60 * 60 * 24;
41
42pub(crate) struct ConsoleProxyConfig {
43    /// Hyper http client, supports https.
44    client: Client<HttpsConnector<HttpConnector>, Body>,
45
46    /// URL of upstream console to proxy to (e.g. <https://console.materialize.com>).
47    url: String,
48
49    /// Route this is being served from (e.g. /internal-console).
50    route_prefix: String,
51
52    /// Host of `url`, under which preview builds are served as subdomains
53    /// (e.g. `<label>.internal.console.materialize.com`).
54    preview_host_suffix: Option<String>,
55}
56
57impl ConsoleProxyConfig {
58    pub(crate) fn new(proxy_url: Option<String>, route_prefix: String) -> Self {
59        let mut url = proxy_url.unwrap_or_else(|| "https://console.materialize.com".to_string());
60        if let Some(new) = url.strip_suffix('/') {
61            url = new.to_string();
62        }
63        let preview_host_suffix = Uri::try_from(url.as_str())
64            .ok()
65            .and_then(|uri| uri.host().map(|host| host.to_string()));
66        Self {
67            client: Client::builder(TokioExecutor::new()).build(https_connector()),
68            url,
69            route_prefix,
70            preview_host_suffix,
71        }
72    }
73
74    /// Returns the upstream URL serving the given preview build, or `None` if
75    /// the label is invalid or no preview host suffix could be derived.
76    ///
77    /// NOTE: This proxy runs inside the environment's network, so it must not
78    /// be usable for SSRF. Preview builds are only ever fetched over https
79    /// from a validated subdomain of the configured upstream host, never from
80    /// a caller-provided URL.
81    fn preview_url(&self, label: &str) -> Option<String> {
82        let suffix = self.preview_host_suffix.as_deref()?;
83        if !is_valid_preview_build_label(label) {
84            return None;
85        }
86        Some(format!("https://{label}.{suffix}"))
87    }
88}
89
90/// Prefix required of preview build labels. CI only creates preview aliases
91/// under this prefix, so requiring it keeps the reachable hosts to builds of
92/// console pull requests.
93const PREVIEW_BUILD_LABEL_PREFIX: &str = "console-git-";
94
95/// A valid preview build label is a DNS label (1-63 characters of lowercase
96/// ASCII alphanumerics and hyphens, not ending with a hyphen) starting with
97/// [`PREVIEW_BUILD_LABEL_PREFIX`].
98fn https_connector() -> HttpsConnector<HttpConnector> {
99    // NOTE: Panics when the platform trust store has no certificates, which
100    // every image we ship includes.
101    hyper_rustls::HttpsConnectorBuilder::new()
102        .with_provider_and_native_roots(rustls::crypto::aws_lc_rs::default_provider())
103        .expect("loading native root certificates")
104        .https_or_http()
105        .enable_http1()
106        .enable_http2()
107        .build()
108}
109
110fn is_valid_preview_build_label(label: &str) -> bool {
111    label.len() <= 63
112        && label.starts_with(PREVIEW_BUILD_LABEL_PREFIX)
113        && label
114            .bytes()
115            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
116        && !label.ends_with('-')
117}
118
119/// OIDC configuration values needed by the Console to initiate OIDC login.
120static CONSOLE_CONFIG_VAR_NAMES: LazyLock<[&'static str; 3]> = LazyLock::new(|| {
121    [
122        OIDC_ISSUER.name(),
123        CONSOLE_OIDC_CLIENT_ID.name(),
124        CONSOLE_OIDC_SCOPES.name(),
125    ]
126});
127
128/// Returns system variable values the web console needs from
129/// environmentd. This endpoint requires no authentication.
130pub async fn handle_console_config(
131    Extension(adapter_client_rx): Extension<Delayed<mz_adapter::Client>>,
132) -> Result<Response, (StatusCode, String)> {
133    let adapter_client = adapter_client_rx.await.map_err(|_| {
134        (
135            StatusCode::INTERNAL_SERVER_ERROR,
136            "Adapter client unavailable".to_string(),
137        )
138    })?;
139
140    let system_vars = adapter_client.get_system_vars().await;
141    let mut config: BTreeMap<&str, String> = BTreeMap::new();
142    for var_name in CONSOLE_CONFIG_VAR_NAMES.iter() {
143        let value = system_vars.get(var_name).map(|v| v.value()).map_err(|_| {
144            (
145                StatusCode::INTERNAL_SERVER_ERROR,
146                format!("failed to retrieve system variable {var_name}"),
147            )
148        })?;
149        config.insert(var_name, value);
150    }
151
152    Ok((StatusCode::OK, Json(config)).into_response())
153}
154
155/// The User Impersonation feature uses a Teleport proxy in front of the
156/// Internal HTTP Server, however Teleport has issues with CORS that prevent
157/// making requests to that Teleport-proxied app from our production console URLs.
158/// To avoid CORS and serve the Console from the same host as the Teleport app,
159/// this route proxies the upstream Console to handle requests for
160/// HTML, JS, and CSS static files.
161///
162/// `?preview_build=<label>` selects a per-browser preview build served from a
163/// subdomain of the upstream host; an empty value returns to the default. A
164/// GET only renders a confirmation page. The selection itself requires a POST,
165/// so that a cross-site link cannot change which build a browser is served.
166pub(crate) async fn handle_internal_console(
167    console_config: Extension<Arc<ConsoleProxyConfig>>,
168    mut req: Request<Body>,
169) -> Result<Response, StatusCode> {
170    if let Some(response) = preview_build_selection_response(&console_config, &req)? {
171        return Ok(response);
172    }
173
174    let preview_build = preview_build_from_cookie(req.headers())
175        .and_then(|label| console_config.preview_url(&label).map(|url| (label, url)));
176    let upstream_url = preview_build
177        .as_ref()
178        .map_or_else(|| console_config.url.clone(), |(_, url)| url.clone());
179
180    let path = req.uri().path();
181    let mut path_query = req
182        .uri()
183        .path_and_query()
184        .map(|v| v.as_str())
185        .unwrap_or(path);
186    if let Some(stripped_path_query) = path_query.strip_prefix(&console_config.route_prefix) {
187        path_query = stripped_path_query;
188    }
189
190    let uri = Uri::try_from(format!("{}{}", upstream_url, path_query)).unwrap();
191    let host = uri.host().unwrap().to_string();
192    // Preserve the request, but update the URI to point upstream.
193    *req.uri_mut() = uri;
194
195    // If vercel sees the request being served from a different host it tries to redirect to it's own.
196    req.headers_mut()
197        .insert(HOST, HeaderValue::from_str(&host).unwrap());
198
199    // Call this request against the upstream, return response directly.
200    match console_config.client.request(req).await {
201        Ok(response) => Ok(response.into_response()),
202        Err(err) => {
203            tracing::warn!("Error retrieving console url: {}", err);
204            // A broken preview selection would otherwise present as an opaque
205            // error until the cookie expires, so offer the way back.
206            match preview_build {
207                Some((label, _)) => Ok(preview_build_unavailable_response(&label)),
208                None => Err(StatusCode::BAD_REQUEST),
209            }
210        }
211    }
212}
213
214/// Handles the `?preview_build=<label>` selection parameter. A GET with a
215/// label renders a confirmation page whose form POSTs the selection back; the
216/// POST stores it in a cookie and redirects to the same path without the
217/// parameter. The POST must additionally be same-origin (see
218/// [`is_same_origin`]), so a cross-site navigation cannot change the served
219/// build even if the fronting proxy's session cookie policy were to allow
220/// cross-site POSTs. Clearing (an empty label) is allowed on GET: it only
221/// ever restores the default build and is the recovery path for a broken
222/// selection. Returns `None` when the parameter is absent.
223fn preview_build_selection_response(
224    console_config: &ConsoleProxyConfig,
225    req: &Request<Body>,
226) -> Result<Option<Response>, StatusCode> {
227    let query = req.uri().query().unwrap_or("");
228    let mut selection = None;
229    let mut remaining_query = url::form_urlencoded::Serializer::new(String::new());
230    let mut any_remaining = false;
231    for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
232        if key == PREVIEW_BUILD_PARAM {
233            selection = Some(value.into_owned());
234        } else {
235            remaining_query.append_pair(&key, &value);
236            any_remaining = true;
237        }
238    }
239    let is_post = *req.method() == Method::POST;
240    if is_post && !is_same_origin(req) {
241        return Err(StatusCode::FORBIDDEN);
242    }
243    let Some(label) = selection else {
244        // The proxied upstream serves only static assets, so only selection
245        // POSTs are accepted.
246        if is_post {
247            return Err(StatusCode::METHOD_NOT_ALLOWED);
248        }
249        return Ok(None);
250    };
251
252    let cookie_attributes = format!(
253        "Path={}; Secure; HttpOnly; SameSite=Lax",
254        console_config.route_prefix
255    );
256    let cookie = if label.is_empty() {
257        format!("{PREVIEW_BUILD_COOKIE}=; Max-Age=0; {cookie_attributes}")
258    } else {
259        let Some(preview_url) = console_config.preview_url(&label) else {
260            return Err(StatusCode::BAD_REQUEST);
261        };
262        if !is_post {
263            return Ok(Some(preview_build_confirmation_response(
264                console_config,
265                &label,
266                &preview_url,
267            )));
268        }
269        format!(
270            "{PREVIEW_BUILD_COOKIE}={label}; \
271             Max-Age={PREVIEW_BUILD_COOKIE_MAX_AGE_SECS}; {cookie_attributes}"
272        )
273    };
274
275    let mut location = req.uri().path().to_string();
276    if any_remaining {
277        location.push('?');
278        location.push_str(&remaining_query.finish());
279    }
280    let response = Response::builder()
281        .status(StatusCode::SEE_OTHER)
282        .header(LOCATION, location)
283        .header(SET_COOKIE, cookie)
284        .body(Body::empty())
285        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
286    Ok(Some(response))
287}
288
289/// True unless the request was initiated by another site. Browser-set
290/// `Sec-Fetch-Site` cannot be forged by page scripts; `Origin` is the
291/// fallback for browsers predating it. The fronting proxy's `SameSite=Lax`
292/// session cookie also keeps a cross-site POST unauthenticated today, but
293/// that is its configuration, not this code's, so the check here is the
294/// layer this proxy owns.
295fn is_same_origin(req: &Request<Body>) -> bool {
296    if let Some(site) = req
297        .headers()
298        .get("sec-fetch-site")
299        .and_then(|v| v.to_str().ok())
300    {
301        return site == "same-origin" || site == "none";
302    }
303    let (Some(origin), Some(host)) = (req.headers().get(ORIGIN), req.headers().get(HOST)) else {
304        // No `Origin` on a POST means it was not a cross-site form submission.
305        return true;
306    };
307    let (Ok(origin), Ok(host)) = (origin.to_str(), host.to_str()) else {
308        return false;
309    };
310    origin
311        .split_once("://")
312        .is_some_and(|(_, authority)| authority == host)
313}
314
315/// Confirmation page for a preview build selection. All interpolated values
316/// are validated or config-controlled, never raw request input.
317fn preview_build_confirmation_response(
318    console_config: &ConsoleProxyConfig,
319    label: &str,
320    preview_url: &str,
321) -> Response {
322    let route_prefix = &console_config.route_prefix;
323    let body = format!(
324        "<!DOCTYPE html>\n\
325         <html><head><title>Console preview build</title></head><body>\n\
326         <p>Serve console assets in this browser from <code>{preview_url}</code> \
327         for the next 24 hours?</p>\n\
328         <form method=\"post\"><button type=\"submit\">Use preview build {label}</button></form>\n\
329         <p><a href=\"{route_prefix}/\">Cancel</a></p>\n\
330         </body></html>\n"
331    );
332    (
333        StatusCode::OK,
334        [(CONTENT_TYPE, "text/html; charset=utf-8")],
335        body,
336    )
337        .into_response()
338}
339
340/// Error page served when the selected preview build cannot be fetched,
341/// linking back to the default build.
342fn preview_build_unavailable_response(label: &str) -> Response {
343    let body = format!(
344        "<!DOCTYPE html>\n\
345         <html><head><title>Console preview build unavailable</title></head><body>\n\
346         <p>Failed to load console preview build <code>{label}</code>.</p>\n\
347         <p><a href=\"?{PREVIEW_BUILD_PARAM}=\">Return to the default console build</a></p>\n\
348         </body></html>\n"
349    );
350    (
351        StatusCode::BAD_GATEWAY,
352        [(CONTENT_TYPE, "text/html; charset=utf-8")],
353        body,
354    )
355        .into_response()
356}
357
358/// Returns the preview build label from the request's cookies, if one is set
359/// and valid. Invalid values are ignored rather than rejected so a stale
360/// cookie can never break the default console.
361fn preview_build_from_cookie(headers: &HeaderMap) -> Option<String> {
362    for header in headers.get_all(COOKIE) {
363        let Ok(header) = header.to_str() else {
364            continue;
365        };
366        for pair in header.split(';') {
367            let mut parts = pair.trim().splitn(2, '=');
368            if parts.next() == Some(PREVIEW_BUILD_COOKIE) {
369                let label = parts.next().unwrap_or("");
370                if is_valid_preview_build_label(label) {
371                    return Some(label.to_string());
372                }
373            }
374        }
375    }
376    None
377}