mz_environmentd/http/
console.rs1use 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
31const PREVIEW_BUILD_PARAM: &str = "preview_build";
34
35const PREVIEW_BUILD_COOKIE: &str = "mz_console_preview_build";
37
38const PREVIEW_BUILD_COOKIE_MAX_AGE_SECS: u64 = 60 * 60 * 24;
41
42pub(crate) struct ConsoleProxyConfig {
43 client: Client<HttpsConnector<HttpConnector>, Body>,
45
46 url: String,
48
49 route_prefix: String,
51
52 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 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
90const PREVIEW_BUILD_LABEL_PREFIX: &str = "console-git-";
94
95fn https_connector() -> HttpsConnector<HttpConnector> {
99 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
119static 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
128pub 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
155pub(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 *req.uri_mut() = uri;
194
195 req.headers_mut()
197 .insert(HOST, HeaderValue::from_str(&host).unwrap());
198
199 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 match preview_build {
207 Some((label, _)) => Ok(preview_build_unavailable_response(&label)),
208 None => Err(StatusCode::BAD_REQUEST),
209 }
210 }
211 }
212}
213
214fn 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 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
289fn 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 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
315fn 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
340fn 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
358fn 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}