diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index f635790f5..f5c64e2d7 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -609,6 +609,10 @@ jobs: # a dev-mode server. This job starts one and exercises the data plane. runs-on: extenddb_ubuntu-2404_4-core timeout-minutes: 40 + # The server reads the listed name at startup, and the wire test that + # checks a listed name is served reads it too, so every step gets it. + env: + EXTENDDB__SERVER__DEV_ALLOWED_HOSTS: app.test steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 diff --git a/crates/app/src/cmd_serve.rs b/crates/app/src/cmd_serve.rs index 5ae4e2d5e..37257aec3 100755 --- a/crates/app/src/cmd_serve.rs +++ b/crates/app/src/cmd_serve.rs @@ -396,7 +396,9 @@ fn is_loopback_host(host: &str) -> bool { /// Print the developer-mode banner lines: the mode notice, the credentials to /// sign with, a warning block when the server is not bound to loopback, and an -/// advisory when an ambient `AWS_ACCESS_KEY_ID` would not verify. +/// advisory when an ambient `AWS_ACCESS_KEY_ID` would not verify. The banner +/// ends with the browser host rule and a note for each entry dropped from +/// `server.dev_allowed_hosts`. /// /// Resolving here (not just in `serve()`) fails fast on a misconfigured /// `EXTENDDB_DEV_*` pair before daemonizing, and gives the invoking user the @@ -411,12 +413,16 @@ fn print_dev_mode_banner( use extenddb_server::dev_credentials; let dev_creds = dev_credentials::resolve()?; + let dev_hosts = extenddb_server::parse_dev_allowed_hosts( + app_config.server.dev_allowed_hosts.as_deref().unwrap_or(""), + ); let lines = dev_mode_banner_lines( &config::redact_password(app_config.storage.connection_config()), app_config.server.bind_addr.trim(), port, &dev_creds, dev_credentials::ignored_aws_env_key(&dev_creds).as_deref(), + &dev_hosts, ); // Same stream split as the main banner: stdout for the daemon parent, // stderr in foreground mode so supervisors capture one stream. @@ -443,6 +449,7 @@ fn dev_mode_banner_lines( port: u16, dev_creds: &[extenddb_server::dev_credentials::DevCredential], ignored_aws_key: Option<&str>, + dev_hosts: &(Vec, Vec), ) -> Vec { use extenddb_server::dev_credentials; @@ -500,6 +507,16 @@ fn dev_mode_banner_lines( EXTENDDB_DEV_SECRET_ACCESS_KEY to seed an additional credential." )); } + // The host rule the server enforces, so the operator sees it without + // reading the log. Dropped entries are named too. + let (kept, dropped) = dev_hosts; + lines.push(format!(" {}", extenddb_server::dev_host_rule_line(kept))); + for entry in dropped { + lines.push(format!( + " Note: {}", + extenddb_server::dev_host_dropped_entry_note(entry) + )); + } lines } @@ -528,6 +545,12 @@ mod tests { } } + /// The banner of a server with no listed hosts, as one string. + fn banner(host: &str, port: u16, creds: &[DevCredential], ignored: Option<&str>) -> String { + dev_mode_banner_lines(":memory:", host, port, creds, ignored, &Default::default()) + .join("\n") + } + #[test] fn loopback_hosts_are_recognised() { for host in ["127.0.0.1", "127.1.2.3", "::1", "localhost"] { @@ -540,16 +563,14 @@ mod tests { #[test] fn loopback_dev_banner_has_no_exposure_warning() { - let text = - dev_mode_banner_lines(":memory:", "127.0.0.1", 18080, &[example()], None).join("\n"); + let text = banner("127.0.0.1", 18080, &[example()], None); assert!(text.contains("plain HTTP on loopback"), "{text}"); assert!(!text.contains("WARNING"), "{text}"); } #[test] fn non_loopback_dev_banner_warns_with_the_publish_command() { - let text = - dev_mode_banner_lines(":memory:", "0.0.0.0", 18080, &[example()], None).join("\n"); + let text = banner("0.0.0.0", 18080, &[example()], None); // The banner used to say "on loopback" whatever the bind was. assert!(!text.contains("plain HTTP on loopback"), "{text}"); assert!(text.contains("plain HTTP on 0.0.0.0"), "{text}"); @@ -564,7 +585,7 @@ mod tests { #[test] fn non_loopback_dev_banner_without_the_example_pair_drops_the_public_wording() { - let text = dev_mode_banner_lines(":memory:", "0.0.0.0", 9000, &[team()], None).join("\n"); + let text = banner("0.0.0.0", 9000, &[team()], None); assert!( text.contains("WARNING: dev mode is listening on 0.0.0.0:9000"), "{text}" @@ -582,14 +603,12 @@ mod tests { #[test] fn dev_banner_keeps_the_ignored_aws_key_note() { - let text = dev_mode_banner_lines( - ":memory:", + let text = banner( "127.0.0.1", 18080, &[example()], Some("ASIAFOREIGNSESSION01"), - ) - .join("\n"); + ); assert!( text.contains("'ASIAFOREIGNSESSION01' will be rejected"), "{text}" @@ -599,14 +618,7 @@ mod tests { #[test] fn dev_banner_names_the_switch_when_it_removed_the_ignored_example_key() { - let text = dev_mode_banner_lines( - ":memory:", - "127.0.0.1", - 18080, - &[team()], - Some(EXAMPLE_ACCESS_KEY_ID), - ) - .join("\n"); + let text = banner("127.0.0.1", 18080, &[team()], Some(EXAMPLE_ACCESS_KEY_ID)); assert!( text.contains(&format!("'{EXAMPLE_ACCESS_KEY_ID}' will be rejected")), "{text}" @@ -617,6 +629,24 @@ mod tests { ); } + #[test] + fn dev_banner_ends_with_the_host_rule_and_each_dropped_entry() { + let hosts = extenddb_server::parse_dev_allowed_hosts("app.test, bad host"); + let lines = + dev_mode_banner_lines(":memory:", "127.0.0.1", 18080, &[example()], None, &hosts); + assert_eq!( + lines[lines.len() - 2..], + [ + " ExtendDB serves a browser request, and any request to /management or \ + /metrics, only when its host is an IP address, localhost, a name ending in \ + .localhost, or a name in server.dev_allowed_hosts (environment variable \ + EXTENDDB__SERVER__DEV_ALLOWED_HOSTS). Listed hosts: app.test", + " Note: dev_allowed_hosts entry 'bad host' was ignored: list a bare host name \ + with no port, scheme or wildcard, such as app.test.", + ] + ); + } + /// Test wrapper so clap has a top-level `Parser` to drive `ServeArgs`. #[derive(Parser)] struct TestCli { diff --git a/crates/app/src/manage_http.rs b/crates/app/src/manage_http.rs index 62ae09261..96899b977 100755 --- a/crates/app/src/manage_http.rs +++ b/crates/app/src/manage_http.rs @@ -65,7 +65,18 @@ pub fn resolve_endpoint( } else { None }; - Ok((format!("{addr}:{}", app_config.server.port), use_tls, cert)) + Ok((host_port(addr, app_config.server.port), use_tls, cert)) +} + +/// `addr:port` for the TCP connect and the `Host` header. An IPv6 literal goes +/// in brackets, which the `Host` header requires; a developer-mode server +/// refuses a management request whose `Host` is not a valid host. +fn host_port(addr: &str, port: u16) -> String { + if addr.contains(':') && !addr.starts_with('[') { + format!("[{addr}]:{port}") + } else { + format!("{addr}:{port}") + } } /// Build a Basic auth header value. @@ -480,3 +491,16 @@ fn dispatch_cache(c: &Ctx<'_>, action: CacheAction) -> anyhow::Result<(u16, Stri }; c.req("POST", "/management/cache/invalidate", Some(&body)) } + +#[cfg(test)] +mod tests { + use super::host_port; + + #[test] + fn host_port_brackets_an_ipv6_bind_address() { + assert_eq!(host_port("127.0.0.1", 18443), "127.0.0.1:18443"); + assert_eq!(host_port("localhost", 18443), "localhost:18443"); + assert_eq!(host_port("::1", 18443), "[::1]:18443"); + assert_eq!(host_port("[::1]", 18443), "[::1]:18443"); + } +} diff --git a/crates/config/src/display.rs b/crates/config/src/display.rs index 46330c6d7..5682260a0 100644 --- a/crates/config/src/display.rs +++ b/crates/config/src/display.rs @@ -84,6 +84,13 @@ pub fn build_config_entries(cfg: &AppConfig) -> Vec<(String, String)> { .throttling_enabled .map_or("none".into(), |b| b.to_string()), ), + ( + "server.dev_allowed_hosts".into(), + cfg.server + .dev_allowed_hosts + .clone() + .unwrap_or_else(|| "none".into()), + ), ( format!("storage.{backend}.connection_string"), r("connection_string", cfg.storage.connection_config()), diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 57802782c..13918630a 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -84,6 +84,15 @@ pub struct ServerConfig { /// client can hold a connection open. Default 30. #[serde(default = "default_request_timeout_secs")] pub request_timeout_secs: u64, + /// Developer mode only: a single comma-separated string of bare host names + /// (no port, scheme or wildcard). The dev-mode host guard serves a browser + /// request, and any request to `/management` or `/metrics`, only under an + /// IP address, `localhost`, a `.localhost` name or one of these names. + /// `docs/manuals/05-admin-guide.md` describes the setting. A production + /// build does not use the value, but an array or a table still stops it at + /// startup. + #[serde(default)] + pub dev_allowed_hosts: Option, } fn default_request_timeout_secs() -> u64 { @@ -100,6 +109,7 @@ impl Default for ServerConfig { tls: TlsConfig::default(), throttling_enabled: None, request_timeout_secs: default_request_timeout_secs(), + dev_allowed_hosts: None, } } } diff --git a/crates/server/src/console/mod.rs b/crates/server/src/console/mod.rs index 647d3af4a..b21622a77 100755 --- a/crates/server/src/console/mod.rs +++ b/crates/server/src/console/mod.rs @@ -39,6 +39,28 @@ const CONTENT_SECURITY_POLICY: &str = "default-src 'none'; script-src 'self'; \ style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; \ base-uri 'none'; form-action 'self'; frame-ancestors 'none'"; +/// Render a standalone 403 page for a browser request the dev-mode host guard +/// refused before any session exists. `message` is the guard's own text, which +/// names the host and the setting; it is HTML-escaped here. +pub(crate) fn host_refused_page(message: &str) -> String { + let content = format!( + r#"
+
+

