diff --git a/crates/app/src/cmd_serve.rs b/crates/app/src/cmd_serve.rs index 5ae4e2d5e..127836936 100755 --- a/crates/app/src/cmd_serve.rs +++ b/crates/app/src/cmd_serve.rs @@ -14,7 +14,7 @@ use crate::serve_helpers::verify_daemon_started; use crate::serve_helpers::{check_config_permissions, narrow_served_tls_key}; use extenddb_config as config; use extenddb_config::pid_file_path; -use extenddb_server::{BuildInfo, LogTarget, ServeParams}; +use extenddb_server::{BuildInfo, Extensions, LogTarget, ServeParams}; #[derive(Args, Default)] pub struct ServeArgs { @@ -51,7 +51,11 @@ pub struct ServeArgs { /// Bind the listening socket, daemonize, then start the tokio runtime. /// Binding before forking ensures port conflicts are reported to stderr /// before the parent process exits (D-4). -pub fn run(args: &ServeArgs, build: BuildInfo) -> anyhow::Result<()> { +pub fn run(args: &ServeArgs, build: BuildInfo, extensions: Extensions) -> anyhow::Result<()> { + // A refused extension prefix is a startup error; checking it here, before + // the backend connects or the daemon forks, puts the message on stderr. + extenddb_server::validate_extension_prefixes(&extensions.http) + .map_err(|e| anyhow::anyhow!("{e}"))?; // Load config early so bind address is known before fork. A dev-mode // build serves with built-in defaults when no config file exists // (zero-config local/CI use: loopback, in-memory storage, seeded dev @@ -280,7 +284,8 @@ pub fn run(args: &ServeArgs, build: BuildInfo) -> anyhow::Result<()> { } else { LogTarget::Syslog }) - .with_dev_mode(cfg!(feature = "dev-mode")); + .with_dev_mode(cfg!(feature = "dev-mode")) + .with_extensions(extensions); if config_exists { params = params.with_config_path(&args.config); } diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index 3e9a781ab..48b3ac389 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -21,6 +21,19 @@ //! }) //! } //! ``` +//! +//! A backend that adds HTTP routes or a per-request observer calls +//! [`run_with`] with an [`Extensions`] value; [`run`] is the same call with the +//! empty default: +//! +//! ```ignore +//! extenddb_app::run_with( +//! build, +//! extenddb_app::Extensions::default() +//! .with_router("/_mybackend/status", status_router()) +//! .with_request_observer(my_observer), +//! ) +//! ``` mod cmd_backup; mod cmd_catalog_check; @@ -51,6 +64,16 @@ use clap::{Parser, Subcommand}; /// `extenddb-app` dependency. pub use extenddb_server::BuildInfo; +/// A thin binary's extension points, re-exported from `extenddb-server` so a +/// thin `main` needs only the `extenddb-app` dependency to use them. Pass an +/// [`Extensions`] to [`run_with`]; [`run`] uses the empty default. +pub use extenddb_server::{Extensions, RequestObserver, RequestRecord}; + +/// The `axum` the server is built with, so a thin binary builds its +/// [`Extensions::http`] routers against the same `Router` type without naming +/// the version itself. +pub use extenddb_server::axum; + #[derive(Parser)] #[command(name = "extenddb", about = "ExtendDB — DynamoDB-compatible API server")] struct Cli { @@ -102,12 +125,28 @@ enum Command { /// Parse the command line and dispatch the selected subcommand. /// /// The backend must already be installed via -/// [`extenddb_storage::set_backend`] before this is called. +/// [`extenddb_storage::set_backend`] before this is called. The same as +/// [`run_with`] with the empty [`Extensions::default`]. /// /// # Errors /// /// Returns any error produced by the selected subcommand. pub fn run(build: BuildInfo) -> anyhow::Result<()> { + run_with(build, Extensions::default()) +} + +/// Parse the command line and dispatch the selected subcommand, handing a thin +/// binary's [`Extensions`] to the `serve` subcommand. +/// +/// The backend must already be installed via +/// [`extenddb_storage::set_backend`] before this is called. Every subcommand +/// other than `serve` ignores the extensions, so a binary that passes routers +/// or an observer keeps the full command line. +/// +/// # Errors +/// +/// Returns any error produced by the selected subcommand. +pub fn run_with(build: BuildInfo, extensions: Extensions) -> anyhow::Result<()> { let cli = Cli::parse(); if cli.version { @@ -116,7 +155,7 @@ pub fn run(build: BuildInfo) -> anyhow::Result<()> { } match cli.command.unwrap_or(Command::Version) { - Command::Serve(args) => cmd_serve::run(&args, build), + Command::Serve(args) => cmd_serve::run(&args, build, extensions), Command::Init(args) => { let code = run_interactive(cmd_init::run(args, build.version))?; if code != 0 { diff --git a/crates/engine/src/pre_dispatch.rs b/crates/engine/src/pre_dispatch.rs index 49c56ee71..28aba9c0c 100644 --- a/crates/engine/src/pre_dispatch.rs +++ b/crates/engine/src/pre_dispatch.rs @@ -62,6 +62,14 @@ pub fn parse_request<'a>( } impl ParsedRequest<'_> { + /// The parsed body, for what the server reads from it before `admit`: + /// the table name of a request observer's record, which a request that + /// authentication refuses also carries. + #[must_use] + pub fn body(&self) -> &Value { + &self.body + } + /// The second step: refuse the requests no deployment serves, then return /// the body to dispatch. /// diff --git a/crates/server/src/extensions.rs b/crates/server/src/extensions.rs new file mode 100644 index 000000000..6f19d9548 --- /dev/null +++ b/crates/server/src/extensions.rs @@ -0,0 +1,245 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Extension points a thin binary hands to the server at startup. +//! +//! A backend crate's `main` calls `extenddb_app::run_with(build, extensions)` +//! with an [`Extensions`] value. Its HTTP routers are mounted under their +//! prefixes after the built-in routes and before the response security layer, +//! so an extension response carries the same security headers as a built-in +//! one. Its [`RequestObserver`], when set, receives one [`RequestRecord`] per +//! request that reached authentication: the operation, the status, the error +//! type, the latency, a hash of the request body and the two SDK correlation +//! headers. The record is built only when an observer is installed; with none, +//! the request path hashes no body and builds no record. + +use std::hash::{DefaultHasher, Hasher}; +use std::sync::Arc; + +use axum::Router; + +/// What a thin binary adds to the server. Build it from +/// [`Extensions::default`] with [`with_router`](Self::with_router) and +/// [`with_request_observer`](Self::with_request_observer); the struct may gain +/// fields in a minor release. +#[derive(Default)] +#[non_exhaustive] +pub struct Extensions { + /// Routers to mount, each under an absolute prefix of literal segments + /// that is not `/`, is not at or under a built-in route, and is not at, + /// under or above another extension's prefix. A violation is a startup + /// error. The server applies its response security headers to these + /// routes, and the layers in front of every route: a `ServiceUnavailable` + /// answer while the serving registration is lost, the refusal of a + /// repeated `host` or `authorization` header, and the request body + /// timeout. Nothing else applies: no authentication, no request rate + /// limit, and axum's default 2 MB body limit for the limited extractors + /// (none for a raw `Body`). A route that changes state or reads data + /// authenticates in its own handler or layer. + pub http: Vec<(String, Router)>, + /// Receives one record per request that reached authentication. + pub request_observer: Option>, +} + +impl Extensions { + /// Add a router to mount under `prefix`. + #[must_use] + pub fn with_router(mut self, prefix: impl Into, router: Router) -> Self { + self.http.push((prefix.into(), router)); + self + } + + /// Install the per-request observer. + #[must_use] + pub fn with_request_observer(mut self, observer: Arc) -> Self { + self.request_observer = Some(observer); + self + } +} + +/// A per-request hook. The server calls [`on_response`](Self::on_response) +/// once per request after the response is built, on the request's own task, +/// outside the request scope and holding no lock. The call runs before the +/// response is written to the socket, so a slow observer delays the response; +/// an observer that does more than record should hand the record to its own +/// task. Calls for different requests arrive concurrently from the connection +/// tasks, in no defined order. The method must not panic: a panic there fails +/// the request and closes its connection. +pub trait RequestObserver: Send + Sync { + /// One request's outcome. + fn on_response(&self, record: RequestRecord); +} + +/// What the server reports about one request. +/// +/// Built through the server only; the struct may gain fields in a minor +/// release. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct RequestRecord { + /// The request id the client received in `x-amzn-RequestId`. + pub request_id: String, + /// The operation name from `X-Amz-Target`. + pub operation: String, + /// The request's top-level `TableName`, when it has one: `None` for the + /// batch, transaction, PartiQL and stream operations, whose tables are + /// inside the request body. + pub table_name: Option, + /// The authenticated account: `Some` on every recorded request that got a + /// response after authentication, `None` on an authentication refusal and + /// on an abandoned request (status 0). + pub account_id: Option, + /// The HTTP status the client received, or 0 when no response was built + /// because the client went away while the request was in flight. + pub status: u16, + /// The `__type` of the error the client received, without its namespace, + /// or `None` on success. + pub error_type: Option, + /// Handler wall time in microseconds, from the handler's entry (the body + /// has been read by then) to the record. + pub latency_us: u64, + /// A 64-bit hash of the raw request body, so an observer can tell retries + /// of one request from distinct requests without holding the body. The + /// standard library's default hasher: compare values within one process + /// only, not across builds. + pub body_hash: u64, + /// `amz-sdk-invocation-id` when the client sent it. + pub sdk_invocation_id: Option, + /// `amz-sdk-request` when the client sent it. + pub sdk_request: Option, +} + +/// Hash of the raw request body for [`RequestRecord::body_hash`]. +pub(crate) fn body_hash(bytes: &[u8]) -> u64 { + let mut hasher = DefaultHasher::new(); + hasher.write(bytes); + hasher.finish() +} + +/// Prefixes the server owns; an extension may not mount at or under them. +pub(crate) const RESERVED_PREFIXES: &[&str] = &["/health", "/metrics", "/management", "/console"]; + +/// Why an extension router could not be mounted. The server does not start. +#[derive(Debug)] +pub enum ExtensionMountError { + /// The prefix does not start with `/`. + NotAbsolute(String), + /// The prefix is `/`, which would shadow the request handler. + Root, + /// The prefix ends with `/`, has an empty segment (`//`), has a parameter + /// or wildcard segment (`{`, `}`, `*`), or has a byte no request path can + /// carry (`?`, `#`, a space, a control byte). `Router::nest` refuses or + /// misroutes the first group, an extension at `/{id}` would take every + /// top-level path the server does not register, and a router under the + /// last group mounts but no request can reach it. + BadShape(String), + /// The prefix is a reserved prefix, is at or under one, or is at, under + /// or above an earlier extension's prefix. + Collision { + /// The prefix that was refused. + prefix: String, + /// The route it collides with. + conflicts_with: String, + }, +} + +impl std::fmt::Display for ExtensionMountError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::NotAbsolute(prefix) => { + write!(f, "extension router prefix '{prefix}' must start with '/'") + } + Self::Root => write!( + f, + "extension router prefix '/' is not allowed: it would shadow the \ + request handler at the root path" + ), + Self::BadShape(prefix) => write!( + f, + "extension router prefix '{prefix}' must be one or more non-empty \ + literal path segments with no trailing '/', no parameter or wildcard, \ + and no '?', '#', space or control byte" + ), + Self::Collision { + prefix, + conflicts_with, + } => write!( + f, + "extension router prefix '{prefix}' collides with '{conflicts_with}'" + ), + } + } +} + +impl std::error::Error for ExtensionMountError {} + +/// `a` is `b`, or is under `b` (`b` followed by `/`). +fn at_or_under(a: &str, b: &str) -> bool { + a == b || (a.len() > b.len() && a.starts_with(b) && a.as_bytes()[b.len()] == b'/') +} + +/// Check one prefix against the rules and the prefixes already taken. +pub(crate) fn validate_extension_prefix( + prefix: &str, + already_taken: &[String], +) -> Result<(), ExtensionMountError> { + if !prefix.starts_with('/') { + return Err(ExtensionMountError::NotAbsolute(prefix.to_owned())); + } + if prefix == "/" { + return Err(ExtensionMountError::Root); + } + if prefix.ends_with('/') + || prefix.contains("//") + || prefix + .bytes() + .any(|b| matches!(b, b'{' | b'}' | b'*' | b'?' | b'#' | b' ') || b.is_ascii_control()) + { + return Err(ExtensionMountError::BadShape(prefix.to_owned())); + } + if let Some(reserved) = RESERVED_PREFIXES.iter().find(|r| at_or_under(prefix, r)) { + return Err(ExtensionMountError::Collision { + prefix: prefix.to_owned(), + conflicts_with: (*reserved).to_owned(), + }); + } + if let Some(taken) = already_taken + .iter() + .find(|t| at_or_under(prefix, t) || at_or_under(t, prefix)) + { + return Err(ExtensionMountError::Collision { + prefix: prefix.to_owned(), + conflicts_with: taken.clone(), + }); + } + Ok(()) +} + +/// Check every prefix in `http` as [`mount_extensions`] will, without +/// mounting. The server calls this before it connects to the backend or +/// forks, so a refused prefix reaches stderr instead of a daemon's log. +pub fn validate_extension_prefixes(http: &[(String, Router)]) -> Result<(), ExtensionMountError> { + let mut taken: Vec = Vec::with_capacity(http.len()); + for (prefix, _) in http { + validate_extension_prefix(prefix, &taken)?; + taken.push(prefix.clone()); + } + Ok(()) +} + +/// Nest each router under its prefix, in order, after checking it. +pub(crate) fn mount_extensions( + mut app: Router, + http: Vec<(String, Router)>, +) -> Result { + let mut taken: Vec = Vec::with_capacity(http.len()); + for (prefix, router) in http { + validate_extension_prefix(&prefix, &taken)?; + app = app.nest(&prefix, router); + taken.push(prefix); + } + Ok(app) +} + +#[cfg(test)] +mod tests; diff --git a/crates/server/src/extensions/tests.rs b/crates/server/src/extensions/tests.rs new file mode 100644 index 000000000..8397622ed --- /dev/null +++ b/crates/server/src/extensions/tests.rs @@ -0,0 +1,221 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! Mounting rules for thin-bin extension routers: a mounted router answers +//! under its prefix and behind the security layer; a reserved, nested, +//! duplicate, relative or root prefix is refused with the colliding route +//! named; the empty default mounts nothing. + +use axum::Router; +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use axum::routing::get; +use tower::ServiceExt; + +use super::{ + ExtensionMountError, Extensions, body_hash, mount_extensions, validate_extension_prefix, + validate_extension_prefixes, +}; + +fn probe_router() -> Router { + Router::new().route("/", get(|| async { StatusCode::OK })) +} + +async fn send(app: Router, path: &str) -> axum::response::Response { + app.oneshot( + Request::builder() + .uri(path) + .body(Body::empty()) + .expect("request builds"), + ) + .await + .expect("router responds") +} + +#[tokio::test] +async fn a_mounted_extension_answers_under_its_prefix_behind_the_security_layer() { + let app = mount_extensions( + Router::new(), + vec![("/_extenddb/probe".to_owned(), probe_router())], + ) + .expect("prefix mounts"); + let app = crate::apply_security_headers(app); + + let resp = send(app, "/_extenddb/probe").await; + + assert_eq!(resp.status(), StatusCode::OK); + assert_eq!( + resp.headers() + .get("x-content-type-options") + .expect("security layer applied to the extension"), + "nosniff" + ); + assert_eq!( + resp.headers().get("x-frame-options").expect("frame header"), + "DENY" + ); +} + +#[tokio::test] +async fn the_default_extensions_mount_nothing() { + let app = mount_extensions(Router::new(), Extensions::default().http).expect("empty mounts"); + let app = crate::apply_security_headers(app); + + let resp = send(app, "/_extenddb/probe").await; + + assert_eq!(resp.status(), StatusCode::NOT_FOUND); +} + +#[test] +fn a_reserved_prefix_is_refused_naming_the_conflict() { + let err = validate_extension_prefix("/management", &[]).expect_err("must reject"); + let msg = err.to_string(); + assert!( + msg.contains("/management"), + "message names the prefix: {msg}" + ); +} + +#[test] +fn a_prefix_must_be_absolute_and_not_root() { + assert!(matches!( + validate_extension_prefix("relative", &[]), + Err(ExtensionMountError::NotAbsolute(p)) if p == "relative" + )); + assert!(matches!( + validate_extension_prefix("/", &[]), + Err(ExtensionMountError::Root) + )); + assert!(validate_extension_prefix("/_extenddb/probe", &[]).is_ok()); +} + +#[test] +fn a_prefix_under_a_reserved_one_is_refused_naming_the_reserved_prefix() { + for (under, reserved) in [ + ("/console/probe", "/console"), + ("/console/login/x", "/console"), + ("/management/accounts", "/management"), + ("/health/live", "/health"), + ("/metrics", "/metrics"), + ] { + match validate_extension_prefix(under, &[]) { + Err(ExtensionMountError::Collision { + prefix, + conflicts_with, + }) => { + assert_eq!(prefix, under); + assert_eq!(conflicts_with, reserved); + } + other => panic!("{under} must collide with {reserved}, got {other:?}"), + } + } + // A prefix that shares the first characters only is not under it. + assert!(validate_extension_prefix("/consoles", &[]).is_ok()); + assert!(validate_extension_prefix("/healthz", &[]).is_ok()); +} + +#[test] +fn a_duplicate_extension_prefix_is_refused() { + let taken = vec!["/_extenddb/a".to_owned()]; + let err = validate_extension_prefix("/_extenddb/a", &taken).expect_err("must reject"); + assert!(matches!( + err, + ExtensionMountError::Collision { ref prefix, ref conflicts_with } + if prefix == "/_extenddb/a" && conflicts_with == "/_extenddb/a" + )); +} + +#[tokio::test] +async fn a_refused_prefix_stops_the_mount_at_that_router() { + let err = mount_extensions( + Router::new(), + vec![ + ("/_extenddb/a".to_owned(), probe_router()), + ("/console/x".to_owned(), probe_router()), + ], + ) + .expect_err("the second prefix is refused"); + assert!(err.to_string().contains("/console/x")); +} + +#[test] +fn body_hash_tells_bodies_apart_and_is_stable() { + let a = body_hash(br#"{"TableName":"t","Key":{"pk":{"S":"1"}}}"#); + let b = body_hash(br#"{"TableName":"t","Key":{"pk":{"S":"2"}}}"#); + assert_ne!(a, b); + assert_eq!(a, body_hash(br#"{"TableName":"t","Key":{"pk":{"S":"1"}}}"#)); +} + +#[test] +fn a_prefix_at_under_or_above_an_earlier_extension_is_refused_naming_it() { + let taken = vec!["/_a/b".to_owned()]; + for prefix in ["/_a/b", "/_a/b/c", "/_a"] { + match validate_extension_prefix(prefix, &taken) { + Err(ExtensionMountError::Collision { + prefix: p, + conflicts_with, + }) => { + assert_eq!(p, prefix); + assert_eq!(conflicts_with, "/_a/b"); + } + other => panic!("{prefix} must collide with /_a/b, got {other:?}"), + } + } + // A sibling and a prefix sharing only the first characters are fine. + assert!(validate_extension_prefix("/_a/c", &taken).is_ok()); + assert!(validate_extension_prefix("/_a/bc", &taken).is_ok()); +} + +#[test] +fn a_prefix_with_a_trailing_slash_empty_segment_parameter_or_wildcard_is_refused() { + for prefix in [ + "/_x/", "/_x//y", "/{id}", "/_x/{id}", "/{*rest}", "/_x/*", "/_x?y", "/_x#y", "/_x y", + "/_x\ty", + ] { + assert!( + matches!( + validate_extension_prefix(prefix, &[]), + Err(ExtensionMountError::BadShape(p)) if p == prefix + ), + "{prefix} must be refused as a bad shape" + ); + } + assert!(validate_extension_prefix("/_x/y-z_1.v2", &[]).is_ok()); + assert!(validate_extension_prefix("/_x/a:b", &[]).is_ok()); + assert!(validate_extension_prefix("/_x/%41", &[]).is_ok()); +} + +#[test] +fn validate_extension_prefixes_checks_the_list_as_the_mount_would() { + let http = vec![ + ("/_a".to_owned(), probe_router()), + ("/_a/b".to_owned(), probe_router()), + ]; + let err = validate_extension_prefixes(&http).expect_err("the second prefix is under the first"); + assert!(err.to_string().contains("/_a/b")); + assert!(err.to_string().contains("'/_a'")); + assert!(validate_extension_prefixes(&[]).is_ok()); + assert!( + validate_extension_prefixes(&[ + ("/_a".to_owned(), probe_router()), + ("/_b".to_owned(), probe_router()) + ]) + .is_ok() + ); +} + +#[test] +fn the_builders_fill_the_fields() { + #[derive(Default)] + struct Nop; + impl super::RequestObserver for Nop { + fn on_response(&self, _: super::RequestRecord) {} + } + let ext = Extensions::default() + .with_router("/_a", probe_router()) + .with_router("/_b", probe_router()) + .with_request_observer(std::sync::Arc::new(Nop)); + assert_eq!(ext.http.len(), 2); + assert_eq!(ext.http[0].0, "/_a"); + assert_eq!(ext.http[1].0, "/_b"); + assert!(ext.request_observer.is_some()); +} diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 1c26bd3f7..82e791210 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -76,6 +76,13 @@ pub(crate) async fn handle_request( } }; + // A thin binary's observer receives one record per request that reached + // authentication. The body hash is taken from the raw bytes before they + // are parsed, and only when an observer is installed; with none, nothing + // below allocates for a record. + let observing = state.request_observer.is_some(); + let record_body_hash = observing.then(|| crate::extensions::body_hash(body.as_ref())); + // Extract operation from X-Amz-Target let operation = match extract_operation(&headers) { Ok(op) => op, @@ -101,18 +108,32 @@ pub(crate) async fn handle_request( // the request makes and to the engine's error mappers, so a fault log line // can name the x-amzn-RequestId the client received. The early returns // above touch no storage and the response building below runs outside it. - let Served { - account_id, - table_name, - metric_table, - partition_value, - batch_entries, - dispatch_result, - auth_us, - authz_us, - throttle_us, - dispatch_us, - } = match extenddb_storage::request_scope::with_scope( + // One record per observed request, built here once with everything known + // before authentication. The guard holds it: if the client goes away + // while the request is in flight, hyper drops this future and the guard's + // Drop reports the record with status 0. On the normal path the guard + // hands the record back, the exit completes it (account, status, error + // type, latency) and reports it once. + let mut abandon_guard = state + .request_observer + .as_ref() + .map(|observer| AbandonGuard { + observer: Arc::clone(observer), + record: Some(crate::extensions::RequestRecord { + request_id: request_id.clone(), + operation: operation.clone(), + table_name: extract_table_name(request.body()), + account_id: None, + status: 0, + error_type: None, + latency_us: 0, + body_hash: record_body_hash.unwrap_or_default(), + sdk_invocation_id: header_string(&headers, "amz-sdk-invocation-id"), + sdk_request: header_string(&headers, "amz-sdk-request"), + }), + started: handler_start, + }); + let served = extenddb_storage::request_scope::with_scope( request_scope_for(&request_id, &operation, &headers), serve_request( &state, @@ -124,15 +145,45 @@ pub(crate) async fn handle_request( request, ), ) - .await - { + .await; + let mut record = abandon_guard.as_mut().and_then(AbandonGuard::disarm); + let Served { + account_id, + table_name, + metric_table, + partition_value, + batch_entries, + dispatch_result, + auth_us, + authz_us, + throttle_us, + dispatch_us, + } = match served { Ok(served) => served, - Err(e) => return error_response(&e, &request_id), + Err(refused) => { + // A refusal before dispatch (authentication, the point-in-time + // recovery refusal, authorization or the throttle) is observed + // too: the operation and table are known and the error names the + // cause, and a throttle report that could not see throttled + // requests would be wrong about retries. + let response = error_response(&refused.error, &request_id); + if let (Some(observer), Some(mut record)) = + (state.request_observer.as_ref(), record.take()) + { + record.account_id = refused.account_id; + record.status = response.status().as_u16(); + record.error_type = Some(refused.error.error_type().to_owned()); + record.latency_us = elapsed_us(handler_start); + observer.on_response(record); + } + return response; + } }; // --- Response segment --- let response_start = std::time::Instant::now(); let mut succeeded = false; + let mut record_error_type = None; let response = match dispatch_result { Ok(result) => { update_throttle_buckets( @@ -223,6 +274,9 @@ pub(crate) async fn handle_request( { record_partial_batch_throttle(&state.metrics, &account_id, &operation, entries); } + if observing { + record_error_type = Some(e.error_type().to_owned()); + } error_response(&e, &request_id) } }; @@ -268,9 +322,64 @@ pub(crate) async fn handle_request( "request complete" ); + // The observed exit for every request that reached dispatch. + if let (Some(observer), Some(mut record)) = (state.request_observer.as_ref(), record.take()) { + record.account_id = Some(account_id.to_string()); + record.status = response.status().as_u16(); + record.error_type = record_error_type; + record.latency_us = elapsed_us(handler_start); + observer.on_response(record); + } + response } +/// Microseconds since `start`, saturating. +fn elapsed_us(start: std::time::Instant) -> u64 { + u64::try_from(start.elapsed().as_micros()).unwrap_or(u64::MAX) +} + +/// Holds the one record of an observed request while `serve_request` runs. +/// If the handler future is dropped before its normal exit (the client went +/// away while the request was in flight), `Drop` reports the record with +/// status 0, so a record of attempts includes the request the client gave up +/// on. On the normal path `disarm` hands the record back for the exit to +/// complete and report. A handler that panics drops the guard during +/// unwinding; the observer is not called then, since a panic in the observer +/// at that point would abort the process. +struct AbandonGuard { + observer: Arc, + record: Option, + started: std::time::Instant, +} + +impl AbandonGuard { + fn disarm(&mut self) -> Option { + self.record.take() + } +} + +impl Drop for AbandonGuard { + fn drop(&mut self) { + if std::thread::panicking() { + return; + } + if let Some(mut record) = self.record.take() { + record.latency_us = elapsed_us(self.started); + self.observer.on_response(record); + } + } +} + +/// A refusal before dispatch, with the account authentication had produced +/// when it had. The table name is on the record already, from the parsed +/// body; there is no `From` for the bare error, so every refusal site states +/// the account. +struct Refused { + error: DynamoDbError, + account_id: Option, +} + /// What the request produced between authentication and the end of dispatch: /// the dispatch result and what the response segment needs to account for it. struct Served { @@ -290,9 +399,10 @@ struct Served { /// Authenticate, authorize, throttle and dispatch one request. Every storage /// read the request makes happens here, so `handle_request` runs this whole -/// future inside the request scope. A refusal before dispatch returns `Err`; -/// a dispatch error is inside `Served::dispatch_result`, because the response -/// segment accounts for it differently. +/// future inside the request scope. A refusal before dispatch returns `Err` +/// with the account the refusal had resolved; a dispatch error is inside +/// `Served::dispatch_result`, because the response segment accounts for it +/// differently. #[allow(clippy::too_many_lines)] // sequential request pipeline async fn serve_request( state: &Arc, @@ -302,10 +412,17 @@ async fn serve_request( request_id: &str, operation: &str, request: extenddb_engine::ParsedRequest<'_>, -) -> Result { +) -> Result { // --- Auth segment --- let auth_start = std::time::Instant::now(); - let identity = state.auth.authenticate(headers, body).await?; + let identity = state + .auth + .authenticate(headers, body) + .await + .map_err(|error| Refused { + error, + account_id: None, + })?; #[allow(clippy::cast_precision_loss)] let auth_us = auth_start.elapsed().as_micros() as f64; @@ -331,7 +448,10 @@ async fn serve_request( ); record_error_metrics(&state.metrics, &e, &account_id, None, operation); state.metrics.record_request_count(&account_id, operation); - return Err(e); + return Err(Refused { + error: e, + account_id: Some(account_id.to_string()), + }); } }; @@ -342,9 +462,12 @@ async fn serve_request( { if state.catalog_store.is_none() { tracing::error!("Authorization required but catalog_store is not configured"); - return Err(DynamoDbError::AccessDeniedException( - "User: is not authorized to perform this operation".to_owned(), - )); + return Err(Refused { + error: DynamoDbError::AccessDeniedException( + "User: is not authorized to perform this operation".to_owned(), + ), + account_id: Some(account_id.to_string()), + }); } // aws:SourceIp is the connection peer address; aws:UserAgent is the // User-Agent header. Behind a proxy only the peer address is trusted, @@ -363,7 +486,11 @@ async fn serve_request( Some(source_ip.as_str()), user_agent.as_deref(), ) - .await?; + .await + .map_err(|error| Refused { + error, + account_id: Some(account_id.to_string()), + })?; // The engine authorizes each PartiQL statement through it. item_authorizer = crate::item_authz::for_request(state, identity, &account_id, source_ip, user_agent); @@ -468,7 +595,10 @@ async fn serve_request( // billing mode. let table_arn = extenddb_storage::util::table_arn(&state.region, &ctx.account_id, &name); - return Err(throttle_error(cause, throttled_read, &table_arn)); + return Err(Refused { + error: throttle_error(cause, throttled_read, &table_arn), + account_id: Some(ctx.account_id.to_string()), + }); } } #[allow(clippy::cast_precision_loss)] @@ -557,7 +687,11 @@ fn header_string(headers: &HeaderMap, name: &str) -> Option { .map(str::to_owned) } +#[cfg(test)] +mod observer_tests; #[cfg(test)] mod request_scope_tests; #[cfg(test)] +mod start_server_tests; +#[cfg(test)] mod throttle_wire_tests; diff --git a/crates/server/src/handler/observer_tests.rs b/crates/server/src/handler/observer_tests.rs new file mode 100644 index 000000000..38f627ff6 --- /dev/null +++ b/crates/server/src/handler/observer_tests.rs @@ -0,0 +1,303 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The request observer, driven through `handle_request` against an in-memory +//! engine: one record per request that reached authentication, with the +//! status and error type the client received, the request id the response +//! carried, the table and account, the body hash and the SDK headers; a +//! refusal before dispatch (authentication, the throttle) is recorded with its +//! error type; a request the client abandons mid-flight is recorded with +//! status 0; a request refused before authentication is not recorded; without +//! an observer the handler builds no record. + +use std::sync::{Arc, Mutex}; + +use axum::body::Bytes; +use axum::extract::State; +use axum::http::HeaderMap; +use extenddb_auth::{AuthIdentity, AuthProvider}; +use extenddb_core::error::DynamoDbError; +use serde_json::{Value, json}; + +use super::throttle_wire_tests::{build_state_with, create_table}; +use crate::AppState; +use crate::extensions::{RequestObserver, RequestRecord, body_hash}; + +#[derive(Default)] +struct Recording(Mutex>); + +impl RequestObserver for Recording { + fn on_response(&self, record: RequestRecord) { + self.0.lock().unwrap().push(record); + } +} + +impl Recording { + fn records(&self) -> Vec { + self.0.lock().unwrap().clone() + } +} + +/// The fixture's stub, with a switch to refuse. +struct SwitchAuth { + account_id: String, + refuse: bool, +} + +#[async_trait::async_trait] +impl AuthProvider for SwitchAuth { + async fn authenticate( + &self, + _headers: &HeaderMap, + _body: &[u8], + ) -> Result { + if self.refuse { + return Err(DynamoDbError::UnrecognizedClientException( + "The security token included in the request is invalid.".to_owned(), + )); + } + Ok(AuthIdentity::User { + account_id: self.account_id.clone(), + user_name: "dev".to_owned(), + }) + } +} + +/// A state with the recording observer installed. +async fn observed_state(refuse_auth: bool) -> (Arc, String, Arc) { + let observer = Arc::new(Recording::default()); + let installed: Arc = Arc::clone(&observer) as Arc; + let (state, account_id) = build_state_with( + None, + move |account_id| { + Arc::new(SwitchAuth { + account_id, + refuse: refuse_auth, + }) + }, + Some(installed), + ) + .await; + (state, account_id, observer) +} + +const INVOCATION_ID: &str = "11111111-2222-3333-4444-555555555555"; + +async fn fire(state: &Arc, operation: &str, body: &Value) -> (u16, String) { + let mut headers = HeaderMap::new(); + headers.insert( + "x-amz-target", + format!("DynamoDB_20120810.{operation}") + .parse() + .expect("target header"), + ); + headers.insert( + "amz-sdk-invocation-id", + INVOCATION_ID.parse().expect("header value"), + ); + headers.insert( + "amz-sdk-request", + "attempt=1; max=3".parse().expect("header value"), + ); + let response = super::handle_request( + State(state.clone()), + "/".parse().expect("uri"), + axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 40002))), + headers, + Ok(Bytes::from(body.to_string())), + ) + .await; + let status = response.status().as_u16(); + let request_id = response + .headers() + .get("x-amzn-requestid") + .and_then(|v| v.to_str().ok()) + .expect("response carries x-amzn-RequestId") + .to_owned(); + (status, request_id) +} + +#[tokio::test] +async fn a_served_request_is_recorded_once_with_the_response_it_got() { + let (state, account_id, observer) = observed_state(false).await; + let body = json!({}); + let (status, request_id) = fire(&state, "ListTables", &body).await; + assert_eq!(status, 200); + + let records = observer.records(); + assert_eq!(records.len(), 1); + let r = &records[0]; + assert_eq!(r.request_id, request_id); + assert_eq!(r.operation, "ListTables"); + assert_eq!(r.table_name, None); + assert_eq!(r.account_id.as_deref(), Some(account_id.as_str())); + assert_eq!(r.status, 200); + assert_eq!(r.error_type, None); + assert_eq!(r.body_hash, body_hash(body.to_string().as_bytes())); + assert_eq!(r.sdk_invocation_id.as_deref(), Some(INVOCATION_ID)); + assert_eq!(r.sdk_request.as_deref(), Some("attempt=1; max=3")); + assert!(r.latency_us > 0); +} + +#[tokio::test] +async fn a_dispatch_error_is_recorded_with_its_error_type_and_table() { + let (state, _, observer) = observed_state(false).await; + let (status, request_id) = fire(&state, "DescribeTable", &json!({"TableName": "absent"})).await; + assert_eq!(status, 400); + + let records = observer.records(); + assert_eq!(records.len(), 1); + assert_eq!(records[0].request_id, request_id); + assert_eq!(records[0].table_name.as_deref(), Some("absent")); + assert_eq!(records[0].status, 400); + assert_eq!( + records[0].error_type.as_deref(), + Some("ResourceNotFoundException") + ); +} + +#[tokio::test] +async fn a_throttle_refusal_is_recorded_with_its_error_type() { + let (state, account_id, observer) = observed_state(false).await; + let table = "observed-throttle"; + create_table( + &state, + table, + json!({"ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}}), + ) + .await; + let before = observer.records().len(); + state.throttle.consume(&account_id, table, 0.0, 2.0); + + let (status, request_id) = fire( + &state, + "PutItem", + &json!({"TableName": table, "Item": {"pk": {"S": "1"}}}), + ) + .await; + assert_eq!(status, 400); + + let records = observer.records(); + assert_eq!( + records.len(), + before + 1, + "one record for the refused request" + ); + let r = records.last().expect("record"); + assert_eq!(r.request_id, request_id); + assert_eq!(r.operation, "PutItem"); + assert_eq!(r.table_name.as_deref(), Some(table)); + assert_eq!(r.account_id.as_deref(), Some(account_id.as_str())); + assert_eq!(r.status, 400); + assert_eq!( + r.error_type.as_deref(), + Some("ProvisionedThroughputExceededException") + ); +} + +#[tokio::test] +async fn an_authentication_refusal_is_recorded_with_the_table_and_no_account() { + let (state, _, observer) = observed_state(true).await; + let (status, request_id) = fire( + &state, + "PutItem", + &json!({"TableName": "t1", "Item": {"pk": {"S": "1"}}}), + ) + .await; + assert_eq!(status, 400); + + let records = observer.records(); + assert_eq!(records.len(), 1); + assert_eq!(records[0].request_id, request_id); + assert_eq!(records[0].operation, "PutItem"); + assert_eq!(records[0].table_name.as_deref(), Some("t1")); + assert_eq!(records[0].account_id, None); + assert_eq!( + records[0].error_type.as_deref(), + Some("UnrecognizedClientException") + ); +} + +#[tokio::test] +async fn a_request_refused_before_authentication_is_not_recorded() { + let (state, _, observer) = observed_state(false).await; + let (status, _) = fire(&state, "NoSuchOperation", &json!({})).await; + assert_eq!(status, 400); + assert!( + observer.records().is_empty(), + "unknown operation left no record" + ); + + let mut headers = HeaderMap::new(); + headers.insert( + "x-amz-target", + "DynamoDB_20120810.ListTables" + .parse() + .expect("target header"), + ); + let response = super::handle_request( + State(state.clone()), + "/".parse().expect("uri"), + axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 40002))), + headers, + Ok(Bytes::from("{not json")), + ) + .await; + assert_eq!(response.status().as_u16(), 400); + assert!( + observer.records().is_empty(), + "a body that is not JSON left no record" + ); +} + +#[tokio::test] +async fn an_abandoned_request_is_recorded_with_status_zero() { + let (state, _, observer) = observed_state(false).await; + let mut headers = HeaderMap::new(); + headers.insert( + "x-amz-target", + "DynamoDB_20120810.ListTables" + .parse() + .expect("target header"), + ); + let fut = super::handle_request( + State(state.clone()), + "/".parse().expect("uri"), + axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 40002))), + headers, + Ok(Bytes::from("{}")), + ); + // Poll once so the handler passes the pre-auth checks and arms the guard, + // then drop the future as hyper does when the client disconnects. + let mut fut = Box::pin(fut); + let waker = std::task::Waker::noop(); + let mut cx = std::task::Context::from_waker(waker); + let polled = fut.as_mut().poll(&mut cx); + assert!( + polled.is_pending(), + "the in-memory engine yields at least once before answering, so the request is in flight after one poll" + ); + drop(fut); + + let records = observer.records(); + assert_eq!(records.len(), 1, "the abandoned request was recorded once"); + assert_eq!(records[0].status, 0); + assert_eq!(records[0].operation, "ListTables"); + assert_eq!(records[0].error_type, None); +} + +#[tokio::test] +async fn without_an_observer_the_request_is_served_as_before() { + let (state, _) = build_state_with( + None, + |account_id| { + Arc::new(SwitchAuth { + account_id, + refuse: false, + }) + }, + None, + ) + .await; + let (status, _) = fire(&state, "ListTables", &json!({})).await; + assert_eq!(status, 200); +} diff --git a/crates/server/src/handler/request_scope_tests.rs b/crates/server/src/handler/request_scope_tests.rs index 44464e438..ed8b417e0 100644 --- a/crates/server/src/handler/request_scope_tests.rs +++ b/crates/server/src/handler/request_scope_tests.rs @@ -146,12 +146,16 @@ async fn no_scope_on_the_task_before_the_request_or_after_the_response() { async fn the_scope_is_current_when_the_auth_provider_runs() { let seen = Arc::new(Mutex::new(Vec::new())); let recorded = Arc::clone(&seen); - let (state, _) = build_state_with(None, move |account_id| { - Arc::new(ScopeAtAuth { - account_id, - seen: recorded, - }) - }) + let (state, _) = build_state_with( + None, + move |account_id| { + Arc::new(ScopeAtAuth { + account_id, + seen: recorded, + }) + }, + None, + ) .await; let (status, request_id) = fire( diff --git a/crates/server/src/handler/start_server_tests.rs b/crates/server/src/handler/start_server_tests.rs new file mode 100644 index 000000000..57b6c6dc8 --- /dev/null +++ b/crates/server/src/handler/start_server_tests.rs @@ -0,0 +1,304 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! `start_server` driven over a loopback socket: an extension router is +//! mounted behind the security layer by the server's own wiring, the built-in +//! routes answer the same with an extension mounted, the extension body limit +//! is axum's default, and a request the client abandons mid-flight reaches the +//! observer once with status 0. + +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; + +use axum::Router; +use axum::body::Bytes; +use axum::http::HeaderMap; +use axum::routing::{get, post}; +use extenddb_auth::{AuthIdentity, AuthProvider}; +use extenddb_core::error::DynamoDbError; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +use super::throttle_wire_tests::build_state_with; +use crate::extensions::{RequestObserver, RequestRecord}; + +#[derive(Default)] +struct Recording(Mutex>); + +impl RequestObserver for Recording { + fn on_response(&self, record: RequestRecord) { + self.0.lock().unwrap().push(record); + } +} + +/// The fixture's stub with an optional delay, so a client can go away while +/// the request is inside authentication. +struct SlowAuth { + account_id: String, + delay_ms: u64, +} + +#[async_trait::async_trait] +impl AuthProvider for SlowAuth { + async fn authenticate( + &self, + _headers: &HeaderMap, + _body: &[u8], + ) -> Result { + if self.delay_ms > 0 { + tokio::time::sleep(std::time::Duration::from_millis(self.delay_ms)).await; + } + Ok(AuthIdentity::User { + account_id: self.account_id.clone(), + user_name: "dev".to_owned(), + }) + } +} + +struct Reply { + status: u16, + headers: Vec<(String, String)>, + body: String, +} + +impl Reply { + fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v.as_str()) + } +} + +/// One HTTP/1.1 exchange over a fresh connection with `Connection: close`. +async fn raw(addr: SocketAddr, request: &[u8]) -> Reply { + let mut s = TcpStream::connect(addr).await.expect("connect"); + s.write_all(request).await.expect("write"); + let mut buf = Vec::new(); + s.read_to_end(&mut buf).await.expect("read"); + let text = String::from_utf8_lossy(&buf).into_owned(); + let (head, body) = text.split_once("\r\n\r\n").expect("head and body"); + let mut lines = head.lines(); + let status: u16 = lines + .next() + .expect("status line") + .split_whitespace() + .nth(1) + .expect("status") + .parse() + .expect("status number"); + let mut headers: Vec<(String, String)> = lines + .filter_map(|l| l.split_once(':')) + .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_owned())) + .collect(); + headers.sort(); + let chunked = headers + .iter() + .any(|(k, v)| k == "transfer-encoding" && v == "chunked"); + let body = if chunked { + let mut out = String::new(); + let mut rest = body; + loop { + let (size, after) = rest.split_once("\r\n").expect("chunk size"); + let n = usize::from_str_radix(size.trim(), 16).expect("hex"); + if n == 0 { + break; + } + out.push_str(&after[..n]); + rest = &after[n + 2..]; + } + out + } else { + body.to_owned() + }; + Reply { + status, + headers, + body, + } +} + +fn get_req(path: &str) -> Vec { + format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n").into_bytes() +} + +fn post_req(path: &str, extra: &str, body: &[u8]) -> Vec { + let mut v = format!( + "POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n{extra}Content-Length: {}\r\n\r\n", + body.len() + ) + .into_bytes(); + v.extend_from_slice(body); + v +} + +/// Bind `127.0.0.1:0`, build the fixture state and spawn `start_server` with +/// the given extension routers. `start_server` runs until a signal, so the +/// caller aborts the returned task. +async fn serve( + extensions: Vec<(String, Router)>, + observer: Option>, + auth_delay_ms: u64, +) -> (SocketAddr, tokio::task::JoinHandle<()>) { + let installed = observer.map(|o| o as Arc); + let (state, _) = build_state_with( + None, + move |account_id| { + Arc::new(SlowAuth { + account_id, + delay_ms: auth_delay_ms, + }) + }, + installed, + ) + .await; + let state = Arc::try_unwrap(state) + .ok() + .expect("the fixture holds the only reference"); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("addr"); + let task = tokio::spawn(async move { + crate::start_server(listener, state, None, None, extensions) + .await + .expect("start_server"); + }); + for _ in 0..50 { + if TcpStream::connect(addr).await.is_ok() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + (addr, task) +} + +fn probe_router() -> Router { + Router::new().route("/", get(|| async { "probe" })).route( + "/echo", + post(|body: Bytes| async move { body.len().to_string() }), + ) +} + +const SECURITY: [(&str, &str); 3] = [ + ("x-content-type-options", "nosniff"), + ("x-frame-options", "DENY"), + ("referrer-policy", "strict-origin-when-cross-origin"), +]; + +#[tokio::test] +async fn start_server_mounts_extensions_behind_the_security_layer() { + let (addr, task) = serve(vec![("/_probe".to_owned(), probe_router())], None, 0).await; + + let probe = raw(addr, &get_req("/_probe")).await; + assert_eq!(probe.status, 200, "{}", probe.body); + assert_eq!(probe.body, "probe"); + for (name, value) in SECURITY { + assert_eq!( + probe.header(name), + Some(value), + "extension response carries {name}" + ); + } + + let health = raw(addr, &get_req("/health")).await; + assert_eq!(health.status, 200); + assert!(health.body.contains("healthy"), "{}", health.body); + for (name, value) in SECURITY { + assert_eq!(health.header(name), Some(value)); + } + + // Body limits: an extension route is bounded by axum's default (2 MB); + // the request handler at `/` by the 16 MB DynamoDB limit. + let three_mb = vec![b'a'; 3 * 1024 * 1024]; + let echo = raw(addr, &post_req("/_probe/echo", "", &three_mb)).await; + assert_eq!(echo.status, 413, "{}", echo.body); + let root = raw(addr, &post_req("/", "", &three_mb)).await; + assert_eq!(root.status, 400, "{}", root.body); + assert!( + root.body.contains("MissingAuthenticationToken"), + "{}", + root.body + ); + let small = raw(addr, &post_req("/_probe/echo", "", b"hello")).await; + assert_eq!(small.status, 200); + assert_eq!(small.body, "5"); + // The layers in front of every route cover an extension route too: + // `post_req` sends one `Host` header, so this request carries two. + let dup = raw(addr, &post_req("/_probe/echo", "Host: other\r\n", b"x")).await; + assert_eq!(dup.status, 400, "{}", dup.body); + + task.abort(); +} + +/// Status, headers and body with the volatile parts normalised: request id, +/// crc32, `date`, cookie values and the listen address in the console footer. +fn normalised(reply: &Reply, addr: SocketAddr) -> String { + let mut h: Vec = reply + .headers + .iter() + .map(|(k, v)| match k.as_str() { + "x-amzn-requestid" => format!("{k}: RID"), + "x-amz-crc32" => format!("{k}: CRC"), + "date" => format!("{k}: DATE"), + "set-cookie" => format!("{k}: {}", v.split('=').next().unwrap_or("")), + _ => format!("{k}: {v}"), + }) + .collect(); + h.sort(); + let mut body = reply.body.replace(&addr.to_string(), "ADDR"); + if let Some(rid) = reply.header("x-amzn-requestid") { + body = body.replace(rid, "RID"); + } + format!("status={}\n{}\nbody={body}\n", reply.status, h.join("\n")) +} + +#[tokio::test] +async fn built_in_routes_answer_the_same_with_an_extension_mounted() { + let (plain_addr, plain) = serve(Vec::new(), None, 0).await; + let (ext_addr, ext) = serve(vec![("/_x".to_owned(), probe_router())], None, 0).await; + + let list = post_req("/", "X-Amz-Target: DynamoDB_20120810.ListTables\r\n", b"{}"); + let requests: Vec<(&str, Vec)> = vec![ + ("GET /console/", get_req("/console/")), + ("GET /console", get_req("/console")), + ("GET /console/login", get_req("/console/login")), + ("GET /console/nope", get_req("/console/nope")), + ("GET /management/accounts", get_req("/management/accounts")), + ("GET /management", get_req("/management")), + ("GET /health", get_req("/health")), + ("GET /metrics", get_req("/metrics")), + ("GET /nope", get_req("/nope")), + ("GET /", get_req("/")), + ("POST / ListTables", list), + ]; + for (name, req) in &requests { + let a = normalised(&raw(plain_addr, req).await, plain_addr); + let b = normalised(&raw(ext_addr, req).await, ext_addr); + assert_eq!(a, b, "{name} differs with an extension mounted"); + } + assert_eq!(raw(plain_addr, &get_req("/_x")).await.status, 404); + assert_eq!(raw(ext_addr, &get_req("/_x")).await.status, 200); + + plain.abort(); + ext.abort(); +} + +#[tokio::test] +async fn a_client_that_goes_away_mid_request_is_recorded_once_with_status_zero() { + let observer = Arc::new(Recording::default()); + let (addr, task) = serve(Vec::new(), Some(observer.clone()), 400).await; + + let list = post_req("/", "X-Amz-Target: DynamoDB_20120810.ListTables\r\n", b"{}"); + let mut s = TcpStream::connect(addr).await.expect("connect"); + s.write_all(&list).await.expect("write"); + // hyper has read the request and the handler is inside authentication. + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + drop(s); + tokio::time::sleep(std::time::Duration::from_millis(1200)).await; + + let records = observer.0.lock().unwrap().clone(); + assert_eq!(records.len(), 1, "{records:?}"); + assert_eq!(records[0].status, 0); + assert_eq!(records[0].operation, "ListTables"); + assert_eq!(records[0].account_id, None); + + task.abort(); +} diff --git a/crates/server/src/handler/throttle_wire_tests.rs b/crates/server/src/handler/throttle_wire_tests.rs index 737998054..3f7d84b0d 100644 --- a/crates/server/src/handler/throttle_wire_tests.rs +++ b/crates/server/src/handler/throttle_wire_tests.rs @@ -57,7 +57,7 @@ fn cache_cfg(name: &'static str) -> extenddb_cache::SwrCacheConfig { /// `dev_mode` on. Returns the state and the account id the stub answers with, /// so the expected ARN can be formed. pub(super) async fn build_state() -> (Arc, String) { - build_state_with(None, stub_auth).await + build_state_with(None, stub_auth, None).await } /// The stub auth provider bound to `account_id`: `build_state`'s provider, @@ -68,11 +68,13 @@ pub(super) fn stub_auth(account_id: String) -> Arc { /// `build_state` with `storage`, when given, in place of the SQLite engine /// for the table and item calls (the catalog and the authorization stores -/// stay on SQLite), and with the auth provider built by `auth` from the -/// bootstrapped default account id, for a test that needs its own provider. +/// stay on SQLite), with the auth provider built by `auth` from the +/// bootstrapped default account id, and with an optional request observer, +/// for a test that needs its own provider or observer. pub(super) async fn build_state_with( storage: Option>, auth: impl FnOnce(String) -> Arc, + request_observer: Option>, ) -> (Arc, String) { let _ = extenddb_storage::set_backend(extenddb_storage_sqlite::backend()); let config = extenddb_storage_sqlite::SqliteConfig { @@ -137,6 +139,7 @@ pub(super) async fn build_state_with( table_key_info_cache, config_entries: Vec::new(), docs_store: None, + request_observer, admission: crate::registration::Admission::default(), }); (state, account_id) @@ -169,7 +172,7 @@ pub(super) async fn call(state: &Arc, operation: &str, body: Value) -> /// Create `table` with the given billing fields and wait for ACTIVE. No /// worker runs in this test, so the CREATING to ACTIVE transition is driven /// here. -async fn create_table(state: &Arc, table: &str, billing: Value) { +pub(super) async fn create_table(state: &Arc, table: &str, billing: Value) { let mut create = json!({ "TableName": table, "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], @@ -539,7 +542,7 @@ async fn a_batch_a_backend_throttled_records_the_throttle_metrics() { let store = failing_store::FailingStore::throttling() .with_items(&["k1", "k2", "k3"]) .failing_on(&["k2", "k3"]); - let (state, account_id) = build_state_with(Some(Arc::new(store)), stub_auth).await; + let (state, account_id) = build_state_with(Some(Arc::new(store)), stub_auth, None).await; let (got, body) = call(&state, operation, request).await; assert_eq!(got, status, "{operation}: {body}"); for (metric, want) in [ diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index c80ccde4c..514cb0534 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -15,6 +15,7 @@ pub(crate) mod authz_resource; pub mod backup_store; pub mod console; pub mod dev_credentials; +pub mod extensions; mod handler; mod import_export_paths; mod import_export_roots; @@ -37,6 +38,11 @@ mod table_name_gate; mod throttle_helpers; mod workers; +/// The `axum` this server is built with, for a thin binary's extension routers. +pub use axum; +pub use extensions::{ + ExtensionMountError, Extensions, RequestObserver, RequestRecord, validate_extension_prefixes, +}; pub use serve::{ BuildInfo, CatalogRefusal, JOB_DRAIN_TIMEOUT, LogTarget, RegistrationLost, ServeParams, WORKER_STOP_TIMEOUT, catalog_refusal, log_to_syslog_raw, serve, @@ -112,12 +118,37 @@ pub struct AppState { pub config_entries: Vec<(String, String)>, /// Runtime documentation store. `None` if `docs_dir` is not configured. pub docs_store: Option, + /// Called once per request after the response is built, when a thin + /// binary installed one through [`Extensions::request_observer`]. `None` + /// leaves the request path as it was and builds no record. + pub request_observer: Option>, /// Whether new requests are admitted, and whether the server must stop: /// set while the backend's serving registration is lost /// ([`registration`]). pub(crate) admission: registration::Admission, } +/// The response security headers over the whole app: `X-Content-Type-Options`, +/// `X-Frame-Options` and `Referrer-Policy`. HSTS is added in [`start_server`] +/// when TLS is on. A function of its own so the extension mount tests apply +/// the layer the server applies. +fn apply_security_headers(app: Router) -> Router { + let security_layers = ServiceBuilder::new() + .layer(SetResponseHeaderLayer::overriding( + axum::http::header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + )) + .layer(SetResponseHeaderLayer::overriding( + axum::http::header::X_FRAME_OPTIONS, + HeaderValue::from_static("DENY"), + )) + .layer(SetResponseHeaderLayer::overriding( + axum::http::header::REFERRER_POLICY, + HeaderValue::from_static("strict-origin-when-cross-origin"), + )); + app.layer(security_layers) +} + /// TLS configuration passed from the binary crate. pub struct ServerTlsConfig { /// Path to the PEM certificate file. @@ -142,6 +173,13 @@ pub const CONNECTION_DRAIN_TIMEOUT: Duration = Duration::from_secs(5); /// When `tls` is `Some`, the server serves HTTPS using `axum-server` with rustls. /// When `tls` is `None`, the server serves plaintext HTTP. /// +/// `extension_routers` are a thin binary's HTTP routers (see +/// [`Extensions::http`]). Each is mounted after the built-in routes and before +/// the response security layer, so an extension response carries the security +/// headers too. A prefix that is not absolute, is `/`, or collides with a +/// built-in route or an earlier extension is an error and the server does not +/// start. +/// /// It stops on SIGINT or SIGTERM, or when `state`'s admission asks for a /// stop after the serving registration was lost; both drain the listener /// the same way and remove the PID file. @@ -150,6 +188,7 @@ pub async fn start_server( state: AppState, pid_file: Option, tls: Option, + extension_routers: Vec<(String, Router)>, ) -> Result<(), anyhow::Error> { // SP-WIRE-007: DynamoDB request body limit is 16 MB. const DYNAMODB_BODY_LIMIT: usize = 16 * 1024 * 1024; @@ -174,21 +213,6 @@ pub async fn start_server( let admission = state.admission.clone(); let shared = Arc::new(state); - // Security headers applied to all responses. - let security_layers = ServiceBuilder::new() - .layer(SetResponseHeaderLayer::overriding( - axum::http::header::X_CONTENT_TYPE_OPTIONS, - HeaderValue::from_static("nosniff"), - )) - .layer(SetResponseHeaderLayer::overriding( - axum::http::header::X_FRAME_OPTIONS, - HeaderValue::from_static("DENY"), - )) - .layer(SetResponseHeaderLayer::overriding( - axum::http::header::REFERRER_POLICY, - HeaderValue::from_static("strict-origin-when-cross-origin"), - )); - let mut app = Router::new() .route("/", post(handler::handle_request)) .layer(DefaultBodyLimit::max(DYNAMODB_BODY_LIMIT)) @@ -239,6 +263,12 @@ pub async fn start_server( ); } + // Thin-bin extension routers go after the built-in nests and before the + // security layer, so their responses carry the security headers too. A + // refused prefix is a startup error. + let app = + extensions::mount_extensions(app, extension_routers).map_err(|e| anyhow::anyhow!("{e}"))?; + // While the serving registration is lost, every route answers // ServiceUnavailable before its handler runs. let app = app.layer(axum::middleware::from_fn_with_state( @@ -247,16 +277,15 @@ pub async fn start_server( )); // Refuse a repeated host or authorization header on every route, then - // apply security headers to all routes (the refusal carries them too). - // A body that stops delivering data for `request_timeout` errors out, so a - // client that announces a Content-Length it never sends cannot hold the - // connection open. The handler answers that error with 408. - let app = app - .layer(axum::middleware::from_fn( - repeated_headers::refuse_repeated_headers, - )) - .layer(security_layers) - .layer(RequestBodyTimeoutLayer::new(request_timeout)); + // apply security headers to all routes, built-in and extension (the + // refusal carries them too). A body that stops delivering data for + // `request_timeout` errors out, so a client that announces a + // Content-Length it never sends cannot hold the connection open. The + // handler answers that error with 408. + let app = app.layer(axum::middleware::from_fn( + repeated_headers::refuse_repeated_headers, + )); + let app = apply_security_headers(app).layer(RequestBodyTimeoutLayer::new(request_timeout)); // Add HSTS header only when TLS is enabled. let app = if tls_enabled { diff --git a/crates/server/src/serve.rs b/crates/server/src/serve.rs index 788593630..e3d3c42cb 100644 --- a/crates/server/src/serve.rs +++ b/crates/server/src/serve.rs @@ -112,6 +112,10 @@ pub struct ServeParams { /// Only a `dev-mode` build of the app crate ever sets this, and it enforces /// the loopback-only bind before handing over the listener. pub dev_mode: bool, + /// A thin binary's extension points: HTTP routers to mount and an optional + /// per-request observer. The empty default leaves the server as it is + /// without them. + pub extensions: crate::Extensions, /// The config file `serve` was started with, named in the command a /// catalog refusal prints. `None` when it started from built-in defaults. pub config_path: Option, @@ -133,10 +137,19 @@ impl ServeParams { log_target: LogTarget::Syslog, build, dev_mode: false, + extensions: crate::Extensions::default(), config_path: None, } } + /// Install a thin binary's [`Extensions`](crate::Extensions): HTTP routers + /// to mount and an optional per-request observer. + #[must_use] + pub fn with_extensions(mut self, extensions: crate::Extensions) -> Self { + self.extensions = extensions; + self + } + /// Send log output to `target` instead of the syslog default. #[must_use] pub fn with_log_target(mut self, target: LogTarget) -> Self { @@ -318,8 +331,15 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { log_target, build, dev_mode, + extensions, config_path, } = params; + // The observer goes into AppState for the handler; the routers go to + // start_server, which mounts them. + let crate::Extensions { + http: extension_http, + request_observer, + } = extensions; let catalog_version = extenddb_storage::migrations::binary_catalog_label(); // Write the PID file, when the caller asked for one, so `extenddb status`, @@ -807,6 +827,7 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { table_key_info_cache, config_entries, docs_store, + request_observer, admission: admission.clone(), }; @@ -935,7 +956,8 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { None }; - let server_result = crate::start_server(listener, state, pid_file, tls_config).await; + let server_result = + crate::start_server(listener, state, pid_file, tls_config, extension_http).await; // The HTTP server has stopped accepting. drain_then_release( diff --git a/docs/manuals/01-architecture-guide.md b/docs/manuals/01-architecture-guide.md index 29be47fd3..6d6b91c92 100755 --- a/docs/manuals/01-architecture-guide.md +++ b/docs/manuals/01-architecture-guide.md @@ -244,6 +244,10 @@ The server sets `extenddb_storage::request_scope::RequestScope` around each requ The engine's fault log lines carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received: `storage internal error` and `backup storage error`, the shared error mapper's lines for an unexpected already-exists error, an idempotency fault, a transient error, an expired snapshot and a connection error, the restore's line for a backup store read that fails, DeleteBackup's line for a catalog id that cannot be read and the BatchWriteItem line for the requests a batch did not apply. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. +### Thin binary extensions + +A backend's `main` passes an `extenddb_app::Extensions` value to `extenddb_app::run_with`; `run` is the same call with the empty default. `Extensions::http` is a list of axum routers with absolute prefixes of literal segments; `start_server` nests each after the built-in routes and before the response security layer, so an extension response carries the same security headers. The layers in front of every route apply to it too: a `ServiceUnavailable` answer while the serving registration is lost, the refusal of a repeated `host` or `authorization` header, and the request body timeout. Nothing else of the server's applies (no authentication, no rate limit, axum's default body limit). A prefix that is `/`, is not absolute, ends with `/`, has an empty segment, a parameter or wildcard segment or a byte no request path carries, is at or under `/health`, `/metrics`, `/management` or `/console`, or is at, under or above an earlier prefix is a startup error, reported before the backend connects. `Extensions::request_observer` is an optional `RequestObserver`; the handler calls it once per request that reached authentication, after the response is built and outside the request scope, with a `RequestRecord` (request id, operation, table, account, status, error type, latency, a hash of the raw body, and the two SDK correlation headers). A request the client abandons in flight is reported with status 0. Without an observer the handler builds no record and hashes no body. + ## Security Architecture ### Authentication diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index f16d4dba2..77f461484 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -364,6 +364,8 @@ inventory::submit! { The `bin` crate will discover your backend at startup and select it by name from the configuration. +A thin binary that needs HTTP routes of its own (a status page, a control endpoint) or a hook on every request passes an `extenddb_app::Extensions` to `extenddb_app::run_with` in place of `run`. `Extensions::http` is a `Vec<(String, axum::Router)>`, built against the `axum` that `extenddb_app` re-exports; `Extensions::request_observer` is an `Option>`, and the trait has one method, `fn on_response(&self, record: RequestRecord)`, on a `Send + Sync` type. Routers mount under absolute prefixes of literal segments, outside `/health`, `/metrics`, `/management` and `/console`, and not at, under or above another extension's prefix; a refused prefix stops the server before it connects to the backend. Their responses carry the server's security headers, and the layers in front of every route apply to them: a `ServiceUnavailable` answer while the serving registration is lost, the refusal of a repeated `host` or `authorization` header, and the request body timeout. Nothing else of the server's applies to them: no authentication, no request rate limit, and axum's default 2 MB body limit for the limited extractors (none for a raw `Body`). A route that changes state or reads data authenticates in its own handler or layer. A `RequestObserver` receives one `RequestRecord` per request that reached authentication, after the response is built, on the request's task, with no lock held and no ordering across requests; keep `on_response` short or hand the record to a task of your own, since the response is written after it returns, and do not let it panic, since a panic there closes the connection. The record's `table_name` is the request's top-level `TableName`, so it is `None` for the batch, transaction, PartiQL and stream operations; its two SDK fields are client-supplied text. + ### Step 7: Test Use the test suite as your specification: diff --git a/docs/rfcs/0002-backend-plugin-policy.md b/docs/rfcs/0002-backend-plugin-policy.md index b83367269..45527257a 100644 --- a/docs/rfcs/0002-backend-plugin-policy.md +++ b/docs/rfcs/0002-backend-plugin-policy.md @@ -255,7 +255,7 @@ cargo build --no-default-features --bin extenddb ### Release model -ExtendDB will move to a release model that includes releases through Crates.io. All crates follow semantic versioning. Breaking changes to `extenddb-storage` trigger coordinated releases. Variants may be added to `StorageError` in a minor release; a backend crate that matches on it exhaustively must carry a catch-all arm. Fields may be added to `RequestScope` in a minor release; a backend crate constructs it through `RequestScope::new`, never a struct literal. Binaries will also be available as GitHub releases. The project will also prioritize releasing images through Docker Hub. +ExtendDB will move to a release model that includes releases through Crates.io. All crates follow semantic versioning. Breaking changes to `extenddb-storage` trigger coordinated releases. Variants may be added to `StorageError` in a minor release; a backend crate that matches on it exhaustively must carry a catch-all arm. Fields may be added to `RequestScope` in a minor release; a backend crate constructs it through `RequestScope::new`, never a struct literal. Fields may be added to `extenddb_app::Extensions` and `RequestRecord` in a minor release; a thin binary builds `Extensions` through `Extensions::default` and its `with_` methods and reads `RequestRecord` by field. Binaries will also be available as GitHub releases. The project will also prioritize releasing images through Docker Hub. ### Third-party backends outside ExtendDB organization