From 15966f25d22d77afd949fee8ea91ab41a8d2e6ae Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:33:15 +0000 Subject: [PATCH 01/12] fix(dev-mode): refuse browser and admin requests for a foreign host In developer mode the server serves plain HTTP on loopback and opens the IAM policy decision for an authenticated caller, signing with a seeded example credential. A web page whose name resolves to the loopback address is then same-origin with the server, so a browser sends the page's requests to it with no preflight and the page can sign them with the published credential. The server now treats a request as 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. The other Sec-Fetch-* headers do not count on their own, because Node's built-in fetch sends Sec-Fetch-Mode by itself. The AWS SDKs, the CLI and Node's fetch send neither header, measured against the CLI, boto3, the JavaScript SDK v3 and the fetch in Node 22. 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 server.dev_allowed_hosts (environment variable EXTENDDB__SERVER__DEV_ALLOWED_HOSTS). The host comes from the Host header, or the request target when there is no Host. A missing, repeated or disagreeing host, or a host that is not a valid name, is refused. Every other browser request gets 403 before authentication, as the DynamoDB JSON error on the API and the console error page on the console, naming the host and the setting. The 403 carries the X-Frame-Options, X-Content-Type-Options and Referrer-Policy headers that every other response carries. A same-origin GET or HEAD from a page served over plain HTTP 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 either header. A client that calls them through another name, such as a Compose service name, needs that name listed. The CLI's management client connects to the endpoint it is given or to the configured bind address, and it now puts an IPv6 bind address in brackets, so a dev server bound to ::1 receives a valid Host header. Any other request with neither header is served as before, whatever its host, so a Compose service name, host.docker.internal and the SDKs keep working on the API. The guard runs in developer-mode builds only; production serving is unchanged. The setting is parsed at startup. Entries that are not bare host names are dropped and named in the startup banner, which states the rule in the sentence the log also prints. Tests cover the host parser, the browser marker with the headers Node's fetch sends, and the decision for each host class, plus router-level cases for the API, the console and the admin routes in developer and production mode. The dev-mode wire tests send a browser request and an admin request under a foreign host to a running server and check the 403 and its security headers. --- crates/app/src/cmd_serve.rs | 11 + crates/app/src/manage_http.rs | 26 +- crates/config/src/display.rs | 7 + crates/config/src/lib.rs | 13 + crates/server/src/console/mod.rs | 22 + crates/server/src/dev_host_guard.rs | 377 ++++++++++++++ crates/server/src/dev_host_guard/tests.rs | 568 ++++++++++++++++++++++ crates/server/src/lib.rs | 17 + crates/server/src/response.rs | 20 +- crates/server/src/serve.rs | 5 + tests/test_dev_mode_authorization.py | 93 ++++ 11 files changed, 1156 insertions(+), 3 deletions(-) create mode 100644 crates/server/src/dev_host_guard.rs create mode 100644 crates/server/src/dev_host_guard/tests.rs diff --git a/crates/app/src/cmd_serve.rs b/crates/app/src/cmd_serve.rs index 37e5167ac..05978e8c1 100755 --- a/crates/app/src/cmd_serve.rs +++ b/crates/app/src/cmd_serve.rs @@ -383,6 +383,17 @@ fn print_dev_mode_banner(app_config: &config::AppConfig, foreground: bool) -> an 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 raw = app_config.server.dev_allowed_hosts.as_deref().unwrap_or(""); + let (kept, dropped) = extenddb_server::parse_dev_allowed_hosts(raw); + 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) + )); + } // Same stream split as the main banner: stdout for the daemon parent, // stderr in foreground mode so supervisors capture one stream. for msg in lines { diff --git a/crates/app/src/manage_http.rs b/crates/app/src/manage_http.rs index fadc794c2..eb21dbaac 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}") + } } /// Resolve the password from: CLI arg or `EXTENDDB_PASSWORD` env var. @@ -493,3 +504,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 cb95a8baa..5bbc9a207 100644 --- a/crates/config/src/display.rs +++ b/crates/config/src/display.rs @@ -77,6 +77,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 30b4f9c92..ff017193c 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -75,6 +75,18 @@ pub struct ServerConfig { /// Enable provisioned throughput throttling via token buckets. /// When `None` or `false`, all requests are allowed regardless of capacity. pub throttling_enabled: Option, + /// Developer mode only: a single comma-separated string of 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 stops a page whose name resolves to the loopback + /// address from driving the local server. Entries that are not bare host + /// names are dropped with a startup warning. Ignored outside a dev-mode + /// build. + #[serde(default)] + pub dev_allowed_hosts: Option, } impl Default for ServerConfig { @@ -86,6 +98,7 @@ impl Default for ServerConfig { run_dir: default_run_dir(), tls: TlsConfig::default(), throttling_enabled: None, + dev_allowed_hosts: None, } } } diff --git a/crates/server/src/console/mod.rs b/crates/server/src/console/mod.rs index 76cc752c7..82f4fbdab 100755 --- a/crates/server/src/console/mod.rs +++ b/crates/server/src/console/mod.rs @@ -27,6 +27,28 @@ use axum::routing::{get, post}; use session::SessionStore; +/// 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..74b74b1bc --- /dev/null +++ b/crates/server/src/dev_host_guard.rs @@ -0,0 +1,377 @@ +// 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. +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. +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 any +/// port, unwrap IPv6 brackets, and ignore a single trailing dot. Returns `None` +/// when the value has no host part or is structurally malformed, including +/// brackets around anything but an 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.starts_with(':')) { + return None; + } + let inner = &rest[..end]; + if inner.parse::().is_err() { + return None; + } + inner + } else { + match raw.split_once(':') { + // A second colon means an unbracketed IPv6, which is not valid in a + // Host header or authority. + Some((_, port)) if port.contains(':') => return None, + Some((h, _)) => h, + None => raw, + } + }; + let host = host.strip_suffix('.').unwrap_or(host); + if host.is_empty() { + return None; + } + Some(host) +} + +/// 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, + /// More than one `Host` header. + RepeatedHost, + /// 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::RepeatedHost => { + format!("Developer mode refused a request with more than one 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; + } + + // More than one Host header is refused: a split header lets a page + // disagree with what verification reads. + let mut host_values = headers.get_all("host").iter(); + let first = host_values.next(); + if host_values.next().is_some() { + return Decision::Reject(RejectReason::RepeatedHost); + } + let host_header = match first { + 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. +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..d066055e1 --- /dev/null +++ b/crates/server/src/dev_host_guard/tests.rs @@ -0,0 +1,568 @@ +// 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); +} + +#[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_repeated_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) + )); + // Repeated Host. + assert!(matches!( + evaluate( + &headers(&[ + ("host", "localhost"), + ("host", "rebind.example"), + ("origin", "http://x") + ]), + &uri("/"), + &[] + ), + Decision::Reject(RejectReason::RepeatedHost) + )); + // 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(_)) + )); +} + +// --- 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 69dc9e0a4..d5fbab243 100755 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -13,6 +13,7 @@ pub mod authz_cache; pub(crate) mod authz_resource; pub mod console; pub mod dev_credentials; +pub(crate) mod dev_host_guard; mod handler; mod import_export_paths; pub mod key_info_cache; @@ -26,6 +27,10 @@ mod serve; 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, LogTarget, ServeParams, log_to_syslog_raw, serve}; use std::path::PathBuf; @@ -68,6 +73,12 @@ 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, + /// Host names a dev-mode browser request, and any dev-mode request to + /// `/management` or `/metrics`, may use beyond an IP literal, `localhost` + /// and a `.localhost` name. Validated and lowercased at startup from + /// `server.dev_allowed_hosts`. Empty outside dev mode, where the host 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]>, @@ -123,6 +134,8 @@ pub async fn start_server( let tls_enabled = state.tls_enabled; 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(); @@ -203,6 +216,10 @@ pub async fn start_server( ); } + // 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); + // Apply security headers to all routes. let app = app.layer(security_layers); diff --git a/crates/server/src/response.rs b/crates/server/src/response.rs index af495d1b4..529a349c5 100755 --- a/crates/server/src/response.rs +++ b/crates/server/src/response.rs @@ -36,6 +36,24 @@ pub(crate) fn success_response(body: &Value, request_id: &str) -> Response { /// REQ-ERR-001: `__type` with prefix. REQ-ERR-002: message field. /// REQ-ERR-003: Omit `message` 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 { // Fix #14: Use full_error_type() which includes the prefix let mut body = serde_json::json!({ "__type": error.full_error_type(), @@ -57,8 +75,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 9ebbaccd4..06a197e46 100644 --- a/crates/server/src/serve.rs +++ b/crates/server/src/serve.rs @@ -468,6 +468,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. let resolve_paths = |raw_paths: &[String], @@ -588,6 +592,7 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { metrics: metrics.clone(), tls_enabled, dev_mode, + dev_allowed_hosts, import_paths, export_paths, throttle: throttle.clone(), diff --git a/tests/test_dev_mode_authorization.py b/tests/test_dev_mode_authorization.py index 354fffff8..25bef325d 100644 --- a/tests/test_dev_mode_authorization.py +++ b/tests/test_dev_mode_authorization.py @@ -25,6 +25,7 @@ import os import pytest +import requests from botocore.exceptions import ClientError from conftest import wait_for_active @@ -34,6 +35,21 @@ 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" +_GUARD_MESSAGE = "Developer mode refused a request" +_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. @@ -159,3 +175,80 @@ def test_transact_get_items_is_not_denied(self, dynamodb_client, dev_table): ), ) assert resp["Responses"][0]["Item"]["pk"]["S"] == "tg1" + + +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]): + """POST an unsigned ListTables under the rebinding host.""" + return requests.post( + f"{_base(endpoint_url)}/", + data=b"{}", + headers={ + "Host": _REBIND_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 != 403, resp.text + + 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", auth=_ADMIN_AUTH, timeout=10 + ) + assert resp.status_code != 403, resp.text + + 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) From 23dd692a0e134fc117fb227ada61cab5c8a3aeeb Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:33:15 +0000 Subject: [PATCH 02/12] docs(dev-mode): document the browser host check and its setting Describe the developer-mode host check in the dev image guide and add server.dev_allowed_hosts to the configuration reference and the sample config. The guide names the headers that mark a browser request and when a browser sends them, and states the host rule. Every request to the management routes and /metrics is checked on the host, so a client in another container that calls them by a Compose service name gets 403; the guide points it at the dev container's IP address or at docker exec in the dev container instead. A name is listed when a browser reaches the server through it, for example through a development proxy that forwards Host or a hosts-file alias for the loopback address. A listed name is trusted for browser requests as localhost is, so the guide says to list a name that resolves to the loopback address only when the developer controls that resolution, and not to list a single-label Compose service name for a browser on the host. The server sends no CORS headers, so a page on another origin cannot call it directly. A reverse proxy that rewrites Host hides the browser's host and has to check Host itself; a proxy that forwards Host keeps the check. The guide lists what the check does not cover: a same-origin GET or HEAD from a page served over plain HTTP, Firefox before 70 and EdgeHTML, and clients that are not browsers, which a web page cannot drive. The setting is a single string of bare host names, with no port, scheme or wildcard. The image properties now say that docker exec can run the extenddb binary in the image, which the guide's management example uses, but cannot open a shell. --- docs/dev-image.md | 126 ++++++++++++++++++++++++++++++++- docs/manuals/05-admin-guide.md | 1 + extenddb.sample.toml | 26 +++++++ 3 files changed, 151 insertions(+), 2 deletions(-) diff --git a/docs/dev-image.md b/docs/dev-image.md index 16a800aca..9f2eaf52f 100644 --- a/docs/dev-image.md +++ b/docs/dev-image.md @@ -47,6 +47,128 @@ and containment moves to the publish flag: always bind the host side to loopback, `-p 127.0.0.1:18080:18080`, as every example here does. Do not publish this port on a shared or routable interface. +## 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. + +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: + +```bash +docker exec extenddb manage --endpoint http://127.0.0.1:18080 \ + --user admin --password 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 it +directly, whether or not its 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 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. @@ -81,8 +203,8 @@ condition: service_healthy` work with no extra wiring. ## Image properties - Runtime base is distroless (`gcr.io/distroless/cc-debian12: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 bd74efb12..9307b3851 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -91,6 +91,7 @@ These settings require a server restart to take effect. | `bind_addr` | `127.0.0.1` | Network interface to bind | | `port` | `18443` | HTTP port | | `region` | `us-east-1` | AWS region for ARN generation. Baked into every backup ARN the server issues, so it must stay within `[a-z0-9-]` (a value outside that class makes the server's own backup ARNs "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 | +| `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 ignores it. Environment override: `EXTENDDB__SERVER__DEV_ALLOWED_HOSTS` | #### [storage] diff --git a/extenddb.sample.toml b/extenddb.sample.toml index 91869028a..1577bc90c 100755 --- a/extenddb.sample.toml +++ b/extenddb.sample.toml @@ -27,6 +27,32 @@ # 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. 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, with or + # without those headers. 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, so 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 /management or /metrics if it + # uses an IP address, such as the dev container's, + # or runs extenddb manage --endpoint + # http://127.0.0.1:18080 in the dev container + # through docker exec. Entries that are not bare + # host names are dropped with a startup warning. + # Ignored by a production build. Environment + # override: EXTENDDB__SERVER__DEV_ALLOWED_HOSTS. [storage] # backend = "postgres" # Storage backend: "postgres" (default), "mongodb", or "sqlite". From 8291dceff9cdde5e06aeaed299c54f6273207f45 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:58:35 +0000 Subject: [PATCH 03/12] fix(dev-mode): leave a repeated Host header to the repeated header refusal Main now refuses a request with more than one host or authorization header on every route, in repeated_headers::refuse_repeated_headers (#355). In start_server that layer runs outside the dev-mode host guard. The guard never sees a repeated Host header, so its own refusal for that case cannot run. This commit removes the RepeatedHost refusal from the guard and its case from the unit test. The guard reads the one Host header. A request with a repeated Host header still gets the 400 that main sends on every route. --- crates/server/src/dev_host_guard.rs | 17 ++++------------- crates/server/src/dev_host_guard/tests.rs | 15 +-------------- 2 files changed, 5 insertions(+), 27 deletions(-) diff --git a/crates/server/src/dev_host_guard.rs b/crates/server/src/dev_host_guard.rs index 74b74b1bc..7af75ed9f 100644 --- a/crates/server/src/dev_host_guard.rs +++ b/crates/server/src/dev_host_guard.rs @@ -226,8 +226,6 @@ enum RejectReason { InvalidHost(String), /// No readable `Host` header and no request-target authority. MissingHost, - /// More than one `Host` header. - RepeatedHost, /// A `Host` header and an absolute-form request target that name different /// hosts. HostMismatch, @@ -246,9 +244,6 @@ impl RejectReason { Self::MissingHost => { format!("Developer mode refused a request with no usable Host header. {rule}") } - Self::RepeatedHost => { - format!("Developer mode refused a request with more than one Host header. {rule}") - } Self::HostMismatch => format!( "Developer mode refused a request whose Host header and request target name \ different hosts. {rule}" @@ -274,14 +269,10 @@ fn evaluate(headers: &HeaderMap, uri: &Uri, allowed: &[String]) -> Decision { return Decision::Allow; } - // More than one Host header is refused: a split header lets a page - // disagree with what verification reads. - let mut host_values = headers.get_all("host").iter(); - let first = host_values.next(); - if host_values.next().is_some() { - return Decision::Reject(RejectReason::RepeatedHost); - } - let host_header = match first { + // 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), diff --git a/crates/server/src/dev_host_guard/tests.rs b/crates/server/src/dev_host_guard/tests.rs index d066055e1..a410b7549 100644 --- a/crates/server/src/dev_host_guard/tests.rs +++ b/crates/server/src/dev_host_guard/tests.rs @@ -231,7 +231,7 @@ fn admin_path_is_checked_on_the_host_alone() { } #[test] -fn missing_repeated_and_mismatched_host_are_refused() { +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("/"), &[]), @@ -242,19 +242,6 @@ fn missing_repeated_and_mismatched_host_are_refused() { evaluate(&headers(&[]), &uri("/management/accounts"), &[]), Decision::Reject(RejectReason::MissingHost) )); - // Repeated Host. - assert!(matches!( - evaluate( - &headers(&[ - ("host", "localhost"), - ("host", "rebind.example"), - ("origin", "http://x") - ]), - &uri("/"), - &[] - ), - Decision::Reject(RejectReason::RepeatedHost) - )); // Absolute-form target and Host header disagree. assert!(matches!( evaluate( From 122be9ac305217b0692314f803fd8550f85e7731 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:18:31 +0000 Subject: [PATCH 04/12] fix(dev-mode): read a host port only when it is digits host_label took everything after the first colon of a Host header or a request target as the port, unless that text held a second colon. A value such as 127.0.0.1:1@evil.com, 127.0.0.1:abc or localhost: then read as the loopback name before the colon. The guard served an admin request under such a value. host_label now reads a port only when it is one or more ASCII digits, after a name and after a bracketed IPv6 address. For any other value it returns None, so the guard refuses a browser request or an admin request that carries the value. New unit rows cover userinfo, a port name and an empty port after a loopback name. Another row sends an absolute-form target with userinfo and no Host header. --- crates/server/src/dev_host_guard.rs | 23 +++++++++++++++-------- crates/server/src/dev_host_guard/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/crates/server/src/dev_host_guard.rs b/crates/server/src/dev_host_guard.rs index 7af75ed9f..0001f31e8 100644 --- a/crates/server/src/dev_host_guard.rs +++ b/crates/server/src/dev_host_guard.rs @@ -180,10 +180,14 @@ fn is_loopback_name(host: &str) -> bool { && host[host.len() - SUFFIX.len()..].eq_ignore_ascii_case(SUFFIX)) } -/// Extract the host token from an authority or `Host`-header value: drop any -/// port, unwrap IPv6 brackets, and ignore a single trailing dot. Returns `None` -/// when the value has no host part or is structurally malformed, including -/// brackets around anything but an IPv6 address. +/// 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: brackets around anything but an IPv6 address, 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() { @@ -193,7 +197,7 @@ fn host_label(raw: &str) -> Option<&str> { // Bracketed IPv6: [addr] or [addr]:port. let end = rest.find(']')?; let after = &rest[end + 1..]; - if !(after.is_empty() || after.starts_with(':')) { + if !(after.is_empty() || after.strip_prefix(':').is_some_and(is_port)) { return None; } let inner = &rest[..end]; @@ -203,9 +207,7 @@ fn host_label(raw: &str) -> Option<&str> { inner } else { match raw.split_once(':') { - // A second colon means an unbracketed IPv6, which is not valid in a - // Host header or authority. - Some((_, port)) if port.contains(':') => return None, + Some((_, port)) if !is_port(port) => return None, Some((h, _)) => h, None => raw, } @@ -217,6 +219,11 @@ fn host_label(raw: &str) -> Option<&str> { 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 { diff --git a/crates/server/src/dev_host_guard/tests.rs b/crates/server/src/dev_host_guard/tests.rs index a410b7549..6725b490e 100644 --- a/crates/server/src/dev_host_guard/tests.rs +++ b/crates/server/src/dev_host_guard/tests.rs @@ -126,6 +126,17 @@ fn host_label_strips_port_brackets_and_one_trailing_dot() { 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] @@ -272,6 +283,15 @@ fn invalid_host_is_refused() { ), 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 --- From bad3f3dc7df634608e50ecc7ab5ad454f86d17fe Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:18:48 +0000 Subject: [PATCH 05/12] test(dev-mode): build the banner's host lines where the app tests reach them The dev-mode banner's host rule line and its notes for dropped entries came from print_dev_mode_banner, which no test calls. dev_mode_banner_lines now takes the names that parse_dev_allowed_hosts kept and the entries it dropped. It ends the banner with the rule line and one note for each dropped entry, in the same order as before. print_dev_mode_banner gets the two lists from parse_dev_allowed_hosts, the function that the host guard's allowed_hosts calls in serve. A new app test checks the last two banner lines by equality. --- crates/app/src/cmd_serve.rs | 79 +++++++++++++++++++++++-------------- 1 file changed, 49 insertions(+), 30 deletions(-) diff --git a/crates/app/src/cmd_serve.rs b/crates/app/src/cmd_serve.rs index 52d93d75f..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,24 +413,17 @@ fn print_dev_mode_banner( use extenddb_server::dev_credentials; let dev_creds = dev_credentials::resolve()?; - let mut lines = dev_mode_banner_lines( + 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, ); - // The host rule the server enforces, so the operator sees it without - // reading the log. Dropped entries are named too. - let raw = app_config.server.dev_allowed_hosts.as_deref().unwrap_or(""); - let (kept, dropped) = extenddb_server::parse_dev_allowed_hosts(raw); - 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) - )); - } // Same stream split as the main banner: stdout for the daemon parent, // stderr in foreground mode so supervisors capture one stream. for msg in lines { @@ -454,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; @@ -511,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 } @@ -539,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"] { @@ -551,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}"); @@ -575,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}" @@ -593,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}" @@ -610,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}" @@ -628,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 { From 47ecd4f181655201f08778cac107b1c187bcdfc7 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:22:46 +0000 Subject: [PATCH 06/12] test(dev-mode): check the exact answers of the two requests the guard serves test_same_request_without_a_marker_is_not_refused and test_admin_get_under_the_endpoint_host_is_not_refused asserted only that the status was not 403, so a 5xx passed both. The CI job sets no admin password, and there the admin GET passed on a 401 for the wrong password. The ListTables test now asserts 400 and the MissingAuthenticationToken body by equality. The admin GET sends a password the server does not have and asserts 401 with the body Invalid credentials. Both answers come from authentication, which runs after the host guard. --- tests/test_dev_mode_authorization.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/test_dev_mode_authorization.py b/tests/test_dev_mode_authorization.py index 16813a1f7..fe158f2b6 100644 --- a/tests/test_dev_mode_authorization.py +++ b/tests/test_dev_mode_authorization.py @@ -51,8 +51,16 @@ os.environ.get("EXTENDDB_ADMIN_USER", "admin"), os.environ.get("EXTENDDB_ADMIN_PASSWORD", "not-the-password"), ) +# A password the server does not have. The admin routes answer it with 401, +# which shows that a request passed the host guard. +_WRONG_ADMIN_AUTH = ("admin", "not-the-password") _REBIND_HOST = "rebind.example" _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#MissingAuthenticationToken", + "message": "Missing Authentication Token", +} _SECURITY_HEADERS = { "x-frame-options": "DENY", "x-content-type-options": "nosniff", @@ -339,7 +347,8 @@ def test_browser_request_under_a_rebinding_host_is_refused(self, endpoint_url): def test_same_request_without_a_marker_is_not_refused(self, endpoint_url): resp = _list_tables_unsigned(endpoint_url, {}) - assert resp.status_code != 403, resp.text + 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. @@ -355,9 +364,9 @@ def test_admin_get_under_a_rebinding_host_is_refused(self, endpoint_url): def test_admin_get_under_the_endpoint_host_is_not_refused(self, endpoint_url): resp = requests.get( - f"{_base(endpoint_url)}/management/accounts", auth=_ADMIN_AUTH, timeout=10 + f"{_base(endpoint_url)}/management/accounts", auth=_WRONG_ADMIN_AUTH, timeout=10 ) - assert resp.status_code != 403, resp.text + assert (resp.status_code, resp.text) == (401, "Invalid credentials") def test_console_browser_request_under_a_rebinding_host_gets_the_html_403( self, endpoint_url From 4a72ee586ab66a6b1161b125fdfdffab2e21ce1a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:23:51 +0000 Subject: [PATCH 07/12] test(dev-mode): check that server.dev_allowed_hosts reaches the guard No test set server.dev_allowed_hosts. A serve that gave the guard no names passed every server unit test and every dev-mode wire test. The dev-mode CI job now sets EXTENDDB__SERVER__DEV_ALLOWED_HOSTS=app.test for every step. The server reads the variable at startup, and the new test_a_listed_host_is_not_refused reads it too. Under Host app.test the test sends an unsigned ListTables with an Origin header and expects 400 with the MissingAuthenticationToken body. It then sends an admin GET with a wrong password and expects 401 with the body Invalid credentials. When the variable does not list app.test, pytest skips the test with a reason that names the variable. A local run against a server without the setting then does not fail. --- .github/workflows/integration.yml | 4 ++++ tests/test_dev_mode_authorization.py | 32 +++++++++++++++++++++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 47567ef56..80eec18c2 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -571,6 +571,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/tests/test_dev_mode_authorization.py b/tests/test_dev_mode_authorization.py index fe158f2b6..7cb3f9cc3 100644 --- a/tests/test_dev_mode_authorization.py +++ b/tests/test_dev_mode_authorization.py @@ -55,6 +55,9 @@ # which shows that a request passed the host guard. _WRONG_ADMIN_AUTH = ("admin", "not-the-password") _REBIND_HOST = "rebind.example" +# The CI dev-mode job lists this name in EXTENDDB__SERVER__DEV_ALLOWED_HOSTS. +_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 = { @@ -312,13 +315,15 @@ def _base(endpoint_url: str | None) -> str: return endpoint_url.rstrip("/") -def _list_tables_unsigned(endpoint_url: str | None, extra_headers: dict[str, str]): - """POST an unsigned ListTables under the rebinding host.""" +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": _REBIND_HOST, + "Host": host, "Content-Type": "application/x-amz-json-1.0", "X-Amz-Target": "DynamoDB_20120810.ListTables", **extra_headers, @@ -368,6 +373,27 @@ def test_admin_get_under_the_endpoint_host_is_not_refused(self, endpoint_url): ) assert (resp.status_code, resp.text) == (401, "Invalid credentials") + @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}, + auth=_WRONG_ADMIN_AUTH, + timeout=10, + ) + assert (resp.status_code, resp.text) == (401, "Invalid credentials") + def test_console_browser_request_under_a_rebinding_host_gets_the_html_403( self, endpoint_url ): From 9b0fa1383b273d9769901d041b90b8ed78bea8e6 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:32:07 +0000 Subject: [PATCH 08/12] docs(dev-mode): fix the host check docs and shorten the setting's copies docs/dev-image.md said that a page on another origin cannot call the server. That holds for the DynamoDB API, whose preflight gets 405. 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. The guide now says both. The guide said that Safari hands .localhost names to the system resolver but not what follows. That resolver can pass the name to a DNS server on the network. The DNS server can serve a page under the name and then answer with the loopback address. The guide now says so, and .localhost names stay allowed. The docker exec example passed --password, which makes the CLI print a warning. It now passes EXTENDDB_PASSWORD into the container and says where the admin password comes from. The admin guide, the sample config and the ServerConfig field doc said that a production build ignores server.dev_allowed_hosts. A production build does not use the value, but a value that is not a string still stops it at startup. The admin guide and the field doc now say that. The sample config's 26-line comment on the setting is now two lines that point to the admin guide row. The ServerConfig field doc now states the host rule in one sentence and names the admin guide. The AppState field doc no longer repeats the rule. --- crates/config/src/lib.rs | 15 ++++++--------- crates/server/src/lib.rs | 8 +++----- docs/dev-image.md | 25 ++++++++++++++++++------- docs/manuals/05-admin-guide.md | 2 +- extenddb.sample.toml | 27 ++------------------------- 5 files changed, 30 insertions(+), 47 deletions(-) diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 49d22245f..f10265e44 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -85,15 +85,12 @@ pub struct ServerConfig { #[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) 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 stops a page whose name resolves to the loopback - /// address from driving the local server. Entries that are not bare host - /// names are dropped with a startup warning. Ignored outside a dev-mode - /// build. + /// (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 a value that is not a string still + /// stops it at startup. #[serde(default)] pub dev_allowed_hosts: Option, } diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 1e2dd8fd8..45e4d369e 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -92,11 +92,9 @@ 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, - /// Host names a dev-mode browser request, and any dev-mode request to - /// `/management` or `/metrics`, may use beyond an IP literal, `localhost` - /// and a `.localhost` name. Validated and lowercased at startup from - /// `server.dev_allowed_hosts`. Empty outside dev mode, where the host guard - /// is not installed. + /// 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). diff --git a/docs/dev-image.md b/docs/dev-image.md index 5c8f88211..116777155 100644 --- a/docs/dev-image.md +++ b/docs/dev-image.md @@ -125,7 +125,10 @@ 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. +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. @@ -137,11 +140,16 @@ container that calls these routes by the Compose service name, such as 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: +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 extenddb manage --endpoint http://127.0.0.1:18080 \ - --user admin --password list-accounts +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 @@ -166,10 +174,13 @@ 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 it -directly, whether or not its name is listed. For a page at +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. +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 diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index 9a30e014d..ab5e45f3d 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -118,7 +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 ignores it. Environment override: `EXTENDDB__SERVER__DEV_ALLOWED_HOSTS` | +| `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 a value that is not a string still stops it at startup. Environment override: `EXTENDDB__SERVER__DEV_ALLOWED_HOSTS` | #### [storage] diff --git a/extenddb.sample.toml b/extenddb.sample.toml index 1a20122e2..770ff8cf4 100755 --- a/extenddb.sample.toml +++ b/extenddb.sample.toml @@ -30,31 +30,8 @@ # 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. 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, with or - # without those headers. 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, so 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 /management or /metrics if it - # uses an IP address, such as the dev container's, - # or runs extenddb manage --endpoint - # http://127.0.0.1:18080 in the dev container - # through docker exec. Entries that are not bare - # host names are dropped with a startup warning. - # Ignored by a production build. Environment - # override: EXTENDDB__SERVER__DEV_ALLOWED_HOSTS. + # 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". From 1439151a4751135bc4fdcbf91d81d1a4bf7bd54b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:53:06 +0000 Subject: [PATCH 09/12] test(dev-mode): send the admin GETs that pass the host check without credentials Two tests check that an admin GET passes the host check, one under the endpoint host and one under a listed name. Each sent a wrong password and expected 401 "Invalid credentials". The server counts a wrong password as a failed login. After 5 failures in 15 minutes it refuses that user from that address. So the third run of the file against one server failed with 429. The two GETs now send no Authorization header and expect 401 "Missing Authorization header". The server answers a missing header before it checks the rate limits, and it records no failure. A comment that repeated the listed-host test's docstring is gone. --- tests/test_dev_mode_authorization.py | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/tests/test_dev_mode_authorization.py b/tests/test_dev_mode_authorization.py index 7cb3f9cc3..5b71a1883 100644 --- a/tests/test_dev_mode_authorization.py +++ b/tests/test_dev_mode_authorization.py @@ -51,11 +51,7 @@ os.environ.get("EXTENDDB_ADMIN_USER", "admin"), os.environ.get("EXTENDDB_ADMIN_PASSWORD", "not-the-password"), ) -# A password the server does not have. The admin routes answer it with 401, -# which shows that a request passed the host guard. -_WRONG_ADMIN_AUTH = ("admin", "not-the-password") _REBIND_HOST = "rebind.example" -# The CI dev-mode job lists this name in EXTENDDB__SERVER__DEV_ALLOWED_HOSTS. _LISTED_HOST = "app.test" _ALLOWED_HOSTS = os.environ.get("EXTENDDB__SERVER__DEV_ALLOWED_HOSTS", "").lower() _GUARD_MESSAGE = "Developer mode refused a request" @@ -368,10 +364,8 @@ def test_admin_get_under_a_rebinding_host_is_refused(self, endpoint_url): _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", auth=_WRONG_ADMIN_AUTH, timeout=10 - ) - assert (resp.status_code, resp.text) == (401, "Invalid credentials") + 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(","), @@ -389,10 +383,9 @@ def test_a_listed_host_is_not_refused(self, endpoint_url): resp = requests.get( f"{_base(endpoint_url)}/management/accounts", headers={"Host": _LISTED_HOST}, - auth=_WRONG_ADMIN_AUTH, timeout=10, ) - assert (resp.status_code, resp.text) == (401, "Invalid credentials") + 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 From 57e5261a04d506226d37058d4250aa269faea954 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:53:07 +0000 Subject: [PATCH 10/12] docs(dev-mode): list the host check in the README and fix doc comments The README lists the server's HTTP checks that the WebAssembly build has no counterpart for. The developer-mode host check is one of them. The list now names it as the refusal of a browser request or a /management or /metrics request whose host the check does not allow. The host_label doc comment now lists two more malformed values that return None. One is an opening bracket with no closing one. The other is text after the closing bracket other than a port, such as `[::1]evil`. The module doc puts DynamoDB and EdgeHTML in backticks, and dropped_entry_note, rule_line and parse_dev_allowed_hosts are #[must_use]. That clears the five clippy::pedantic warnings on lines this branch adds. --- README.md | 4 +++- crates/server/src/dev_host_guard.rs | 16 ++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 161121574..fd7610025 100755 --- a/README.md +++ b/README.md @@ -535,7 +535,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/crates/server/src/dev_host_guard.rs b/crates/server/src/dev_host_guard.rs index 0001f31e8..f7491b4d7 100644 --- a/crates/server/src/dev_host_guard.rs +++ b/crates/server/src/dev_host_guard.rs @@ -23,7 +23,7 @@ //! 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 +//! 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 @@ -34,7 +34,7 @@ //! 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 +//! 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. @@ -93,6 +93,7 @@ pub(crate) fn allowed_hosts(dev_mode: bool, raw: Option<&str>) -> Arc<[String]> /// 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, \ @@ -111,6 +112,7 @@ fn rule() -> String { /// 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() @@ -184,10 +186,11 @@ fn is_loopback_name(host: &str) -> bool { /// 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: brackets around anything but an IPv6 address, 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. +/// 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() { @@ -354,6 +357,7 @@ fn reject_response(path: &str, reason: &RejectReason) -> Response { /// 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(); From 662ef93819ef14086af30ca3a68208a21d9684dc Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:03:27 +0000 Subject: [PATCH 11/12] docs(config): say which dev_allowed_hosts values stop a production build The admin guide and the doc comment of ServerConfig.dev_allowed_hosts said that a value that is not a string stops a production build at startup. The config loader reads a number or a boolean as its text, so a production build starts with dev_allowed_hosts = 5, = true or = 1.5. Only an array or a table stops it. Both places now say that. --- crates/config/src/lib.rs | 4 ++-- docs/manuals/05-admin-guide.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index f10265e44..13918630a 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -89,8 +89,8 @@ pub struct ServerConfig { /// 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 a value that is not a string still - /// stops it at startup. + /// build does not use the value, but an array or a table still stops it at + /// startup. #[serde(default)] pub dev_allowed_hosts: Option, } diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index ab5e45f3d..e19cfac3d 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -118,7 +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 a value that is not a string still stops it at startup. Environment override: `EXTENDDB__SERVER__DEV_ALLOWED_HOSTS` | +| `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] From f3fdc0f21dc4912baf2372fcf208ddaf3f65903d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:22:31 +0000 Subject: [PATCH 12/12] test(dev-mode): expect the answer main gives a request with no token Since #1290, the server gives a request with no Authorization header the type MissingAuthenticationTokenException and the message "Request is missing Authentication Token". DynamoDB sends this answer. The tests test_same_request_without_a_marker_is_not_refused and test_a_listed_host_is_not_refused compared the body with the earlier type and message. They failed in the merge queue run of 27 Nov, on main c175e427e. --- tests/test_dev_mode_authorization.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_dev_mode_authorization.py b/tests/test_dev_mode_authorization.py index 5b71a1883..4c432447e 100644 --- a/tests/test_dev_mode_authorization.py +++ b/tests/test_dev_mode_authorization.py @@ -57,8 +57,8 @@ _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#MissingAuthenticationToken", - "message": "Missing Authentication Token", + "__type": "com.amazon.coral.service#MissingAuthenticationTokenException", + "message": "Request is missing Authentication Token", } _SECURITY_HEADERS = { "x-frame-options": "DENY",