Request refused

+{alert} +
+
"#, + alert = html::alert_error(message), + ); + html::layout_full( + "Request refused", + r#""#, + &content, + None, + None, + ) +} + /// Shared state for console handlers. pub struct ConsoleState { pub sessions: SessionStore, diff --git a/crates/server/src/dev_host_guard.rs b/crates/server/src/dev_host_guard.rs new file mode 100644 index 000000000..f7491b4d7 --- /dev/null +++ b/crates/server/src/dev_host_guard.rs @@ -0,0 +1,379 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Developer-mode host guard. +//! +//! Developer mode serves plain HTTP on loopback with the IAM policy decision +//! open for an authenticated caller, and it seeds a well-known credential. A +//! web page served from a name that later resolves to the loopback address is +//! then same-origin with this server, so the browser sends the page's requests +//! to it with no preflight, and the page can sign them with the published +//! credential. This guard closes that path. +//! +//! A request is a browser request when it carries an `Origin` header or a +//! `Sec-Fetch-Site` header. A browser sends `Origin` on every request whose +//! method is not `GET` or `HEAD` and on every cross-origin CORS request, and it +//! sends `Sec-Fetch-*` headers only to `https` and loopback URLs. A page script +//! cannot remove either header, because both are forbidden request-header +//! names. The other `Sec-Fetch-*` headers do not count on their own: Node's +//! built-in `fetch` sends `Sec-Fetch-Mode: cors` by itself, and every browser +//! that sends Fetch Metadata sends `Sec-Fetch-Site` with it. The AWS SDKs and +//! the CLI send none of these headers. +//! +//! In developer mode a browser request is served only when its host is an IP +//! address, `localhost`, a name ending in `.localhost`, or a name the operator +//! lists in [`SETTING_KEY`]. Every other browser request is refused with 403 +//! before authentication. A call to the `DynamoDB` API and a console login are +//! `POST`s, which carry `Origin`, so a rebinding page can make neither. +//! +//! A same-origin `GET` or `HEAD` from a page served over plain HTTP from any +//! other name carries neither header, and the management routes and `/metrics` +//! answer `GET` with the admin password. Every request to `/management` and +//! below, and to `/metrics`, is therefore checked against the host rule +//! whether or not it carries a marker. A client that calls them through +//! another name, such as a Compose service name, needs that name listed. Any +//! other request with no marker is served as before, whatever its host. +//! +//! Firefox before 70 and `EdgeHTML` send no `Origin` on a `POST` and no +//! `Sec-Fetch-*` headers, so outside the admin routes the guard serves their +//! requests as it serves a non-browser client. The guard is installed only in +//! developer mode; production serving is unchanged. + +use std::net::{IpAddr, Ipv6Addr}; +use std::sync::Arc; + +use axum::Router; +use axum::extract::{Request, State}; +use axum::http::{HeaderMap, StatusCode, Uri}; +use axum::middleware::Next; +use axum::response::{Html, IntoResponse, Response}; +use extenddb_core::error::DynamoDbError; + +/// Configuration key for the operator-listed host names. +pub(crate) const SETTING_KEY: &str = "server.dev_allowed_hosts"; +/// Environment-variable form of [`SETTING_KEY`]. +pub(crate) const SETTING_ENV: &str = "EXTENDDB__SERVER__DEV_ALLOWED_HOSTS"; + +/// Path prefixes checked against the host rule on every request: the routes +/// that answer `GET` with the admin password. +const ADMIN_PREFIXES: [&str; 2] = ["/management", "/metrics"]; + +/// Per-request state for the host guard: the operator-listed host names, +/// validated and lowercased at startup. +#[derive(Clone)] +struct DevHostGuard { + allowed: Arc<[String]>, +} + +/// Wrap `app` in the guard when `dev_mode` is true; return it unchanged +/// otherwise. `start_server` calls this before it adds the security headers, +/// so the guard's 403s carry them. +pub(crate) fn install(app: Router, dev_mode: bool, allowed: Arc<[String]>) -> Router { + if !dev_mode { + return app; + } + let guard = Arc::new(DevHostGuard { allowed }); + app.layer(axum::middleware::from_fn_with_state(guard, enforce)) +} + +/// Parse [`SETTING_KEY`] at startup and log the rule and each dropped entry. +/// Returns the kept names; outside developer mode the setting is ignored and +/// the list is empty. +pub(crate) fn allowed_hosts(dev_mode: bool, raw: Option<&str>) -> Arc<[String]> { + if !dev_mode { + return Arc::from(Vec::new()); + } + let (kept, dropped) = parse_dev_allowed_hosts(raw.unwrap_or("")); + for entry in &dropped { + tracing::warn!("DEVELOPER MODE: {}", dropped_entry_note(entry)); + } + tracing::warn!("DEVELOPER MODE: {}", rule_line(&kept)); + Arc::from(kept) +} + +/// The note for an entry [`parse_dev_allowed_hosts`] dropped, saying what a +/// kept entry looks like, for the startup banner and the log. +#[must_use] +pub fn dropped_entry_note(entry: &str) -> String { + format!( + "dev_allowed_hosts entry '{entry}' was ignored: list a bare host name with no port, \ + scheme or wildcard, such as app.test." + ) +} + +/// The host rule, as the startup banner, the log and the 403 message state it. +fn rule() -> String { + format!( + "ExtendDB serves a browser request, and any request to /management or /metrics, only \ + when its host is an IP address, localhost, a name ending in .localhost, or a name in \ + {SETTING_KEY} (environment variable {SETTING_ENV})." + ) +} + +/// The host rule followed by the names kept from the setting, for the startup +/// banner and the log. +#[must_use] +pub fn rule_line(kept: &[String]) -> String { + let listed = if kept.is_empty() { + "(none)".to_owned() + } else { + kept.join(", ") + }; + format!("{} Listed hosts: {listed}", rule()) +} + +/// Whether a request carries a browser marker (`Origin` or `Sec-Fetch-Site`). +/// Header names in [`HeaderMap`] are stored lowercased. +fn is_browser_request(headers: &HeaderMap) -> bool { + headers.contains_key("origin") || headers.contains_key("sec-fetch-site") +} + +/// Whether a path is `/management`, `/metrics`, or a path below either. +fn is_admin_path(path: &str) -> bool { + ADMIN_PREFIXES.iter().any(|prefix| { + path.strip_prefix(prefix) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('/')) + }) +} + +/// Classification of a host token. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum HostKind { + /// An IPv4 or IPv6 literal. + Ip, + /// A syntactically valid DNS name. + Dns, + /// Neither; refused before any comparison. + Invalid, +} + +fn classify(host: &str) -> HostKind { + if host.parse::().is_ok() { + HostKind::Ip + } else if is_valid_dns_name(host) { + HostKind::Dns + } else { + HostKind::Invalid + } +} + +/// A DNS name: 1 to 253 characters, dot-separated labels of 1 to 63 characters +/// drawn from letters, digits, hyphen and underscore. An empty label (a leading +/// or trailing dot, or two dots in a row) is rejected. +fn is_valid_dns_name(host: &str) -> bool { + if host.is_empty() || host.len() > 253 { + return false; + } + host.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + }) +} + +/// Whether a DNS name is `localhost` or ends in `.localhost` with at least one +/// label before the suffix. +fn is_loopback_name(host: &str) -> bool { + const SUFFIX: &str = ".localhost"; + host.eq_ignore_ascii_case("localhost") + || (host.len() > SUFFIX.len() + && host[host.len() - SUFFIX.len()..].eq_ignore_ascii_case(SUFFIX)) +} + +/// Extract the host token from an authority or `Host`-header value: drop the +/// port, unwrap IPv6 brackets, and ignore a single trailing dot. The port is +/// the text after the colon that follows the host, and it must be one or more +/// ASCII digits. Returns `None` when the value has no host part or is +/// structurally malformed: an opening bracket with no closing one, brackets +/// around anything but an IPv6 address, text after the closing bracket other +/// than a port, or a colon followed by anything but digits, such as userinfo +/// (`127.0.0.1:1@evil.com`), a port name, an empty port or an unbracketed +/// IPv6 address. +fn host_label(raw: &str) -> Option<&str> { + let raw = raw.trim(); + if raw.is_empty() { + return None; + } + let host = if let Some(rest) = raw.strip_prefix('[') { + // Bracketed IPv6: [addr] or [addr]:port. + let end = rest.find(']')?; + let after = &rest[end + 1..]; + if !(after.is_empty() || after.strip_prefix(':').is_some_and(is_port)) { + return None; + } + let inner = &rest[..end]; + if inner.parse::().is_err() { + return None; + } + inner + } else { + match raw.split_once(':') { + Some((_, port)) if !is_port(port) => return None, + Some((h, _)) => h, + None => raw, + } + }; + let host = host.strip_suffix('.').unwrap_or(host); + if host.is_empty() { + return None; + } + Some(host) +} + +/// Whether `port` is one or more ASCII digits. +fn is_port(port: &str) -> bool { + !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) +} + +/// Why a request was refused. Carries the offending host where one was +/// determined, for the message. +enum RejectReason { + /// A valid host that is neither loopback nor listed. + UnlistedHost(String), + /// A host token that is not an IP literal or a valid DNS name. + InvalidHost(String), + /// No readable `Host` header and no request-target authority. + MissingHost, + /// A `Host` header and an absolute-form request target that name different + /// hosts. + HostMismatch, +} + +impl RejectReason { + fn message(&self) -> String { + let rule = rule(); + match self { + Self::UnlistedHost(h) => { + format!("Developer mode refused a request for host '{h}'. {rule}") + } + Self::InvalidHost(h) => { + format!("Developer mode refused a request: '{h}' is not a valid host name. {rule}") + } + Self::MissingHost => { + format!("Developer mode refused a request with no usable Host header. {rule}") + } + Self::HostMismatch => format!( + "Developer mode refused a request whose Host header and request target name \ + different hosts. {rule}" + ), + } + } +} + +/// The guard decision for one request. +enum Decision { + /// Serve the request unchanged. + Allow, + /// Refuse before authentication. + Reject(RejectReason), +} + +/// Decide whether a request is served. A request with no browser marker is +/// allowed unless it is for an admin route. Every other request is allowed +/// only when its single, agreeing host is an IP literal, a loopback name, or a +/// listed name. +fn evaluate(headers: &HeaderMap, uri: &Uri, allowed: &[String]) -> Decision { + if !is_browser_request(headers) && !is_admin_path(uri.path()) { + return Decision::Allow; + } + + // A request with more than one Host header does not get here: + // `repeated_headers::refuse_repeated_headers`, layered outside this guard + // in `start_server`, refuses it on every route. + let host_header = match headers.get("host") { + Some(v) => match v.to_str() { + Ok(s) => Some(s), + Err(_) => return Decision::Reject(RejectReason::MissingHost), + }, + None => None, + }; + let authority = uri.authority().map(axum::http::uri::Authority::as_str); + + // The host is the Host header, or the request-target authority when there + // is no Host. When both are present they must name the same host (ports + // ignored), or the request is refused. + let raw = match (host_header, authority) { + (Some(h), Some(a)) => match (host_label(h), host_label(a)) { + (Some(x), Some(y)) if x.eq_ignore_ascii_case(y) => h, + _ => return Decision::Reject(RejectReason::HostMismatch), + }, + (Some(h), None) => h, + (None, Some(a)) => a, + (None, None) => return Decision::Reject(RejectReason::MissingHost), + }; + + let Some(host) = host_label(raw) else { + return Decision::Reject(RejectReason::InvalidHost(raw.trim().to_owned())); + }; + + match classify(host) { + HostKind::Ip => Decision::Allow, + HostKind::Invalid => Decision::Reject(RejectReason::InvalidHost(host.to_owned())), + HostKind::Dns => { + if is_loopback_name(host) || allowed.iter().any(|a| a.eq_ignore_ascii_case(host)) { + Decision::Allow + } else { + Decision::Reject(RejectReason::UnlistedHost(host.to_owned())) + } + } + } +} + +/// axum middleware: refuse a dev-mode request whose host is foreign, before +/// the request reaches authentication. +async fn enforce(State(cfg): State>, req: Request, next: Next) -> Response { + match evaluate(req.headers(), req.uri(), &cfg.allowed) { + Decision::Allow => next.run(req).await, + Decision::Reject(reason) => reject_response(req.uri().path(), &reason), + } +} + +/// Build the 403 for a refused request, in the shape its surface uses: the +/// console error page for a `/console` path, the `DynamoDB` JSON error for +/// everything else. +fn reject_response(path: &str, reason: &RejectReason) -> Response { + let message = reason.message(); + if path.starts_with("/console") { + ( + StatusCode::FORBIDDEN, + Html(crate::console::host_refused_page(&message)), + ) + .into_response() + } else { + let request_id = uuid::Uuid::new_v4().to_string(); + crate::response::error_response_with_status( + &DynamoDbError::AccessDeniedException(message), + &request_id, + StatusCode::FORBIDDEN, + ) + } +} + +/// Parse the comma-separated [`SETTING_KEY`] value into the host names kept and +/// the entries dropped. An entry must be a bare host name (an IP literal or a +/// valid DNS name, a single trailing dot ignored) with no port, scheme or +/// wildcard; any other entry is dropped, and the startup banner names it. Kept +/// names are lowercased for a case-insensitive comparison against a request +/// host. +#[must_use] +pub fn parse_dev_allowed_hosts(raw: &str) -> (Vec, Vec) { + let mut kept = Vec::new(); + let mut dropped = Vec::new(); + for entry in raw.split(',') { + let trimmed = entry.trim(); + if trimmed.is_empty() { + continue; + } + let candidate = trimmed.strip_suffix('.').unwrap_or(trimmed); + match classify(candidate) { + HostKind::Dns | HostKind::Ip => kept.push(candidate.to_ascii_lowercase()), + HostKind::Invalid => dropped.push(trimmed.to_owned()), + } + } + (kept, dropped) +} + +#[cfg(test)] +mod tests; diff --git a/crates/server/src/dev_host_guard/tests.rs b/crates/server/src/dev_host_guard/tests.rs new file mode 100644 index 000000000..6725b490e --- /dev/null +++ b/crates/server/src/dev_host_guard/tests.rs @@ -0,0 +1,575 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Unit and router-level tests for the developer-mode host guard. + +use super::*; +use axum::body::Body; +use axum::routing::{get, post}; +use tower::ServiceExt as _; + +fn headers(pairs: &[(&str, &str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append( + axum::http::HeaderName::from_bytes(k.as_bytes()).unwrap(), + v.parse().unwrap(), + ); + } + h +} + +fn uri(s: &str) -> Uri { + s.parse().unwrap() +} + +fn allow_path(path: &str, headers: &[(&str, &str)], allowed: &[&str]) -> bool { + let names: Vec = allowed.iter().map(|s| (*s).to_owned()).collect(); + matches!( + evaluate(&self::headers(headers), &uri(path), &names), + Decision::Allow + ) +} + +fn allow(headers: &[(&str, &str)], allowed: &[&str]) -> bool { + allow_path("/", headers, allowed) +} + +/// The headers Node's built-in `fetch` (undici) sends with no caller-set +/// headers, as captured from Node 22. +const UNDICI_HEADERS: [(&str, &str); 4] = [ + ("sec-fetch-mode", "cors"), + ("accept", "*/*"), + ("accept-language", "*"), + ("user-agent", "node"), +]; + +/// Admin HTTP Basic credentials. The guard runs before authentication, so the +/// value only has to look like what a page that knows the password sends. +const ADMIN_AUTH: &str = "Basic YWRtaW46YWRtaW4tcGFzc3dvcmQ="; + +// --- browser-marker detection --- + +#[test] +fn non_browser_request_has_no_marker() { + assert!(!is_browser_request(&headers(&[("host", "rebind.example")]))); + assert!(!is_browser_request(&headers(&[( + "x-amz-target", + "DynamoDB_20120810.ListTables" + )]))); +} + +#[test] +fn origin_or_sec_fetch_site_is_a_marker() { + assert!(is_browser_request(&headers(&[("origin", "http://x")]))); + assert!(is_browser_request(&headers(&[("origin", "null")]))); + assert!(is_browser_request(&headers(&[( + "sec-fetch-site", + "same-origin" + )]))); +} + +#[test] +fn undici_fetch_headers_are_not_a_browser_request() { + assert!(!is_browser_request(&headers(&UNDICI_HEADERS))); +} + +#[test] +fn other_sec_fetch_headers_alone_are_not_a_marker() { + assert!(!is_browser_request(&headers(&[("sec-fetch-mode", "cors")]))); + assert!(!is_browser_request(&headers(&[( + "sec-fetch-dest", + "empty" + )]))); + assert!(!is_browser_request(&headers(&[("sec-fetch-user", "?1")]))); +} + +// --- admin paths --- + +#[test] +fn admin_path_covers_management_and_metrics_and_below() { + for path in [ + "/management", + "/management/", + "/management/accounts", + "/management/accounts/123456789012/users", + "/metrics", + "/metrics/", + ] { + assert!(is_admin_path(path), "{path} is an admin path"); + } + for path in [ + "/", + "/health", + "/managementx", + "/metricsx", + "/console/metrics", + "/console/metrics-data", + "/console/login", + ] { + assert!(!is_admin_path(path), "{path} is not an admin path"); + } +} + +// --- host parsing --- + +#[test] +fn host_label_strips_port_brackets_and_one_trailing_dot() { + assert_eq!(host_label("rebind.example:18602"), Some("rebind.example")); + assert_eq!(host_label("127.0.0.1:18602"), Some("127.0.0.1")); + assert_eq!(host_label("[::1]:18602"), Some("::1")); + assert_eq!(host_label("[::1]"), Some("::1")); + assert_eq!(host_label("localhost."), Some("localhost")); + assert_eq!(host_label("::1:7"), None); // unbracketed IPv6 is malformed + assert_eq!(host_label("[::1]junk"), None); + assert_eq!(host_label("[localhost]"), None); + assert_eq!(host_label("[127.0.0.1]"), None); + assert_eq!(host_label(""), None); + assert_eq!(host_label("."), None); + // A port is one or more digits: userinfo, a port name or an empty port + // after a loopback name does not read as that name. + for raw in [ + "127.0.0.1:1@evil.com", + "localhost:x@evil.com", + "127.0.0.1:abc", + "[::1]:abc", + "localhost:", + ] { + assert_eq!(host_label(raw), None, "{raw}"); + } +} + +#[test] +fn classify_ip_dns_and_invalid() { + assert_eq!(classify("127.0.0.1"), HostKind::Ip); + assert_eq!(classify("::1"), HostKind::Ip); + assert_eq!(classify("localhost"), HostKind::Dns); + assert_eq!(classify("app.localhost"), HostKind::Dns); + assert_eq!(classify("under_score.test"), HostKind::Dns); + assert_eq!(classify("bad host"), HostKind::Invalid); + assert_eq!(classify("a..b"), HostKind::Invalid); + assert_eq!(classify(&"a".repeat(64)), HostKind::Invalid); // label too long +} + +#[test] +fn loopback_name_covers_localhost_and_dot_localhost() { + assert!(is_loopback_name("localhost")); + assert!(is_loopback_name("LocalHost")); + assert!(is_loopback_name("app.localhost")); + assert!(is_loopback_name("a.b.localhost")); + assert!(!is_loopback_name(".localhost")); + assert!(!is_loopback_name("notlocalhost")); + assert!(!is_loopback_name("localhost.evil.com")); +} + +// --- the decision --- + +#[test] +fn rebinding_browser_host_is_refused() { + assert!(!allow( + &[ + ("host", "rebind.example:1"), + ("origin", "http://rebind.example:1") + ], + &[] + )); + // each marker on its own + assert!(!allow( + &[("host", "rebind.example:1"), ("origin", "null")], + &[] + )); + assert!(!allow( + &[ + ("host", "rebind.example:1"), + ("sec-fetch-site", "same-origin") + ], + &[] + )); +} + +#[test] +fn undici_fetch_with_a_compose_host_is_served() { + let mut with_host = UNDICI_HEADERS.to_vec(); + with_host.push(("host", "extenddb:18000")); + assert!(allow(&with_host, &[])); +} + +#[test] +fn loopback_and_ip_browser_hosts_are_served() { + for host in ["localhost:1", "127.0.0.1:1", "[::1]:1", "app.localhost:1"] { + assert!( + allow(&[("host", host), ("origin", "http://x")], &[]), + "{host} should be served" + ); + } +} + +#[test] +fn listed_browser_host_is_served_case_insensitively() { + assert!(allow( + &[("host", "Dev.Test:1"), ("origin", "http://x")], + &["dev.test"] + )); + assert!(!allow( + &[("host", "other.test:1"), ("origin", "http://x")], + &["dev.test"] + )); +} + +#[test] +fn non_browser_request_is_served_whatever_the_host() { + // No marker: a Compose service name, an SDK Host, anything. + assert!(allow(&[("host", "rebind.example:1")], &[])); + assert!(allow(&[("host", "extenddb:1")], &[])); + assert!(allow(&[("host", "host.docker.internal:1")], &[])); +} + +#[test] +fn admin_path_is_checked_on_the_host_alone() { + let rebind = [("host", "rebind.example:1"), ("authorization", ADMIN_AUTH)]; + assert!(!allow_path("/management/accounts", &rebind, &[])); + assert!(!allow_path("/metrics", &rebind, &[])); + for host in ["localhost:1", "127.0.0.1:1", "dev.test:1"] { + let marked_none = [("host", host), ("authorization", ADMIN_AUTH)]; + assert!( + allow_path("/management/accounts", &marked_none, &["dev.test"]), + "{host} should be served" + ); + } + // The other routes keep the marker rule. + assert!(allow_path("/health", &rebind, &[])); + assert!(allow_path("/console/login", &rebind, &[])); +} + +#[test] +fn missing_and_mismatched_host_are_refused() { + // Missing Host on a browser request (no authority in a "/" uri). + assert!(matches!( + evaluate(&headers(&[("origin", "http://x")]), &uri("/"), &[]), + Decision::Reject(RejectReason::MissingHost) + )); + // Missing Host on an admin route, no marker. + assert!(matches!( + evaluate(&headers(&[]), &uri("/management/accounts"), &[]), + Decision::Reject(RejectReason::MissingHost) + )); + // Absolute-form target and Host header disagree. + assert!(matches!( + evaluate( + &headers(&[("host", "localhost"), ("origin", "http://x")]), + &uri("http://rebind.example/"), + &[] + ), + Decision::Reject(RejectReason::HostMismatch) + )); + // Absolute-form target and Host header agree (ports ignored): served. + assert!(matches!( + evaluate( + &headers(&[("host", "localhost:1"), ("origin", "http://x")]), + &uri("http://localhost/"), + &[] + ), + Decision::Allow + )); +} + +#[test] +fn invalid_host_is_refused() { + assert!(matches!( + evaluate( + &headers(&[("host", "bad_host .x"), ("origin", "http://x")]), + &uri("/"), + &[] + ), + Decision::Reject(RejectReason::InvalidHost(_)) + )); + // An absolute-form target with userinfo and no Host header. + assert!(matches!( + evaluate( + &headers(&[]), + &uri("http://127.0.0.1:1@evil.com/management/accounts"), + &[] + ), + Decision::Reject(RejectReason::InvalidHost(h)) if h == "127.0.0.1:1@evil.com" + )); +} + +// --- setting parser and rule text --- + +#[test] +fn parse_keeps_host_names_and_drops_junk() { + let (kept, dropped) = + parse_dev_allowed_hosts("dev.test, My.Host , , bad host, with:port, 10.0.0.5, trailing."); + assert_eq!(kept, vec!["dev.test", "my.host", "10.0.0.5", "trailing"]); + assert_eq!(dropped, vec!["bad host", "with:port"]); +} + +#[test] +fn a_port_suffixed_entry_is_dropped_with_what_to_list_instead() { + let (kept, dropped) = parse_dev_allowed_hosts("app.test:3000"); + assert!(kept.is_empty(), "{kept:?}"); + assert_eq!(dropped, vec!["app.test:3000"]); + assert_eq!( + dropped_entry_note(&dropped[0]), + "dev_allowed_hosts entry 'app.test:3000' was ignored: list a bare host name with no \ + port, scheme or wildcard, such as app.test." + ); +} + +#[test] +fn rule_line_states_the_rule_and_the_listed_names() { + let none = rule_line(&[]); + assert!(none.starts_with(&rule()), "{none}"); + assert!(none.ends_with("Listed hosts: (none)"), "{none}"); + assert!( + none.contains("/management") && none.contains("/metrics"), + "{none}" + ); + let two = rule_line(&["dev.test".to_owned(), "api.test".to_owned()]); + assert!(two.ends_with("Listed hosts: dev.test, api.test"), "{two}"); +} + +#[test] +fn allowed_hosts_is_empty_outside_dev_mode() { + assert!(allowed_hosts(false, Some("dev.test")).is_empty()); + assert_eq!( + &*allowed_hosts(true, Some("Dev.Test, bad host")), + ["dev.test"] + ); + assert!(allowed_hosts(true, None).is_empty()); +} + +// --- router wiring and response shape --- + +fn routes() -> Router { + Router::new() + .route("/", post(|| async { "api-ok" })) + .route("/health", get(|| async { "health-ok" })) + .route("/metrics", get(|| async { "metrics-ok" })) + .route("/management/accounts", get(|| async { "mgmt-ok" })) + .route( + "/console/login", + get(|| async { "console-ok" }).post(|| async { "console-ok" }), + ) +} + +fn guarded_router(allowed: Vec) -> Router { + install(routes(), true, allowed.into()) +} + +async fn body_string(resp: Response) -> (StatusCode, String, String) { + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_owned(); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + ( + status, + content_type, + String::from_utf8_lossy(&bytes).into_owned(), + ) +} + +async fn send(router: Router, method: &str, path: &str, hdrs: &[(&str, &str)]) -> Response { + let mut req = Request::builder().method(method).uri(path); + for (k, v) in hdrs { + req = req.header(*k, *v); + } + let body = if method == "POST" { + Body::from("{}") + } else { + Body::empty() + }; + router.oneshot(req.body(body).unwrap()).await.unwrap() +} + +#[tokio::test] +async fn api_rebinding_browser_request_gets_dynamodb_json_403() { + let resp = send( + guarded_router(vec![]), + "POST", + "/", + &[ + ("host", "rebind.example:1"), + ("origin", "http://rebind.example:1"), + ("x-amz-target", "DynamoDB_20120810.CreateTable"), + ], + ) + .await; + let (status, content_type, body) = body_string(resp).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(content_type, "application/x-amz-json-1.0"); + assert!(body.contains("AccessDeniedException"), "body: {body}"); + assert!(body.contains("rebind.example"), "names the host: {body}"); + assert!(body.contains(SETTING_KEY), "names the setting: {body}"); + assert!(!body.contains("api-ok"), "handler must not have run"); +} + +#[tokio::test] +async fn api_sdk_request_with_compose_host_is_served() { + // No browser marker, a Compose-style Host: served. + let resp = send( + guarded_router(vec![]), + "POST", + "/", + &[ + ("host", "extenddb:18000"), + ("x-amz-target", "DynamoDB_20120810.ListTables"), + ], + ) + .await; + let (status, _, body) = body_string(resp).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, "api-ok"); +} + +#[tokio::test] +async fn api_undici_fetch_request_with_compose_host_is_served() { + let mut hdrs = UNDICI_HEADERS.to_vec(); + hdrs.push(("host", "extenddb")); + hdrs.push(("x-amz-target", "DynamoDB_20120810.ListTables")); + let resp = send(guarded_router(vec![]), "POST", "/", &hdrs).await; + let (status, _, body) = body_string(resp).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, "api-ok"); +} + +#[tokio::test] +async fn api_browser_request_with_loopback_host_is_served() { + for host in ["localhost:1", "127.0.0.1:1", "[::1]:1", "x.localhost:1"] { + let resp = send( + guarded_router(vec![]), + "POST", + "/", + &[("host", host), ("origin", "http://x")], + ) + .await; + let (status, _, body) = body_string(resp).await; + assert_eq!(status, StatusCode::OK, "{host}"); + assert_eq!(body, "api-ok", "{host}"); + } +} + +#[tokio::test] +async fn api_browser_request_with_listed_host_is_served() { + let resp = send( + guarded_router(vec!["dev.test".to_owned()]), + "POST", + "/", + &[("host", "dev.test:1"), ("origin", "http://x")], + ) + .await; + let (status, _, body) = body_string(resp).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, "api-ok"); +} + +#[tokio::test] +async fn console_rebinding_browser_request_gets_html_403() { + for method in ["GET", "POST"] { + let resp = send( + guarded_router(vec![]), + method, + "/console/login", + &[ + ("host", "rebind.example:1"), + ("origin", "http://rebind.example:1"), + ], + ) + .await; + let (status, content_type, body) = body_string(resp).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{method}"); + assert!( + content_type.starts_with("text/html"), + "{method}: {content_type}" + ); + assert!(body.contains("rebind.example"), "{method}: {body}"); + assert!( + !body.contains("console-ok"), + "{method}: handler must not run" + ); + } +} + +#[tokio::test] +async fn admin_get_with_no_marker_under_a_rebinding_host_gets_403() { + for path in ["/management/accounts", "/metrics"] { + let resp = send( + guarded_router(vec![]), + "GET", + path, + &[("host", "rebind.example:1"), ("authorization", ADMIN_AUTH)], + ) + .await; + let (status, content_type, body) = body_string(resp).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{path}"); + assert_eq!(content_type, "application/x-amz-json-1.0", "{path}"); + assert!(body.contains("AccessDeniedException"), "{path}: {body}"); + assert!(body.contains("rebind.example"), "{path}: {body}"); + } +} + +#[tokio::test] +async fn admin_get_under_loopback_or_listed_host_is_served() { + for host in ["localhost:1", "127.0.0.1:1", "dev.test:1"] { + let resp = send( + guarded_router(vec!["dev.test".to_owned()]), + "GET", + "/management/accounts", + &[("host", host), ("authorization", ADMIN_AUTH)], + ) + .await; + let (status, _, body) = body_string(resp).await; + assert_eq!(status, StatusCode::OK, "{host}"); + assert_eq!(body, "mgmt-ok", "{host}"); + } +} + +#[tokio::test] +async fn health_with_no_marker_under_a_rebinding_host_is_served() { + let resp = send( + guarded_router(vec![]), + "GET", + "/health", + &[("host", "rebind.example:1")], + ) + .await; + let (status, _, body) = body_string(resp).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, "health-ok"); +} + +#[tokio::test] +async fn production_mode_installs_no_guard() { + // `install` with dev_mode false returns the router unchanged, so the + // requests the guard refuses in developer mode reach their handlers. + let router = install(routes(), false, Arc::from(Vec::new())); + let resp = send( + router.clone(), + "POST", + "/", + &[ + ("host", "rebind.example:1"), + ("origin", "http://rebind.example:1"), + ], + ) + .await; + let (status, _, body) = body_string(resp).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, "api-ok"); + let resp = send( + router, + "GET", + "/management/accounts", + &[("host", "rebind.example:1"), ("authorization", ADMIN_AUTH)], + ) + .await; + let (status, _, body) = body_string(resp).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, "mgmt-ok"); +} diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index de3212182..36f280914 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -15,6 +15,7 @@ pub(crate) mod authz_resource; pub mod backup_store; pub mod console; pub mod dev_credentials; +pub(crate) mod dev_host_guard; mod handler; mod import_export_paths; mod import_export_roots; @@ -37,6 +38,10 @@ mod table_name_gate; mod throttle_helpers; mod workers; +pub use dev_host_guard::{ + dropped_entry_note as dev_host_dropped_entry_note, parse_dev_allowed_hosts, + rule_line as dev_host_rule_line, +}; pub use serve::{ BuildInfo, CatalogRefusal, JOB_DRAIN_TIMEOUT, LogTarget, RegistrationLost, ServeParams, WORKER_STOP_TIMEOUT, catalog_refusal, log_to_syslog_raw, serve, @@ -87,6 +92,10 @@ pub struct AppState { /// is still verified). Only ever true in a `dev-mode` build bound to /// loopback; the bin's serve path enforces those preconditions. pub dev_mode: bool, + /// The names kept from `server.dev_allowed_hosts`, lowercased, for the + /// dev-mode host guard (`dev_host_guard`). Empty outside dev mode, where + /// the guard is not installed. + pub dev_allowed_hosts: std::sync::Arc<[String]>, /// Allowed directories for import file operations. Empty means imports /// are disabled (secure default). pub import_paths: Arc<[Arc]>, @@ -157,6 +166,8 @@ pub async fn start_server( let tls_enabled = state.tls_enabled; let request_timeout = state.request_timeout; let catalog_store = state.catalog_store.clone(); + let dev_mode = state.dev_mode; + let dev_allowed_hosts = state.dev_allowed_hosts.clone(); let auth_cache_for_mgmt = state.auth_cache.clone(); let auth_cache_for_console = state.auth_cache.clone(); let metrics_for_console = state.metrics.clone(); @@ -254,6 +265,10 @@ pub async fn start_server( registration::refuse_while_unregistered, )); + // Dev-mode host guard. Added before the security headers so its 403s carry + // them; it still runs before every handler and before authentication. + let app = dev_host_guard::install(app, dev_mode, dev_allowed_hosts); + // Refuse a repeated host or authorization header on every route, then // apply security headers to all routes (the refusal carries them too). // A body that stops delivering data for `request_timeout` errors out, so a diff --git a/crates/server/src/response.rs b/crates/server/src/response.rs index 1b26cd378..cf71072c9 100755 --- a/crates/server/src/response.rs +++ b/crates/server/src/response.rs @@ -37,6 +37,24 @@ pub(crate) fn success_response(body: &Value, request_id: &str) -> Response { /// key `error_document` picks. REQ-ERR-003: Omit the message field when empty /// (real `DynamoDB` behavior, verified 2026-05-04). pub(crate) fn error_response(error: &DynamoDbError, request_id: &str) -> Response { + let status = + StatusCode::from_u16(error.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + error_response_with_status(error, request_id, status) +} + +/// Build the same wire-format error body as [`error_response`] but with an +/// explicit HTTP status instead of the error's own catalog status. +/// +/// The dev-mode host guard refuses a browser request with HTTP 403 while still +/// returning the JSON error body the `DynamoDB` API uses, so it sets the status +/// itself. `AccessDeniedException` carries a 400 in the real `DynamoDB` catalog; +/// here the guard pairs it with 403, which is why the status cannot come from +/// the error. +pub(crate) fn error_response_with_status( + error: &DynamoDbError, + request_id: &str, + status: StatusCode, +) -> Response { // The body shape (`__type`, optional message, `CancellationReasons`, `Item`) // is built by the shared `error_document` helper so the wire body and the // in-process body come from the same code; this transport adds the HTTP status and headers. @@ -44,8 +62,6 @@ pub(crate) fn error_response(error: &DynamoDbError, request_id: &str) -> Respons let body_bytes = serde_json::to_vec(&body).unwrap_or_else(|_| SERIALIZATION_FAILURE_BODY.to_vec()); let crc = crc32fast::hash(&body_bytes); - let status = - StatusCode::from_u16(error.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); ( status, diff --git a/crates/server/src/serve.rs b/crates/server/src/serve.rs index 1b64336f6..72f9f8bf3 100644 --- a/crates/server/src/serve.rs +++ b/crates/server/src/serve.rs @@ -653,6 +653,10 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { // app crate's `config::is_tls_enabled` applies the same rule for clients. let tls_enabled = app_config.server.tls.enabled && !dev_mode; + // Dev-mode host guard names, parsed and logged by `dev_host_guard`. + let raw_hosts = app_config.server.dev_allowed_hosts.as_deref(); + let dev_allowed_hosts = crate::dev_host_guard::allowed_hosts(dev_mode, raw_hosts); + // P53: Resolve import and export path lists. Supports both the new // [import]/[export] sections and the deprecated import_export_root. // @@ -804,6 +808,7 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { tls_enabled, request_timeout: Duration::from_secs(app_config.server.request_timeout_secs), dev_mode, + dev_allowed_hosts, import_paths, export_paths, throttle: throttle.clone(), diff --git a/docs/dev-image.md b/docs/dev-image.md index a051ee21f..116777155 100644 --- a/docs/dev-image.md +++ b/docs/dev-image.md @@ -105,6 +105,139 @@ the current `EXTENDDB_DEV_*` pair, recreate the volume. This narrows who can sign requests; it does not add TLS or permissions. Keep the loopback publish. +## Browser requests + +The server treats a request as coming from a browser when it carries an +`Origin` header or a `Sec-Fetch-Site` header. A browser sends `Origin` on every +request whose method is not `GET` or `HEAD` and on every cross-origin CORS +request. It sends `Sec-Fetch-Site` and the other `Sec-Fetch-*` headers only to +`https` URLs and to loopback URLs (a loopback IP address, `localhost` or a +`.localhost` name). A page script cannot remove these headers. The AWS SDKs and +the CLI send neither. Node's built-in `fetch` sends `Sec-Fetch-Mode` on its own, +which the server does not count. + +In dev mode the server serves a browser request only when its host is an IP +address, `localhost`, a name ending in `.localhost`, or a name you list in +`server.dev_allowed_hosts` (environment variable +`EXTENDDB__SERVER__DEV_ALLOWED_HOSTS`). The host is read from the `Host` +header. Any other browser request gets HTTP 403 before authentication. A call +to the DynamoDB API and a console login are `POST`s, which carry `Origin`, so a +web page whose name resolves to the loopback address cannot use the seeded +credential or log in to the console. The allowance for `.localhost` names +assumes a browser that resolves them to the loopback address itself. Chrome, +Firefox and Edge do. Safari on macOS hands them to the system resolver, which +can pass a `.localhost` name to a DNS server on the network. That server can +answer with its own address and serve a page under the name. When it then +answers with the loopback address, the check serves that page's requests. + +The management routes (`/management` and below) and `/metrics` answer `GET` +with the admin password, and a page's same-origin `GET` carries neither header. +The server therefore checks every request to these routes against the host +rule, whether or not it carries a browser header. A client on the same host +that uses `127.0.0.1` or `localhost` needs no change. A client in another +container that calls these routes by the Compose service name, such as +`extenddb manage --endpoint http://extenddb-dev:18080` or a metrics poller, +gets HTTP 403. Such a client needs no listed name if it uses an IP address, +which the rule always serves. Point a metrics poller at the dev container's IP +address, and run `extenddb manage` inside the dev container, where `127.0.0.1` +reaches the server. The image has no config file, so give the endpoint. Set +`EXTENDDB_PASSWORD` in your shell to the admin password first: the one the +container's log shows at first start, or the `EXTENDDB_ADMIN_PASSWORD` value +the container started with. `-e EXTENDDB_PASSWORD` with no value copies the +variable from your shell into the container, and the command line does not +show the password: + +```bash +docker exec -e EXTENDDB_PASSWORD extenddb manage \ + --endpoint http://127.0.0.1:18080 --user admin list-accounts +``` + +The setting is a single string of comma-separated bare host names, with no +port, scheme or wildcard, such as `app.test,api.test`. A TOML array stops the +server at startup. The startup banner states the rule and the names in force, +and names each entry it dropped. + +List a name when a browser reaches the server through it, for example a +development proxy that forwards the browser's `Host`: + +```bash +# A development proxy at http://app.test:3000 forwards the browser's requests, +# with their Host header unchanged, to this dev server: +docker run -d -p 127.0.0.1:18080:18080 \ + -e EXTENDDB__SERVER__DEV_ALLOWED_HOSTS=app.test \ + extenddb/extenddb-dev +``` + +A name your hosts file maps to the loopback address, such as +`localhost.localdomain`, `localhost4` or your machine's own name, has to be +listed too when a browser uses it, and so does the host name of the URL a cloud +development environment forwards to the server, if it passes the browser's +`Host` through unchanged. + +The server sends no CORS headers, so a page on another origin cannot call its +DynamoDB API, whether or not the page's name is listed. For a page at +`http://app.test:3000` that calls `http://localhost:18080`, the browser's +preflight `OPTIONS` request gets 405 and the browser does not send the call. A +form on another origin can still post to the console login page. A form post +needs no preflight, and the check reads the host from `Host`, whatever the +`Origin` header says. + +A listed name is trusted for browser requests as `localhost` is, so a +page served under it can call the server with the seeded credential. List a +name that resolves to the loopback address only when you control that +resolution on the machine where the browser runs, as with an entry in its hosts +file or the name your own development proxy forwards. + +A browser on the host reaches the dev container through its published port as +`localhost` or `127.0.0.1` and needs no listed name. Do not list a single-label +Compose service name such as `extenddb-dev` for that browser. The host resolves +such a name through its DNS search domains and, on Windows, through Link-Local +Multicast Name Resolution (LLMNR) and NetBIOS, which another machine on the +network can answer. That machine can answer with its own address and serve a +page under the name, then answer with the loopback address, so the page's +requests reach the dev server under a listed name. + +A browser that has to reach the server by a Compose service name or +`host.docker.internal`, for example one in a test container, sends its requests +under that name, so the name has to be listed in the dev service's environment: + +```yaml +services: + extenddb-dev: + environment: + EXTENDDB__SERVER__DEV_ALLOWED_HOSTS: extenddb-dev +``` + +The listed name is then trusted for browser requests from the host too. + +A reverse proxy in front of the dev server decides which `Host` the server +sees: + +- A proxy that rewrites `Host` to `localhost` or to a listed name hides the + browser's host, so the check does not protect a server behind it. That proxy + has to check `Host` itself. +- A proxy that forwards the browser's `Host` unchanged keeps the check, and the + name the browser uses has to be listed. + +The check does not cover these cases: + +- **A same-origin `GET` or `HEAD` from a page served over plain HTTP.** It + carries neither header, so the server serves it as it serves a non-browser + client. Outside the management routes and `/metrics`, which are checked on the + host alone, it reaches `/health` and the console's login and documentation + pages. Every other console page needs a session, which only a login `POST` + creates. +- **Firefox before 70 and EdgeHTML.** They send no `Origin` on a `POST` and no + `Sec-Fetch-*` headers, so in one of them a page whose name resolves to the + loopback address can still reach the DynamoDB API with the seeded credential, + and, if it knows a console password, log in to the console and use it. The + management routes and `/metrics` are still refused, since they are checked on + the host alone. +- **Clients that are not browsers.** The SDKs, the CLI and any other + non-browser client send no browser header, so outside the management routes + and `/metrics` they are served whatever their `Host`, as before. A web page + cannot drive those clients. + ## Storage modes One image serves both modes; the mode is chosen at run time. @@ -147,8 +280,8 @@ condition: service_healthy` work with no extra wiring. ## Image properties - Runtime base is distroless (`gcr.io/distroless/cc-debian13:nonroot`): no - shell, no package manager, runs as uid 65532. `docker exec` into it is not - possible by design. + shell, no package manager, runs as uid 65532. `docker exec` can run the + `extenddb` binary in it but cannot open a shell, by design. - The binary is built with the `release-slim` profile (stripped, LTO). - Licence notices for this image's exact dependency set ship at `/usr/share/doc/extenddb/SOFTWARE-LICENSE-NOTICES.html` diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index 214040065..b5ebb81bc 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -118,6 +118,7 @@ These settings require a server restart to take effect. | `port` | `18443` | HTTP port | | `region` | `us-east-1` | AWS region for ARN generation. Requests must carry a credential scope for this region; any other region is rejected with `InvalidSignatureException`, as the service rejects a scope for a region other than the endpoint's. Baked into every backup ARN the server issues, so it must stay within `[a-z0-9-]` (under a value outside that class `CreateBackup` is refused with a `ValidationException` naming `server.region`, since no backup ARN can be formed; backups taken before the upgrade under such a region keep an ARN `DescribeBackup`, `DeleteBackup`, and `RestoreTableFromBackup` refuse as "not valid"; the server logs a warning at startup). A backup ARN of the caller's account in another region is resolved in the server's region first, then as written; see the upgrade manual before changing this on a deployment with backups | | `request_timeout_secs` | `30` | Seconds a connection may take to deliver its request headers, and seconds a request body may stall without delivering data, before the server closes it (a stalled body gets HTTP 408). A connection that is accepted, or that completes the TLS handshake, and then sends no byte is closed after the same number of seconds, as is one that sends only part of the 24-byte HTTP/2 preface. The same value bounds how long an idle keep-alive connection waits for its next request, so SDK connection pools see idle connections closed after it (they reopen transparently), and it is the HTTP/2 keep-alive PING interval and timeout, so a stalled HTTP/2 connection is closed within twice the value. Must be at least 1 and at most 86400 (a day); the server refuses a larger value at startup, because the per-connection timers add it to the current instant and a value near `u64::MAX` overflows that addition | +| `dev_allowed_hosts` | (unset) | Developer-mode builds only. A single string of comma-separated bare host names (no port, scheme or wildcard) a browser request may use, beyond an IP address, `localhost` and any `.localhost` name. A dev-mode server refuses a browser request (one carrying an `Origin` or `Sec-Fetch-Site` header) whose host is none of these, and checks every request to `/management` and `/metrics` the same way whether or not it carries either header. This keeps a page whose name resolves to the loopback address from driving the local server. A listed name is trusted for browser requests as `localhost` is. List a name that resolves to the loopback address only when you control that resolution where the browser runs, such as a hosts-file entry, and do not list a single-label Compose service name for a browser on the host. A client in another container needs no listed name for the management routes or `/metrics` if it uses an IP address, such as the dev container's address, or runs `extenddb manage --endpoint http://127.0.0.1:18080` in the dev container with `docker exec`. Entries that are not bare host names are dropped with a startup warning. A production build does not use the value, but an array or a table still stops it at startup. Environment override: `EXTENDDB__SERVER__DEV_ALLOWED_HOSTS` | #### [storage] diff --git a/docs/webassembly.md b/docs/webassembly.md index e7dc53e04..3992c8cb2 100644 --- a/docs/webassembly.md +++ b/docs/webassembly.md @@ -253,7 +253,9 @@ arrive within the request timeout, its body must not stall for longer, and an HTTP/2 client must answer the keep-alive pings), the redirect of plain HTTP on a TLS port, the router's 404 and 405 answers to a path it has no route for or a method other than `POST` on `/`, the refusal of a repeated `host` or -`authorization` header, and the checks of the `X-Amz-Target` header. Nor has +`authorization` header, the developer-mode refusal of a browser request or a +`/management` or `/metrics` request whose host the host check does not allow, +and the checks of the `X-Amz-Target` header. Nor has this build the server's refusal of every request while a Cassandra, MongoDB or PostgreSQL backend registers again with its catalog, or the `AccessDeniedException` "User: is not authorized to perform this operation" it diff --git a/extenddb.sample.toml b/extenddb.sample.toml index eafa3047d..770ff8cf4 100755 --- a/extenddb.sample.toml +++ b/extenddb.sample.toml @@ -29,6 +29,9 @@ # port = 18443 # HTTP port # region = "us-east-1" # AWS region for ARN generation # run_dir = "~/.extenddb/run" # Directory for PID file (~ is expanded to $HOME) +# dev_allowed_hosts = "app.test,api.test" + # Developer-mode builds only: host names the dev-mode host check allows. + # See the dev_allowed_hosts row in docs/manuals/05-admin-guide.md. [storage] # backend = "postgres" # Storage backend: "postgres" (default), "mongodb", or "sqlite". diff --git a/tests/test_dev_mode_authorization.py b/tests/test_dev_mode_authorization.py index 734ae0082..4c432447e 100644 --- a/tests/test_dev_mode_authorization.py +++ b/tests/test_dev_mode_authorization.py @@ -33,6 +33,7 @@ import boto3 import pytest +import requests from botocore.config import Config as BotoConfig from botocore.exceptions import ClientError @@ -43,6 +44,28 @@ reason="requires a dev-mode server (set EXTENDDB_TEST_DEV_MODE=1)", ) +# The host guard runs before authentication, so its 403 does not depend on the +# password being right. The CI dev-mode job does not set one, and the server +# then generates a random admin password. +_ADMIN_AUTH = ( + os.environ.get("EXTENDDB_ADMIN_USER", "admin"), + os.environ.get("EXTENDDB_ADMIN_PASSWORD", "not-the-password"), +) +_REBIND_HOST = "rebind.example" +_LISTED_HOST = "app.test" +_ALLOWED_HOSTS = os.environ.get("EXTENDDB__SERVER__DEV_ALLOWED_HOSTS", "").lower() +_GUARD_MESSAGE = "Developer mode refused a request" +# The answer to an unsigned ListTables that passed the host guard. +_MISSING_TOKEN = { + "__type": "com.amazon.coral.service#MissingAuthenticationTokenException", + "message": "Request is missing Authentication Token", +} +_SECURITY_HEADERS = { + "x-frame-options": "DENY", + "x-content-type-options": "nosniff", + "referrer-policy": "strict-origin-when-cross-origin", +} + def _assert_not_denied(op_name: str, call): """Run `call`, failing loudly if the operation was denied rather than served. @@ -280,3 +303,101 @@ def read(t: str): assert err == { "Code": "ExpiredIteratorException", "Message": "Shard iterator has expired" }, err + + +def _base(endpoint_url: str | None) -> str: + if not endpoint_url: + pytest.fail("MISCONFIGURED: dev-mode tests require EXTENDDB_TEST_ENDPOINT.") + return endpoint_url.rstrip("/") + + +def _list_tables_unsigned( + endpoint_url: str | None, extra_headers: dict[str, str], host: str = _REBIND_HOST +): + """POST an unsigned ListTables under `host`.""" + return requests.post( + f"{_base(endpoint_url)}/", + data=b"{}", + headers={ + "Host": host, + "Content-Type": "application/x-amz-json-1.0", + "X-Amz-Target": "DynamoDB_20120810.ListTables", + **extra_headers, + }, + timeout=10, + ) + + +def _assert_security_headers(resp) -> None: + for name, value in _SECURITY_HEADERS.items(): + assert resp.headers.get(name) == value, f"{name}: {resp.headers.get(name)!r}" + + +class TestDevModeHostGuard: + """A dev-mode server refuses a request from a page whose name resolves to + loopback: a browser request (Origin or Sec-Fetch-Site) under a foreign + host, and any request to the admin routes under a foreign host.""" + + def test_browser_request_under_a_rebinding_host_is_refused(self, endpoint_url): + resp = _list_tables_unsigned(endpoint_url, {"Origin": f"http://{_REBIND_HOST}"}) + assert resp.status_code == 403, resp.text + message = resp.json()["message"] + assert _GUARD_MESSAGE in message + assert _REBIND_HOST in message + _assert_security_headers(resp) + + def test_same_request_without_a_marker_is_not_refused(self, endpoint_url): + resp = _list_tables_unsigned(endpoint_url, {}) + assert resp.status_code == 400, resp.text + assert resp.json() == _MISSING_TOKEN + + def test_admin_get_under_a_rebinding_host_is_refused(self, endpoint_url): + # A same-origin GET from a plain-HTTP page carries no marker. + resp = requests.get( + f"{_base(endpoint_url)}/management/accounts", + headers={"Host": _REBIND_HOST}, + auth=_ADMIN_AUTH, + timeout=10, + ) + assert resp.status_code == 403, resp.text + assert _GUARD_MESSAGE in resp.json()["message"] + _assert_security_headers(resp) + + def test_admin_get_under_the_endpoint_host_is_not_refused(self, endpoint_url): + resp = requests.get(f"{_base(endpoint_url)}/management/accounts", timeout=10) + assert (resp.status_code, resp.text) == (401, "Missing Authorization header") + + @pytest.mark.skipif( + _LISTED_HOST not in _ALLOWED_HOSTS.replace(" ", "").split(","), + reason=f"requires EXTENDDB__SERVER__DEV_ALLOWED_HOSTS to list {_LISTED_HOST}", + ) + def test_a_listed_host_is_not_refused(self, endpoint_url): + """server.dev_allowed_hosts reaches the guard. The server and this test + read EXTENDDB__SERVER__DEV_ALLOWED_HOSTS, which the CI dev-mode job sets + for every step.""" + resp = _list_tables_unsigned( + endpoint_url, {"Origin": f"http://{_LISTED_HOST}"}, host=_LISTED_HOST + ) + assert resp.status_code == 400, resp.text + assert resp.json() == _MISSING_TOKEN + resp = requests.get( + f"{_base(endpoint_url)}/management/accounts", + headers={"Host": _LISTED_HOST}, + timeout=10, + ) + assert (resp.status_code, resp.text) == (401, "Missing Authorization header") + + def test_console_browser_request_under_a_rebinding_host_gets_the_html_403( + self, endpoint_url + ): + resp = requests.post( + f"{_base(endpoint_url)}/console/login", + data={"username": _ADMIN_AUTH[0], "password": _ADMIN_AUTH[1]}, + headers={"Host": _REBIND_HOST, "Origin": f"http://{_REBIND_HOST}"}, + allow_redirects=False, + timeout=10, + ) + assert resp.status_code == 403, resp.text + assert resp.headers.get("content-type", "").startswith("text/html") + assert _GUARD_MESSAGE in resp.text + _assert_security_headers(resp)