From 01e897576d8c5d7b1b3562c3330c6694e0895c56 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:32:48 +0000 Subject: [PATCH 01/10] feat(server): trusted-proxy sign-in behind a stock reverse proxy [trusted_proxy] gains username_header (default X-SQB-User), optional display_name_header and email_header, unknown_users (provision_viewer, the default, or reject) and proxy_logout_url; identities become optional pre-bindings. The origin may be plain HTTP, with a start-up warning. A newcomer gets a principal named by the canonical username, with an id derived from it, and the installation-wide viewer role; a username that already names another principal is refused rather than taken over. Requests from trusted peers may report the browser host in X-Forwarded-Host, as Apache's mod_proxy does without ProxyPreserveHost. Each untrusted peer that sends the username header is logged once, without header values. Change feeds send Cache-Control: no-cache, no-transform and X-Accel-Buffering: no. --- .../tests/native_commands/test_proxy.rs | 125 ++++++++- .../tests/native_commands/test_types.rs | 8 + .../src/api/_helpers/authentication/bearer.rs | 7 +- .../src/api/_helpers/authentication/mod.rs | 3 + .../api/_helpers/authentication/origins.rs | 39 +++ .../authentication/password_transport.rs | 45 +++- .../_helpers/authentication/proxy_settings.rs | 236 +++++++++++++++++ .../_helpers/authentication/proxy_warnings.rs | 33 +++ .../_helpers/authentication/trusted_proxy.rs | 114 +++++---- .../src/api/_helpers/resources/changes.rs | 19 +- .../_helpers/resources/person_bootstrap.rs | 17 +- .../src/api/constants.rs | 29 +++ .../src/api/main/parse_origin.rs | 24 +- .../sqlbuild-orchestration/src/api/models.rs | 57 ++++- .../src/authorization/_helpers/mod.rs | 1 + .../authorization/_helpers/proxy_people.rs | 64 +++++ .../src/authorization/main/bootstrap_user.rs | 3 +- .../src/authorization/main/mod.rs | 1 + .../main/resolve_proxy_person.rs | 43 ++++ .../src/authorization/models.rs | 10 + .../main/identities/create_principal.rs | 2 +- .../main/identities/insert_principal.rs | 4 +- .../tests/api/changes/helpers.rs | 6 +- .../tests/api/person_sessions/helpers.rs | 6 + .../tests/api/proxy_provisioning/helpers.rs | 66 +++++ .../tests/api/test_contracts.rs | 4 + .../tests/api/test_external_sessions.rs | 9 +- .../tests/api/test_proxy.rs | 6 + .../tests/api/test_proxy_provisioning.rs | 237 ++++++++++++++++++ .../tests/api/test_types.rs | 13 + fensu.toml | 6 + 31 files changed, 1135 insertions(+), 102 deletions(-) create mode 100644 crates/sqlbuild-orchestration/src/api/_helpers/authentication/origins.rs create mode 100644 crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs create mode 100644 crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs create mode 100644 crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs create mode 100644 crates/sqlbuild-orchestration/src/authorization/main/resolve_proxy_person.rs create mode 100644 crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs create mode 100644 crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs diff --git a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs index 9d33b2a1b9..2ecdd6fa8b 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs @@ -4,7 +4,7 @@ use reqwest::{Client, StatusCode, header}; use serde_json::{Value, json}; use crate::helpers::{api_ready, start_control_in, wait_for_exit}; -use crate::test_types::{ProxyCliTestCase, ServerConfigurationTestCase}; +use crate::test_types::{ProxyCliTestCase, ProxyStartupTestCase, ServerConfigurationTestCase}; #[test] fn given_an_owner_configured_proxy_when_requests_carry_a_subject_then_only_explicit_people_resolve_without_sessions_or_machine_authority() @@ -94,16 +94,46 @@ fn given_invalid_or_conflicting_server_configuration_when_a_standalone_server_st expected_error: "requires explicit trusted peer IP addresses", }, ServerConfigurationTestCase { - description: "non-HTTPS external origin", - configuration: "[trusted_proxy]\norigin = \"http://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\nidentities = {}\n", + description: "neither an HTTP nor an HTTPS external origin", + configuration: "[trusted_proxy]\norigin = \"ftp://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\n", arguments: &[], - expected_error: "trusted-proxy authentication requires an HTTPS origin", + expected_error: "trusted-proxy authentication requires an HTTP or HTTPS origin", + }, + ServerConfigurationTestCase { + description: "a username header a browser sets", + configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\nusername_header = \"Cookie\"\n", + arguments: &[], + expected_error: "[trusted_proxy] username_header cannot be cookie", + }, + ServerConfigurationTestCase { + description: "the display name in the username header", + configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\nusername_header = \"X-Example-User\"\ndisplay_name_header = \"x-example-user\"\n", + arguments: &[], + expected_error: "username_header, display_name_header and email_header must differ", + }, + ServerConfigurationTestCase { + description: "a script as the sign-out URL", + configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\nproxy_logout_url = \"javascript:alert(1)\"\n", + arguments: &[], + expected_error: "proxy_logout_url must be an http:// or https:// URL", + }, + ServerConfigurationTestCase { + description: "an unknown policy for unknown users", + configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\nunknown_users = \"provision_admin\"\n", + arguments: &[], + expected_error: "unknown variant `provision_admin`", + }, + ServerConfigurationTestCase { + description: "two bindings for one username", + configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\n\n[trusted_proxy.identities]\n\"Orders-Reader\" = \"00000000-0000-0000-0000-000000000001\"\n\"orders-reader\" = \"00000000-0000-0000-0000-000000000002\"\n", + arguments: &[], + expected_error: "binds 'orders-reader' more than once", }, ServerConfigurationTestCase { description: "subject cannot be represented by the header transport", configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\n\n[trusted_proxy.identities]\n\"external-café\" = \"00000000-0000-0000-0000-000000000001\"\n", arguments: &[], - expected_error: "subjects must be nonempty, unpadded ASCII header values", + expected_error: "trusted-proxy usernames must be 1-128 characters", }, ServerConfigurationTestCase { description: "a password-origin flag conflicts with the file's trusted proxy", @@ -206,3 +236,88 @@ fn given_invalid_or_conflicting_server_configuration_when_a_standalone_server_st }); } } + +#[test] +fn given_an_http_proxy_origin_and_an_unconfigured_proxy_address_when_requests_arrive_then_startup_warns_and_each_peer_is_logged_once() + { + let test_cases = [ProxyStartupTestCase { + description: "the proxy's real address differs from trusted_peers", + configuration: "[trusted_proxy]\norigin = \"http://control.example.com\"\ntrusted_peers = [\"192.0.2.1\"]\nusername_header = \"X-Example-User\"\n", + username: "orders-confidential-reader", + expected_warnings: &[ + ( + "warning: the trusted-proxy origin http://control.example.com is plain HTTP", + 1, + ), + ( + "warning: ignored the trusted-proxy username header x-example-user from 127.0.0.1, which is not in [trusted_proxy] trusted_peers", + 1, + ), + ], + }]; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + for test_case in test_cases { + runtime.block_on(async { + let directory = tempfile::tempdir().expect("proxy installation"); + std::fs::write( + directory.path().join("server.toml"), + test_case.configuration, + ) + .expect("server configuration"); + let mut control = start_control_in( + directory, + &[ + "server", + "--host", + "127.0.0.1", + "--port", + "0", + "--no-scheduler", + "--config", + "server.toml", + ], + ); + let url = api_ready(&mut control).await; + let client = Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .expect("HTTP client"); + let mut statuses = Vec::new(); + for _ in 0..2 { + let response = client + .get(format!("{url}/api/control/bootstrap")) + .header("x-forwarded-host", "control.example.com") + .header("x-example-user", test_case.username) + .send() + .await + .expect("untrusted proxy request"); + statuses.push(response.status()); + } + let log = std::fs::read_to_string(&control.stderr).expect("server log"); + let counts: Vec<(&str, usize)> = test_case + .expected_warnings + .iter() + .map(|(warning, _)| (*warning, log.matches(warning).count())) + .collect(); + assert_eq!( + ( + statuses, + counts.as_slice(), + log.contains(test_case.username) + ), + ( + vec![StatusCode::UNAUTHORIZED; 2], + test_case.expected_warnings, + false + ), + "{}: {log}", + test_case.description + ); + #[cfg(unix)] + crate::helpers::terminate(&mut control).await; + }); + } +} diff --git a/crates/sqlbuild-cli/tests/native_commands/test_types.rs b/crates/sqlbuild-cli/tests/native_commands/test_types.rs index 9d9d05ae93..fc3fc1b52d 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_types.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_types.rs @@ -52,6 +52,14 @@ pub(crate) struct ProxyCliTestCase { pub(crate) expected_statuses: [reqwest::StatusCode; 3], } +pub(crate) struct ProxyStartupTestCase { + pub(crate) description: &'static str, + pub(crate) configuration: &'static str, + /// The username the untrusted requests carry, which the log must never show. + pub(crate) username: &'static str, + pub(crate) expected_warnings: &'static [(&'static str, usize)], +} + pub(crate) struct ServerConfigurationTestCase { pub(crate) description: &'static str, pub(crate) configuration: &'static str, diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs index 014cc2ec71..48c580fff2 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs @@ -3,11 +3,12 @@ use std::net::SocketAddr; use axum::extract::{Request, State}; -use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::http::{HeaderMap, StatusCode, header}; use axum::middleware::Next; use axum::response::Response; use uuid::Uuid; +use crate::api::_helpers::authentication::password_transport::private_cache_control; use crate::api::errors::ApiError; use crate::api::models::{DevelopmentScope, ReadResource}; use crate::credentials::main::tokens::authenticate_token::authenticate_token; @@ -39,9 +40,7 @@ pub(crate) async fn authenticate( .ok_or_else(unauthorized)?; request.extensions_mut().insert(identity); let mut response = next.run(request).await; - response - .headers_mut() - .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + private_cache_control(&mut response); Ok(response) } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs index a83a2a8dee..ef181ccbeb 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs @@ -4,6 +4,9 @@ pub(crate) mod configure; pub(crate) mod development; pub(crate) mod oidc; pub(crate) mod oidc_provider; +pub(crate) mod origins; pub(crate) mod password_sessions; pub(crate) mod password_transport; +pub(crate) mod proxy_settings; +pub(crate) mod proxy_warnings; pub(crate) mod trusted_proxy; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/origins.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/origins.rs new file mode 100644 index 0000000000..d4babf278c --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/origins.rs @@ -0,0 +1,39 @@ +//! The browser origin every sign-in method checks requests against. + +use crate::api::constants::{HTTP_SCHEME, HTTPS_SCHEME, ROOT_PATH}; +use crate::store::errors::ControlError; + +/// A bare `https://` origin, or with `allow_http` also an `http://` one, in its serialized form. +pub(crate) fn parse_origin_with( + value: &str, + mechanism: &str, + allow_http: bool, +) -> Result { + let schemes = if allow_http { + "an HTTP or HTTPS" + } else { + "an HTTPS" + }; + let error = || { + ControlError::Invalid(format!( + "{mechanism} authentication requires {schemes} origin without credentials, path, query or fragment" + )) + }; + let url = reqwest::Url::parse(value).map_err(|_| { + ControlError::Invalid(format!( + "{mechanism} authentication requires {schemes} origin" + )) + })?; + let scheme_allowed = url.scheme() == HTTPS_SCHEME || allow_http && url.scheme() == HTTP_SCHEME; + if !scheme_allowed + || url.host().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.path() != ROOT_PATH + || url.query().is_some() + || url.fragment().is_some() + { + return Err(error()); + } + Ok(url.origin().ascii_serialization()) +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs index 10b2c098d9..c5df18c6d6 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs @@ -9,9 +9,14 @@ use axum::response::{IntoResponse, Response}; use axum::{Extension, Json}; use uuid::Uuid; -use crate::api::constants::{PASSWORD_COOKIE, PASSWORD_CSRF_COOKIE, PASSWORD_CSRF_HEADER}; +use crate::api::constants::{ + EVENT_STREAM_MEDIA_TYPE, FORWARDED_HOST_HEADER, PASSWORD_COOKIE, PASSWORD_CSRF_COOKIE, + PASSWORD_CSRF_HEADER, STREAM_BUFFERING_HEADER, STREAM_CACHE_CONTROL, +}; use crate::api::errors::ApiError; -use crate::api::models::{AuthenticationDenial, BrowserOrigin, ExternalIdentityResponse}; +use crate::api::models::{ + AuthenticationDenial, BrowserOrigin, ExternalIdentityResponse, ForwardedHostPeers, +}; use crate::credentials::constants::PASSWORD_SESSION_SECONDS; use crate::credentials::main::sessions::authenticate_session::authenticate_session; use crate::credentials::models::{AuditContext, AuthenticatedPerson, IssuedSession, SessionAccess}; @@ -38,8 +43,14 @@ pub(crate) async fn guard( request_id: Uuid::now_v7(), ip_address: Some(peer.ip().to_canonical()), }; - let valid_host = single_header(request.headers(), header::HOST.as_str()) - == origin.0.strip_prefix("https://"); + let authority = origin.0.split_once("://").map(|(_, authority)| authority); + let forwarded_by_proxy = request + .extensions() + .get::() + .is_some_and(|ForwardedHostPeers(peers)| peers.contains(&peer.ip().to_canonical())); + let valid_host = single_header(request.headers(), header::HOST.as_str()) == authority + || forwarded_by_proxy + && single_header(request.headers(), FORWARDED_HOST_HEADER) == authority; let valid_origin = match single_header(request.headers(), header::ORIGIN.as_str()) { Some(value) => value == origin.0, None => request.method().is_safe() && !request.headers().contains_key(header::ORIGIN), @@ -50,9 +61,7 @@ pub(crate) async fn guard( request.extensions_mut().insert(context); next.run(request).await }; - response - .headers_mut() - .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + private_cache_control(&mut response); response.headers_mut().insert( header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"), @@ -60,6 +69,28 @@ pub(crate) async fn guard( Ok(response) } +/// Never store authenticated responses; let no proxy cache, compress or buffer an event stream. +pub(crate) fn private_cache_control(response: &mut Response) { + let streamed = response + .headers() + .get(header::CONTENT_TYPE) + .is_some_and(|value| { + value + .as_bytes() + .starts_with(EVENT_STREAM_MEDIA_TYPE.as_bytes()) + }); + let headers = response.headers_mut(); + if streamed { + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static(STREAM_CACHE_CONTROL), + ); + headers.insert(STREAM_BUFFERING_HEADER, HeaderValue::from_static("no")); + } else { + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + } +} + pub(crate) async fn authenticate( State(store): State, mut request: Request, diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs new file mode 100644 index 0000000000..f88a425945 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs @@ -0,0 +1,236 @@ +//! Validated `[trusted_proxy]` settings: identity headers, canonical usernames and the sign-out URL. + +use std::collections::{BTreeMap, BTreeSet}; +use std::net::IpAddr; +use std::sync::Mutex; + +use axum::http::{HeaderMap, HeaderName}; +use uuid::Uuid; + +use crate::api::_helpers::authentication::proxy_warnings::{ + warn_taken_username, warn_untrusted_overflow, warn_untrusted_source, +}; +use crate::api::constants::{ + HTTP_SCHEME, HTTPS_SCHEME, PROXY_NOTED_SOURCES, PROXY_PROFILE_CHARS, PROXY_RESERVED_HEADERS, + PROXY_USER_HEADER, PROXY_USERNAME_CHARS, +}; +use crate::api::models::{ProxyProfile, TrustedProxyAuthentication, UnknownProxyUsers}; +use crate::store::errors::ControlError; + +pub(crate) struct ProxySettings { + pub(crate) trusted_peers: BTreeSet, + /// Canonical usernames bound to existing principals. + pub(crate) identities: BTreeMap, + pub(crate) username_header: HeaderName, + display_name_header: Option, + email_header: Option, + pub(crate) provision: bool, + pub(crate) logout_url: Option, + /// Untrusted peers already logged for sending the username header. + noted_sources: Mutex>, + /// Usernames already logged for naming another principal. + noted_usernames: Mutex>, +} + +/// Whether an item is logged now: the first time, or the one time the log fills up. +enum Note { + First, + Overflow, + Quiet, +} + +/// The username header when `[trusted_proxy] username_header` is not set. +pub(crate) fn default_username_header() -> String { + PROXY_USER_HEADER.to_owned() +} + +fn note(noted: &Mutex>, item: T) -> Note { + let Ok(mut noted) = noted.lock() else { + return Note::Quiet; + }; + if noted.len() > PROXY_NOTED_SOURCES || !noted.insert(item) { + return Note::Quiet; + } + if noted.len() > PROXY_NOTED_SOURCES { + Note::Overflow + } else { + Note::First + } +} + +impl ProxySettings { + pub(crate) fn new(settings: TrustedProxyAuthentication) -> Result { + if settings.trusted_peers.is_empty() { + return Err(ControlError::Invalid( + "trusted-proxy authentication requires explicit trusted peer IP addresses".into(), + )); + } + let username_header = header_name(&settings.username_header, "username_header")?; + let display_name_header = settings + .display_name_header + .as_deref() + .map(|name| header_name(name, "display_name_header")) + .transpose()?; + let email_header = settings + .email_header + .as_deref() + .map(|name| header_name(name, "email_header")) + .transpose()?; + let mut names = vec![&username_header]; + names.extend(display_name_header.iter()); + names.extend(email_header.iter()); + if names + .iter() + .map(|name| name.as_str()) + .collect::>() + .len() + != names.len() + { + return Err(ControlError::Invalid( + "[trusted_proxy] username_header, display_name_header and email_header must differ" + .into(), + )); + } + let mut identities: BTreeMap = BTreeMap::new(); + for (subject, principal) in settings.identities { + let username = canonical_username(&subject).ok_or_else(|| { + ControlError::Invalid(format!( + "trusted-proxy usernames must be 1-{PROXY_USERNAME_CHARS} characters of a-z, 0-9, \ + '.', '_', '@', '+' or '-', starting with a letter or digit; \ + '{}' in [trusted_proxy.identities] is not", + subject.escape_default() + )) + })?; + if identities.insert(username.clone(), principal).is_some() { + return Err(ControlError::Invalid(format!( + "[trusted_proxy.identities] binds '{username}' more than once; \ + usernames are compared in lowercase" + ))); + } + } + Ok(Self { + trusted_peers: settings + .trusted_peers + .into_iter() + .map(|peer| peer.to_canonical()) + .collect(), + identities, + username_header, + display_name_header, + email_header, + provision: match settings.unknown_users { + UnknownProxyUsers::ProvisionViewer => true, + UnknownProxyUsers::Reject => false, + }, + logout_url: settings + .proxy_logout_url + .as_deref() + .map(logout_url) + .transpose()?, + noted_sources: Mutex::new(BTreeSet::new()), + noted_usernames: Mutex::new(BTreeSet::new()), + }) + } + + /// Logs each untrusted peer that sends the username header once, so its address can be configured. + pub(crate) fn note_untrusted_source(&self, peer: IpAddr) { + match note(&self.noted_sources, peer) { + Note::First => warn_untrusted_source(self.username_header.as_str(), peer), + Note::Overflow => warn_untrusted_overflow(), + Note::Quiet => {} + } + } + + /// Logs each refused username that already names another principal once. + pub(crate) fn note_taken_username(&self, username: &str) { + if let Note::First = note(&self.noted_usernames, username.to_owned()) { + warn_taken_username(username); + } + } + + /// The display name and email address the proxy reported, read per request and never stored. + pub(crate) fn profile(&self, headers: &HeaderMap) -> ProxyProfile { + let value = + |name: &Option| name.as_ref().and_then(|name| profile_value(headers, name)); + ProxyProfile { + display_name: value(&self.display_name_header), + email: value(&self.email_header), + } + } +} + +/// The username a proxy reports, trimmed and lowercased, when it is a valid username. +pub(crate) fn canonical_username(raw: &str) -> Option { + let username = raw.trim().to_ascii_lowercase(); + let mut characters = username.chars(); + let valid = characters + .next() + .is_some_and(|first| first.is_ascii_lowercase() || first.is_ascii_digit()) + && characters.all(|character| { + character.is_ascii_lowercase() + || character.is_ascii_digit() + || matches!(character, '.' | '_' | '@' | '+' | '-') + }) + && username.len() <= PROXY_USERNAME_CHARS; + valid.then_some(username) +} + +/// One header's trimmed UTF-8 value without control characters, or nothing. +fn profile_value(headers: &HeaderMap, name: &HeaderName) -> Option { + let mut values = headers.get_all(name).iter(); + let value = values.next()?; + if values.next().is_some() { + return None; + } + let Ok(text) = std::str::from_utf8(value.as_bytes()) else { + return None; + }; + let text = text.trim(); + let usable = !text.is_empty() + && text.chars().count() <= PROXY_PROFILE_CHARS + && !text.chars().any(char::is_control); + usable.then(|| text.to_owned()) +} + +fn header_name(value: &str, key: &str) -> Result { + let name = HeaderName::from_bytes(value.trim().as_bytes()).map_err(|_| { + ControlError::Invalid(format!("[trusted_proxy] {key} is not a valid header name")) + })?; + if PROXY_RESERVED_HEADERS.contains(&name.as_str()) { + return Err(ControlError::Invalid(format!( + "[trusted_proxy] {key} cannot be {name}: browsers, proxies or the server set it" + ))); + } + Ok(name) +} + +/// An absolute HTTP(S) URL without credentials, or a path on this origin. +fn logout_url(value: &str) -> Result { + let error = || { + ControlError::Invalid( + "[trusted_proxy] proxy_logout_url must be an http:// or https:// URL without \ + credentials, or a path starting with a single /" + .into(), + ) + }; + if value.starts_with('/') { + return if value.starts_with("//") + || value.contains('\\') + || value.chars().any(char::is_control) + { + Err(error()) + } else { + Ok(value.to_owned()) + }; + } + let url = reqwest::Url::parse(value).map_err(|_| error())?; + let allowed = (url.scheme() == HTTPS_SCHEME || url.scheme() == HTTP_SCHEME) + && url.host().is_some() + && url.username().is_empty() + && url.password().is_none(); + if allowed { + Ok(url.into()) + } else { + Err(error()) + } +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs new file mode 100644 index 0000000000..5a3039336e --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs @@ -0,0 +1,33 @@ +//! Operator warnings a trusted proxy setup prints on stderr; an untrusted peer's header values are never printed. + +use std::net::IpAddr; + +use crate::api::constants::PROXY_NOTED_SOURCES; + +pub(crate) fn warn_plain_http_origin(origin: &str) { + eprintln!( + "warning: the trusted-proxy origin {origin} is plain HTTP, so sign-ins and data cross the \ + network unencrypted; serve it over HTTPS where you can" + ); +} + +pub(crate) fn warn_untrusted_source(header: &str, peer: IpAddr) { + eprintln!( + "warning: ignored the trusted-proxy username header {header} from {peer}, which is not in \ + [trusted_proxy] trusted_peers; if {peer} is your proxy, add it there" + ); +} + +pub(crate) fn warn_untrusted_overflow() { + eprintln!( + "warning: more than {PROXY_NOTED_SOURCES} untrusted peers sent the trusted-proxy username \ + header; further peers are not logged" + ); +} + +pub(crate) fn warn_taken_username(username: &str) { + eprintln!( + "warning: refused trusted-proxy username '{username}', which already names another \ + principal; bind it under [trusted_proxy.identities] to sign that person in" + ); +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs index 65a24227bd..2816f2092e 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs @@ -1,52 +1,40 @@ -//! Each request's proxy subject resolves through explicit bindings and the real socket peer. +//! Each request's proxy username resolves through bindings or provisioning, and only from a trusted socket peer. +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; -use axum::extract::{Request, State}; -use axum::http::HeaderValue; +use axum::extract::{ConnectInfo, Request, State}; use axum::middleware::Next; use axum::response::Response; use axum::{Extension, Router, middleware}; +use crate::api::_helpers::authentication::origins::parse_origin_with; use crate::api::_helpers::authentication::password_sessions; use crate::api::_helpers::authentication::password_transport::{self, deny, guard, single_header}; -use crate::api::constants::PROXY_USER_HEADER; +use crate::api::_helpers::authentication::proxy_settings::{ProxySettings, canonical_username}; +use crate::api::_helpers::authentication::proxy_warnings::warn_plain_http_origin; +use crate::api::constants::HTTP_SCHEME; use crate::api::errors::ApiError; -use crate::api::main::parse_origin::parse_origin; -use crate::api::models::{BrowserLoginMethod, BrowserOrigin, TrustedProxyAuthentication}; +use crate::api::models::{ + BrowserLoginMethod, BrowserOrigin, ForwardedHostPeers, ProxyLogoutUrl, + TrustedProxyAuthentication, +}; +use crate::authorization::main::resolve_proxy_person::resolve_proxy_person; +use crate::authorization::models::ProxyPerson; use crate::credentials::models::{AuditContext, AuthenticatedPerson}; use crate::store::errors::ControlError; -use crate::store::main::{begin::begin, commit::commit, query::query}; -use crate::store::models::{ControlStore, Parameter, TransactionMode}; +use crate::store::models::ControlStore; pub(crate) fn router( store: &ControlStore, - mut settings: TrustedProxyAuthentication, + settings: TrustedProxyAuthentication, ) -> Result, ControlError> { - let origin = BrowserOrigin(parse_origin(&settings.origin, "trusted-proxy")?); - if settings.trusted_peers.is_empty() { - return Err(ControlError::Invalid( - "trusted-proxy authentication requires explicit trusted peer IP addresses".into(), - )); + let origin = BrowserOrigin(parse_origin_with(&settings.origin, "trusted-proxy", true)?); + let settings = Arc::new(ProxySettings::new(settings)?); + if origin.0.starts_with(&format!("{HTTP_SCHEME}://")) { + warn_plain_http_origin(&origin.0); } - if settings.identities.keys().any(|subject| { - subject.trim().is_empty() - || subject.trim() != subject - || match HeaderValue::from_str(subject) { - Ok(value) => value.to_str().is_err(), - Err(_) => true, - } - }) { - return Err(ControlError::Invalid( - "trusted-proxy subjects must be nonempty, unpadded ASCII header values".into(), - )); - } - settings.trusted_peers = settings - .trusted_peers - .into_iter() - .map(|peer| peer.to_canonical()) - .collect(); - Ok(Router::new() + let mut routes = Router::new() .merge( password_sessions::person_routes() .route_layer(middleware::from_fn_with_state(store.clone(), authenticate)), @@ -54,14 +42,41 @@ pub(crate) fn router( .merge(password_sessions::session_routes(store)) .merge(super::cli_login::router(BrowserLoginMethod::Proxy)) .layer(middleware::from_fn(guard)) + .layer(middleware::from_fn(note_untrusted_sources)); + if let Some(url) = settings.logout_url.clone() { + routes = routes.layer(Extension(ProxyLogoutUrl(url))); + } + Ok(routes .layer(Extension(origin)) - .layer(Extension(Arc::new(settings)))) + .layer(Extension(ForwardedHostPeers(Arc::new( + settings.trusted_peers.clone(), + )))) + .layer(Extension(settings))) } -/// A CLI session credential authenticates as a session; otherwise the bound proxy subject does. +/// Logs untrusted peers that send the username header before any check can refuse them. +async fn note_untrusted_sources( + Extension(settings): Extension>, + request: Request, + next: Next, +) -> Response { + let peer: Option = request + .extensions() + .get::>() + .map(|ConnectInfo(peer)| peer.ip().to_canonical()); + if let Some(peer) = peer + && !settings.trusted_peers.contains(&peer) + && request.headers().contains_key(&settings.username_header) + { + settings.note_untrusted_source(peer); + } + next.run(request).await +} + +/// A CLI session credential authenticates as a session; otherwise the trusted proxy's username does. async fn authenticate( State(store): State, - Extension(settings): Extension>, + Extension(settings): Extension>, mut request: Request, next: Next, ) -> Result { @@ -79,25 +94,28 @@ async fn authenticate( { return deny(&context); } - let Some(principal_id) = single_header(request.headers(), PROXY_USER_HEADER) - .and_then(|subject| settings.identities.get(subject)) - .copied() + let Some(username) = single_header(request.headers(), settings.username_header.as_str()) + .and_then(canonical_username) else { return deny(&context); }; - let (transaction, people) = query( - begin(&store, TransactionMode::Read).await?, - "SELECT principal_id FROM sqb_principals WHERE principal_id=$1 AND disabled_at IS NULL", - vec![Parameter::Id(principal_id)], - ) - .await?; - commit(transaction).await?; - if people.is_empty() { - return deny(&context); - } + let binding = settings.identities.get(&username).copied(); + let principal_id = + match resolve_proxy_person(&store, &context, (&username, binding, settings.provision)) + .await? + { + ProxyPerson::Person(principal_id) => principal_id, + ProxyPerson::Refused => return deny(&context), + ProxyPerson::NameTaken => { + settings.note_taken_username(&username); + return deny(&context); + } + }; context.actor = format!("principal:{principal_id}"); context.granting_role = "trusted-proxy".into(); + let profile = settings.profile(request.headers()); request.extensions_mut().insert(context); + request.extensions_mut().insert(profile); request .extensions_mut() .insert(AuthenticatedPerson(principal_id, None)); diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs index cafe3c39d5..b0c442c555 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs @@ -4,16 +4,17 @@ use std::time::Duration; use axum::Extension; use axum::extract::{Path, State}; -use axum::http::{HeaderMap, HeaderValue}; -use axum::response::Sse; +use axum::http::{HeaderMap, HeaderName, HeaderValue, header}; use axum::response::sse::Event; -use futures_util::{Stream, stream}; +use axum::response::{IntoResponse, Response, Sse}; +use futures_util::stream; use sqlbuild_recall::records::main::sha256_hex::sha256_hex; use tokio::sync::broadcast; use uuid::Uuid; use crate::api::_helpers::authentication::bearer::{bearer, require_location}; use crate::api::_helpers::authentication::password_transport::session_credentials; +use crate::api::constants::{STREAM_BUFFERING_HEADER, STREAM_CACHE_CONTROL}; use crate::api::errors::ApiError; use crate::api::models::{ChangeFeed, ChangeNotice, ChangeStream, ChangeSubscriber}; use crate::authorization::main::authorize_listing::authorize_listing; @@ -46,7 +47,7 @@ pub(crate) async fn subscribe( ), Path((location_id, target)): Path<(Uuid, String)>, headers: HeaderMap, -) -> Result>>, ApiError> { +) -> Result { require_location(&identity, location_id)?; let subscriber = if identity.token_id.is_nil() { ChangeSubscriber::Development @@ -72,7 +73,7 @@ pub(crate) async fn subscribe_person( Extension, ), (Path((location_id, target)), headers): (Path<(Uuid, String)>, HeaderMap), -) -> Result>>, ApiError> { +) -> Result { let transaction = begin(&store, TransactionMode::Write).await?; let (transaction, _) = authorize_listing( transaction, @@ -107,7 +108,7 @@ async fn stream_changes( feed: ChangeFeed, subscriber: ChangeSubscriber, (location_id, target): (Uuid, String), -) -> Result>>, ApiError> { +) -> Result { let receiver = feed.sender.subscribe(); let updates = watch_node_states(&cache, (location_id, &target)).await?; let state = ChangeStream { @@ -122,7 +123,11 @@ async fn stream_changes( keepalive: tokio::time::interval(Duration::from_secs(15)), initial: true, }; - Ok(Sse::new(stream::try_unfold(state, next_event))) + let headers = [ + (header::CACHE_CONTROL, STREAM_CACHE_CONTROL), + (HeaderName::from_static(STREAM_BUFFERING_HEADER), "no"), + ]; + Ok((headers, Sse::new(stream::try_unfold(state, next_event))).into_response()) } /// Whether the subscriber may still receive this stream, checked before every emission. diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs index 1b99368046..187843212d 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs @@ -4,7 +4,7 @@ use axum::http::StatusCode; use axum::{Extension, Json, extract::State}; use crate::api::errors::ApiError; -use crate::api::models::{ControlBootstrap, LoginMode}; +use crate::api::models::{ControlBootstrap, LoginMode, ProxyLogoutUrl, ProxyProfile}; use crate::authorization::main::read_person_access::read_person_access; use crate::credentials::models::{AuthenticatedPerson, DefaultRole}; use crate::store::models::ControlStore; @@ -19,6 +19,10 @@ pub(crate) async fn read( Extension, ), Extension(AuthenticatedPerson(principal, _)): Extension, + (profile, logout_url): ( + Option>, + Option>, + ), ) -> Result, ApiError> { let Some(access) = read_person_access(&store, principal, default_role).await? else { return Err(ApiError { @@ -27,5 +31,14 @@ pub(crate) async fn read( decision_id: None, }); }; - Ok(Json(ControlBootstrap { login_mode, access })) + let profile = profile + .map(|Extension(profile)| profile) + .unwrap_or_default(); + Ok(Json(ControlBootstrap { + login_mode, + access, + display_name: profile.display_name, + email: profile.email, + logout_url: logout_url.map(|Extension(ProxyLogoutUrl(url))| url), + })) } diff --git a/crates/sqlbuild-orchestration/src/api/constants.rs b/crates/sqlbuild-orchestration/src/api/constants.rs index 176b9119c8..0b39455fb1 100644 --- a/crates/sqlbuild-orchestration/src/api/constants.rs +++ b/crates/sqlbuild-orchestration/src/api/constants.rs @@ -14,6 +14,35 @@ pub(crate) const PASSWORD_COOKIE: &str = "__Host-sqb-session"; pub(crate) const PASSWORD_CSRF_COOKIE: &str = "__Host-sqb-csrf"; pub(crate) const PASSWORD_CSRF_HEADER: &str = "x-sqb-csrf"; pub(crate) const PROXY_USER_HEADER: &str = "x-sqb-user"; +/// Headers a trusted proxy's identity headers may not reuse: browsers, the proxy or this server own them. +pub(crate) const PROXY_RESERVED_HEADERS: [&str; 14] = [ + "accept", + "authorization", + "connection", + "content-length", + "content-type", + "cookie", + "forwarded", + "host", + "origin", + "referer", + "user-agent", + "x-forwarded-for", + "x-forwarded-host", + PASSWORD_CSRF_HEADER, +]; +/// The browser host a proxy that rewrites `Host` reports, as Apache's `mod_proxy` does by default. +pub(crate) const FORWARDED_HOST_HEADER: &str = "x-forwarded-host"; +/// The longest proxy username, after trimming and lowercasing. +pub(crate) const PROXY_USERNAME_CHARS: usize = 128; +/// The longest display name or email address a proxy may report. +pub(crate) const PROXY_PROFILE_CHARS: usize = 256; +/// How many untrusted header-carrying peers are logged before the rest go unlogged. +pub(crate) const PROXY_NOTED_SOURCES: usize = 32; +/// What a streamed response sends so a proxy neither caches, compresses nor buffers it. +pub(crate) const STREAM_CACHE_CONTROL: &str = "no-cache, no-transform"; +pub(crate) const STREAM_BUFFERING_HEADER: &str = "x-accel-buffering"; +pub(crate) const EVENT_STREAM_MEDIA_TYPE: &str = "text/event-stream"; pub(crate) const OIDC_FLOW_COOKIE: &str = "__Host-sqb-oidc"; pub(crate) const OIDC_RESPONSE_BYTES: usize = 1024 * 1024; #[cfg(unix)] diff --git a/crates/sqlbuild-orchestration/src/api/main/parse_origin.rs b/crates/sqlbuild-orchestration/src/api/main/parse_origin.rs index 74cc32b878..3af7bb2fe5 100644 --- a/crates/sqlbuild-orchestration/src/api/main/parse_origin.rs +++ b/crates/sqlbuild-orchestration/src/api/main/parse_origin.rs @@ -1,28 +1,8 @@ //! Browser authentication and CLI handoffs share one strict HTTPS origin contract. -use crate::api::constants::{HTTPS_SCHEME, ROOT_PATH}; +use crate::api::_helpers::authentication::origins::parse_origin_with; use crate::store::errors::ControlError; pub fn parse_origin(value: &str, mechanism: &str) -> Result { - let error = || { - ControlError::Invalid(format!( - "{mechanism} authentication requires an HTTPS origin without credentials, path, query or fragment" - )) - }; - let url = reqwest::Url::parse(value).map_err(|_| { - ControlError::Invalid(format!( - "{mechanism} authentication requires an HTTPS origin" - )) - })?; - if url.scheme() != HTTPS_SCHEME - || url.host().is_none() - || !url.username().is_empty() - || url.password().is_some() - || url.path() != ROOT_PATH - || url.query().is_some() - || url.fragment().is_some() - { - return Err(error()); - } - Ok(url.origin().ascii_serialization()) + parse_origin_with(value, mechanism, false) } diff --git a/crates/sqlbuild-orchestration/src/api/models.rs b/crates/sqlbuild-orchestration/src/api/models.rs index 35465a9339..ff7bebeba3 100644 --- a/crates/sqlbuild-orchestration/src/api/models.rs +++ b/crates/sqlbuild-orchestration/src/api/models.rs @@ -242,6 +242,15 @@ pub enum LoginMode { pub struct ControlBootstrap { pub login_mode: LoginMode, pub access: crate::authorization::models::PersonAccess, + /// The display name a trusted proxy reported for this request, if it reports one. + #[serde(skip_serializing_if = "Option::is_none")] + pub display_name: Option, + /// The email address a trusted proxy reported for this request, if it reports one. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + /// Where signing out goes when a trusted proxy owns the sign-in; absent means no sign-out link. + #[serde(skip_serializing_if = "Option::is_none")] + pub logout_url: Option, } /// SSE invalidation topics; `all` means refetch the authorized REST resources. @@ -301,15 +310,61 @@ pub struct DockerImageSource { #[derive(Clone, Debug)] pub(crate) struct BrowserOrigin(pub(crate) String); -/// Explicit person bindings require an upstream-replaced X-SQB-User; no provisioning or grants. +/// A proxy names each signed-in person in a header that only `trusted_peers` may supply. #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct TrustedProxyAuthentication { pub origin: String, pub trusted_peers: std::collections::BTreeSet, + /// Usernames pre-bound to existing principals; a binding wins over provisioning. + #[serde(default)] pub identities: std::collections::BTreeMap, + /// The header naming the signed-in person. + #[serde( + default = "crate::api::_helpers::authentication::proxy_settings::default_username_header" + )] + pub username_header: String, + /// A header carrying the person's display name, shown in the UI and never stored. + #[serde(default)] + pub display_name_header: Option, + /// A header carrying the person's email address, shown in the UI and never stored. + #[serde(default)] + pub email_header: Option, + #[serde(default)] + pub unknown_users: UnknownProxyUsers, + /// Where the UI's sign-out link goes, since only the proxy can end its own sign-in. + #[serde(default)] + pub proxy_logout_url: Option, +} + +/// What happens to a proxy username that is neither bound nor provisioned yet. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UnknownProxyUsers { + /// Create the person with the installation-wide viewer role; admins grant more in the UI. + #[default] + ProvisionViewer, + /// Refuse the request. + Reject, +} + +/// Who the proxy says this request's person is, beyond the username; read per request, never stored. +#[derive(Clone, Debug, Default)] +pub(crate) struct ProxyProfile { + pub(crate) display_name: Option, + pub(crate) email: Option, } +/// The proxy's sign-out URL, shown to people signed in through it. +#[derive(Clone, Debug)] +pub(crate) struct ProxyLogoutUrl(pub(crate) String); + +/// Peers trusted to report the browser's host in `X-Forwarded-Host`, as a proxy that rewrites `Host` does. +#[derive(Clone, Debug)] +pub(crate) struct ForwardedHostPeers( + pub(crate) std::sync::Arc>, +); + /// Exact issuer/subject bindings authenticate existing people; beta group mappings grant roles. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/mod.rs index 2e33ac15ba..54518eed5d 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/mod.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/mod.rs @@ -4,4 +4,5 @@ pub(crate) mod administrators; pub(crate) mod custom_roles; pub(crate) mod person_grants; pub(crate) mod principal_names; +pub(crate) mod proxy_people; pub(crate) mod role_overview; diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs new file mode 100644 index 0000000000..78dd6961a1 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs @@ -0,0 +1,64 @@ +//! Proxy-provisioned people: ids derived from usernames, and the viewer each newcomer gets. + +use uuid::Uuid; + +use crate::authorization::_helpers::administrator_roles::assign_role_in; +use crate::credentials::main::identities::insert_principal::insert_principal; +use crate::credentials::models::{AuditContext, BuiltinRole, RoleAssignmentRequest, RoleKey}; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit, query::query}; +use crate::store::models::{ControlStore, Parameter, TransactionMode}; + +/// Prefixes each username before hashing, so proxy ids differ from every other derived id. +const PROXY_PRINCIPAL_PREFIX: &[u8] = b"sqlbuild:trusted-proxy-principal:"; + +/// The principal a proxy username provisions, derived so no table maps usernames to people. +pub(crate) fn proxy_principal_id(username: &str) -> Uuid { + Uuid::new_v5( + &Uuid::NAMESPACE_OID, + &[PROXY_PRINCIPAL_PREFIX, username.as_bytes()].concat(), + ) +} + +/// Whether `principal_id` exists, and if so whether it is enabled. +pub(crate) async fn principal_enabled( + store: &ControlStore, + principal_id: Uuid, +) -> Result, ControlError> { + let (transaction, people) = query( + begin(store, TransactionMode::Read).await?, + "SELECT disabled_at FROM sqb_principals WHERE principal_id=$1", + vec![Parameter::Id(principal_id)], + ) + .await?; + commit(transaction).await?; + Ok(people.first().map(|person| person["disabled_at"].is_null())) +} + +/// Creates the person with the installation-wide viewer role, or false when the name is taken. +pub(crate) async fn provision_viewer( + store: &ControlStore, + context: &AuditContext, + (principal_id, username): (Uuid, &str), +) -> Result { + let (transaction, taken) = query( + begin(store, TransactionMode::Write).await?, + "SELECT principal_id FROM sqb_principals WHERE name=$1", + vec![Parameter::Text(username.into())], + ) + .await?; + if !taken.is_empty() { + commit(transaction).await?; + return Ok(false); + } + let (transaction, _) = insert_principal(transaction, context, (principal_id, username)).await?; + let viewer = RoleAssignmentRequest { + principal_id, + role: RoleKey::Builtin(BuiltinRole::Viewer), + location_id: None, + target: None, + revoke: false, + }; + assign_role_in(transaction, context, &viewer).await?; + Ok(true) +} diff --git a/crates/sqlbuild-orchestration/src/authorization/main/bootstrap_user.rs b/crates/sqlbuild-orchestration/src/authorization/main/bootstrap_user.rs index d7a4a62ad4..6dea6cba40 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/bootstrap_user.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/bootstrap_user.rs @@ -27,7 +27,8 @@ pub async fn bootstrap_user( "people already exist, so bootstrap is closed; use grant-admin".into(), )); } - let (transaction, principal_id) = insert_principal(transaction, context, name).await?; + let (transaction, principal_id) = + insert_principal(transaction, context, (Uuid::now_v7(), name)).await?; let (transaction, _) = grant_installation_admin(transaction, context, principal_id, "bootstrap").await?; commit( diff --git a/crates/sqlbuild-orchestration/src/authorization/main/mod.rs b/crates/sqlbuild-orchestration/src/authorization/main/mod.rs index 761e1fd373..6013d50fa4 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/mod.rs @@ -17,4 +17,5 @@ pub(crate) mod publish_group_roles; pub(crate) mod read_person_access; pub mod read_security_audit; pub(crate) mod refuse_unknown; +pub(crate) mod resolve_proxy_person; pub(crate) mod row_in_target; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/resolve_proxy_person.rs b/crates/sqlbuild-orchestration/src/authorization/main/resolve_proxy_person.rs new file mode 100644 index 0000000000..b6e1c09424 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/resolve_proxy_person.rs @@ -0,0 +1,43 @@ +//! A trusted proxy's username resolves to a bound or provisioned person, provisioning newcomers as viewers. + +use uuid::Uuid; + +use crate::authorization::_helpers::proxy_people::{ + principal_enabled, provision_viewer, proxy_principal_id, +}; +use crate::authorization::models::ProxyPerson; +use crate::credentials::models::AuditContext; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; + +/// The enabled person a canonical `username` names: its binding, else its provisioned person. +pub(crate) async fn resolve_proxy_person( + store: &ControlStore, + context: &AuditContext, + (username, binding, provision): (&str, Option, bool), +) -> Result { + let principal_id = binding.unwrap_or_else(|| proxy_principal_id(username)); + let refused_or = |enabled: bool| { + if enabled { + ProxyPerson::Person(principal_id) + } else { + ProxyPerson::Refused + } + }; + match principal_enabled(store, principal_id).await? { + Some(enabled) => return Ok(refused_or(enabled)), + None if binding.is_some() || !provision => return Ok(ProxyPerson::Refused), + None => {} + } + let mut context = context.clone(); + context.actor = format!("principal:{principal_id}"); + context.granting_role = "trusted-proxy-provisioning".into(); + match provision_viewer(store, &context, (principal_id, username)).await { + Ok(true) => Ok(ProxyPerson::Person(principal_id)), + Ok(false) => Ok(ProxyPerson::NameTaken), + Err(error) => match principal_enabled(store, principal_id).await? { + Some(enabled) => Ok(refused_or(enabled)), + None => Err(error), + }, + } +} diff --git a/crates/sqlbuild-orchestration/src/authorization/models.rs b/crates/sqlbuild-orchestration/src/authorization/models.rs index 5e80963f3d..797483de74 100644 --- a/crates/sqlbuild-orchestration/src/authorization/models.rs +++ b/crates/sqlbuild-orchestration/src/authorization/models.rs @@ -14,6 +14,16 @@ pub struct LocationAccess { pub actions: Vec, } +/// What a trusted proxy's username resolves to; a concurrent first sign-in resolves to the same person. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ProxyPerson { + Person(uuid::Uuid), + /// Unknown with provisioning off, bound to a missing person, or disabled. + Refused, + /// Unknown, and its name already belongs to another principal, which is not taken over. + NameTaken, +} + /// The person's name, the actions allowed server-wide, and the location targets they can view. #[derive(Clone, Debug, PartialEq, Eq, Serialize, utoipa::ToSchema)] pub struct PersonAccess { diff --git a/crates/sqlbuild-orchestration/src/credentials/main/identities/create_principal.rs b/crates/sqlbuild-orchestration/src/credentials/main/identities/create_principal.rs index 1ff6e9a250..1f725b7805 100644 --- a/crates/sqlbuild-orchestration/src/credentials/main/identities/create_principal.rs +++ b/crates/sqlbuild-orchestration/src/credentials/main/identities/create_principal.rs @@ -14,7 +14,7 @@ pub async fn create_principal( name: &str, ) -> Result { write(store, |transaction| { - insert_principal(transaction, context, name) + insert_principal(transaction, context, (Uuid::now_v7(), name)) }) .await } diff --git a/crates/sqlbuild-orchestration/src/credentials/main/identities/insert_principal.rs b/crates/sqlbuild-orchestration/src/credentials/main/identities/insert_principal.rs index e664ebae45..c7c30818bf 100644 --- a/crates/sqlbuild-orchestration/src/credentials/main/identities/insert_principal.rs +++ b/crates/sqlbuild-orchestration/src/credentials/main/identities/insert_principal.rs @@ -9,15 +9,15 @@ use crate::store::errors::ControlError; use crate::store::main::query::query; use crate::store::models::{ControlTransaction, Parameter}; +/// Creates principal `name` with `id`: a fresh v7 id, or one derived from an external username. pub(crate) async fn insert_principal( transaction: ControlTransaction, context: &AuditContext, - name: &str, + (id, name): (Uuid, &str), ) -> Result<(ControlTransaction, Uuid), ControlError> { if name.trim().is_empty() { return Err(ControlError::Invalid("principal name is required".into())); } - let id = Uuid::now_v7(); let now = transaction.now; let (transaction, _) = query( transaction, diff --git a/crates/sqlbuild-orchestration/tests/api/changes/helpers.rs b/crates/sqlbuild-orchestration/tests/api/changes/helpers.rs index 1271f24122..3700605c61 100644 --- a/crates/sqlbuild-orchestration/tests/api/changes/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/changes/helpers.rs @@ -51,7 +51,11 @@ pub(crate) async fn request_person_feed( pub(crate) async fn opened(response: reqwest::Response) -> SseConnection { assert_eq!(response.status(), reqwest::StatusCode::OK); assert_eq!(response.headers()["content-type"], "text/event-stream"); - assert_eq!(response.headers()["cache-control"], "no-store"); + assert_eq!( + response.headers()["cache-control"], + "no-cache, no-transform" + ); + assert_eq!(response.headers()["x-accel-buffering"], "no"); let mut stream = SseConnection { response, pending: Vec::new(), diff --git a/crates/sqlbuild-orchestration/tests/api/person_sessions/helpers.rs b/crates/sqlbuild-orchestration/tests/api/person_sessions/helpers.rs index 1016ab1c86..f5de4d0917 100644 --- a/crates/sqlbuild-orchestration/tests/api/person_sessions/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/person_sessions/helpers.rs @@ -8,6 +8,7 @@ use uuid::Uuid; use crate::api::models::{ ApiAuthentication, HumanLogin, OidcAuthentication, TrustedProxyAuthentication, + UnknownProxyUsers, }; use crate::api::tests::helpers::start_api_with_authentication; use crate::api::tests::oidc_helpers::{callback, login}; @@ -37,6 +38,11 @@ pub(crate) async fn browser_sessions( origin: origin.into(), trusted_peers: BTreeSet::from(["127.0.0.1".parse().expect("socket peer")]), identities: BTreeMap::from([("orders-person".into(), person)]), + username_header: "X-SQB-User".into(), + display_name_header: None, + email_header: None, + unknown_users: UnknownProxyUsers::Reject, + proxy_logout_url: None, }), ..Default::default() }, diff --git a/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs b/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs new file mode 100644 index 0000000000..f75ddbe4cf --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs @@ -0,0 +1,66 @@ +//! Starts proxy-authenticated APIs and sends requests the way a host-rewriting proxy forwards them. + +use std::collections::{BTreeMap, BTreeSet}; + +use reqwest::{Client, RequestBuilder}; +use serde_json::{Value, json}; + +use crate::api::models::{ + ApiAuthentication, HumanLogin, TrustedProxyAuthentication, UnknownProxyUsers, +}; +use crate::api::tests::helpers::start_api_with_authentication; +use crate::api::tests::test_types::TestApi; +use crate::store::main::{begin::begin, commit::commit, query::query}; +use crate::store::models::{ControlStore, Parameter, TransactionMode}; + +pub(crate) const ORIGIN: &str = "http://control.example.com"; +pub(crate) const PUBLIC_HOST: &str = "control.example.com"; +pub(crate) const USER_HEADER: &str = "x-example-user"; +pub(crate) const NAME_HEADER: &str = "x-example-name"; +pub(crate) const LOGOUT_URL: &str = "https://sign-in.example.com/logout"; + +pub(crate) fn settings( + trusted_peer: &str, + unknown_users: UnknownProxyUsers, +) -> TrustedProxyAuthentication { + TrustedProxyAuthentication { + origin: ORIGIN.into(), + trusted_peers: BTreeSet::from([trusted_peer.parse().expect("peer IP")]), + identities: BTreeMap::new(), + username_header: "X-Example-User".into(), + display_name_header: Some("X-Example-Name".into()), + email_header: None, + unknown_users, + proxy_logout_url: Some(LOGOUT_URL.into()), + } +} + +pub(crate) async fn start(store: &ControlStore, settings: TrustedProxyAuthentication) -> TestApi { + start_api_with_authentication( + store, + ApiAuthentication { + login: HumanLogin::TrustedProxy(settings), + ..ApiAuthentication::default() + }, + ) + .await +} + +/// What the proxy forwards: the backend address as `Host` and the browser's host in `X-Forwarded-Host`. +pub(crate) fn forwarded(client: &Client, method: reqwest::Method, url: String) -> RequestBuilder { + client + .request(method, url) + .header("x-forwarded-host", PUBLIC_HOST) +} + +pub(crate) async fn rows(store: &ControlStore, sql: &str, parameters: Vec) -> Value { + let (transaction, rows) = query( + begin(store, TransactionMode::Read).await.expect("read"), + sql, + parameters, + ) + .await + .expect("query"); + commit(transaction).await.expect("read complete"); + json!(rows) +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_contracts.rs b/crates/sqlbuild-orchestration/tests/api/test_contracts.rs index 606270678b..ba12ed0de0 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_contracts.rs @@ -26,6 +26,8 @@ mod person_sessions_helpers; mod person_sessions_test_types; #[path = "plans/helpers.rs"] mod plans_helpers; +#[path = "proxy_provisioning/helpers.rs"] +mod proxy_provisioning_helpers; #[path = "recall/helpers.rs"] mod recall_helpers; #[path = "state_history/helpers.rs"] @@ -90,6 +92,8 @@ mod test_person_sessions; mod test_providers; #[path = "test_proxy.rs"] mod test_proxy; +#[path = "test_proxy_provisioning.rs"] +mod test_proxy_provisioning; #[path = "test_publish_encoding.rs"] mod test_publish_encoding; #[path = "test_reads.rs"] diff --git a/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs b/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs index 58aabc2518..d03fe4e2d6 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs @@ -6,7 +6,9 @@ use reqwest::{Client, StatusCode, header}; use serde_json::{Value, json}; use uuid::Uuid; -use crate::api::models::{ApiAuthentication, HumanLogin, TrustedProxyAuthentication}; +use crate::api::models::{ + ApiAuthentication, HumanLogin, TrustedProxyAuthentication, UnknownProxyUsers, +}; use crate::api::tests::helpers::{start_api_with_authentication, stop_api}; use crate::api::tests::test_types::ExternalSessionTestCase; use crate::authorization::main::bootstrap_user::bootstrap_user; @@ -67,6 +69,11 @@ fn given_proxy_people_when_administrators_and_roles_change_then_live_authority_h (first_subject.into(), first), (second_subject.into(), second), ]), + username_header: "X-SQB-User".into(), + display_name_header: None, + email_header: None, + unknown_users: UnknownProxyUsers::Reject, + proxy_logout_url: None, }; let api = start_api_with_authentication( store, diff --git a/crates/sqlbuild-orchestration/tests/api/test_proxy.rs b/crates/sqlbuild-orchestration/tests/api/test_proxy.rs index f9f762b681..bd91da170a 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_proxy.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_proxy.rs @@ -8,6 +8,7 @@ use uuid::Uuid; use crate::api::models::{ ApiAuthentication, AuthenticationDenial, HumanLogin, TrustedProxyAuthentication, + UnknownProxyUsers, }; use crate::api::tests::helpers::{start_api_with_authentication, stop_api}; use crate::api::tests::test_types::ProxyApiTestCase; @@ -68,6 +69,11 @@ fn given_explicit_proxy_bindings_when_real_peers_and_live_people_are_checked_the (value("subject").into(), person), (value("absent_subject").into(), Uuid::now_v7()), ]), + username_header: "X-SQB-User".into(), + display_name_header: None, + email_header: None, + unknown_users: UnknownProxyUsers::Reject, + proxy_logout_url: None, }; let api = start_api_with_authentication( store, diff --git a/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs b/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs new file mode 100644 index 0000000000..d476890413 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs @@ -0,0 +1,237 @@ +//! A proxy that rewrites `Host` over plain HTTP signs people in, provisioning newcomers as viewers. + +use reqwest::{Client, StatusCode, header}; +use serde_json::{Value, json}; + +use crate::api::models::UnknownProxyUsers; +use crate::api::tests::helpers::stop_api; +use crate::api::tests::proxy_provisioning_helpers::{ + LOGOUT_URL, NAME_HEADER, ORIGIN, USER_HEADER, forwarded, rows, settings, start, +}; +use crate::api::tests::test_types::ProxyProvisioningTestCase; +use crate::credentials::tests::role_helpers::role_fixture; +use crate::store::main::migrate_store::migrate_store; +use crate::store::models::Parameter; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_host_rewriting_http_proxy_when_people_sign_in_then_newcomers_become_viewers_and_spoofing_is_refused() + { + let test_cases = [ + ProxyProvisioningTestCase { + description: "SQLite proxy provisioning", + backend: Backend::Sqlite, + expected_refusals: [StatusCode::UNAUTHORIZED; 5], + expected_write_statuses: [ + StatusCode::UNAUTHORIZED, + StatusCode::UNAUTHORIZED, + StatusCode::UNAUTHORIZED, + StatusCode::UNPROCESSABLE_ENTITY, + ], + expected_roles: r#"[{"role_key": "viewer", "location_id": null, "target": null}]"#, + expected_feed_headers: ["no-cache, no-transform", "no", "text/event-stream"], + }, + ProxyProvisioningTestCase { + description: "PostgreSQL proxy provisioning", + backend: Backend::Postgres, + expected_refusals: [StatusCode::UNAUTHORIZED; 5], + expected_write_statuses: [ + StatusCode::UNAUTHORIZED, + StatusCode::UNAUTHORIZED, + StatusCode::UNAUTHORIZED, + StatusCode::UNPROCESSABLE_ENTITY, + ], + expected_roles: r#"[{"role_key": "viewer", "location_id": null, "target": null}]"#, + expected_feed_headers: ["no-cache, no-transform", "no", "text/event-stream"], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let roles = role_fixture(store).await; + let api = start( + store, + settings("127.0.0.1", UnknownProxyUsers::ProvisionViewer), + ) + .await; + let untrusted = start( + store, + settings("192.0.2.24", UnknownProxyUsers::ProvisionViewer), + ) + .await; + let rejecting = start(store, settings("127.0.0.1", UnknownProxyUsers::Reject)).await; + let client = Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .expect("HTTP client"); + let bootstrap = |url: &str| { + forwarded( + &client, + reqwest::Method::GET, + format!("{url}/api/control/bootstrap"), + ) + }; + let untrusted_status = bootstrap(&untrusted.url) + .header(USER_HEADER, "orders-viewer") + .send() + .await + .expect("untrusted peer") + .status(); + let missing_status = bootstrap(&api.url) + .send() + .await + .expect("no username") + .status(); + let wrong_host_status = bootstrap(&api.url) + .header("x-forwarded-host", "other.example.com") + .header(USER_HEADER, "orders-viewer") + .send() + .await + .expect("another host") + .status(); + let taken_status = bootstrap(&api.url) + .header(USER_HEADER, "support-person") + .send() + .await + .expect("a name another principal holds") + .status(); + let rejected_status = bootstrap(&rejecting.url) + .header(USER_HEADER, "orders-newcomer") + .send() + .await + .expect("rejected newcomer") + .status(); + assert_eq!( + [ + untrusted_status, + missing_status, + wrong_host_status, + taken_status, + rejected_status + ], + test_case.expected_refusals, + "{}: untrusted peer, missing username, other host, taken name, reject mode", + test_case.description + ); + assert_eq!( + rows(store, "SELECT COUNT(*) AS people FROM sqb_principals WHERE name IN ('orders-viewer','orders-newcomer')", vec![]).await, + json!([{"people": 0}]), + "{}: refused requests provision nobody", + test_case.description + ); + let first = bootstrap(&api.url) + .header(USER_HEADER, " Orders-Viewer ") + .header(NAME_HEADER, "Orders Viewer") + .send() + .await + .expect("first sign-in"); + assert_eq!(first.status(), StatusCode::OK, "{}", test_case.description); + let first: Value = first.json().await.expect("bootstrap"); + let second: Value = bootstrap(&api.url) + .header(USER_HEADER, "orders-viewer") + .send() + .await + .expect("second sign-in") + .json() + .await + .expect("bootstrap"); + assert_eq!( + ( + &first["login_mode"], + &first["access"]["name"], + &first["display_name"], + &first["logout_url"], + &second["access"]["principal_id"], + second.get("display_name"), + ), + ( + &json!("trusted_proxy"), + &json!("orders-viewer"), + &json!("Orders Viewer"), + &json!(LOGOUT_URL), + &first["access"]["principal_id"], + None, + ), + "{}: one person, named per request", + test_case.description + ); + let principal: uuid::Uuid = + serde_json::from_value(first["access"]["principal_id"].clone()).expect("person"); + assert_eq!( + rows(store, "SELECT role_key, location_id, target FROM sqb_role_assignments WHERE principal_id=$1", vec![Parameter::Id(principal)]).await, + serde_json::from_str::(test_case.expected_roles).expect("expected roles"), + "{}: exactly the installation-wide viewer role", + test_case.description + ); + let write = |origin: Option<&str>| { + let request = forwarded( + &client, + reqwest::Method::POST, + format!("{}/api/control/runs", api.url), + ) + .header(USER_HEADER, "orders-viewer") + .json(&json!({})); + origin.into_iter().fold(request, |request, origin| { + request.header(header::ORIGIN, origin) + }) + }; + let mut write_statuses = Vec::new(); + for origin in [ + Some("http://other.example.com"), + Some("https://control.example.com"), + None, + Some(ORIGIN), + ] { + write_statuses.push(write(origin).send().await.expect("write").status()); + } + assert_eq!( + write_statuses, test_case.expected_write_statuses, + "{}: only the configured http origin may write", + test_case.description + ); + let feed = forwarded( + &client, + reqwest::Method::GET, + format!( + "{}/api/control/locations/{}/targets/development/changes", + api.url, roles.location_id + ), + ) + .header(USER_HEADER, "orders-viewer") + .header(header::ACCEPT, "text/event-stream") + .send() + .await + .expect("change feed"); + let header_text = |name: &str| { + feed.headers() + .get(name) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned) + }; + assert_eq!( + ( + feed.status(), + ["cache-control", "x-accel-buffering", "content-type"].map(header_text), + ), + ( + StatusCode::OK, + test_case + .expected_feed_headers + .map(|value| Some(value.to_owned())), + ), + "{}: a proxy neither caches, compresses nor buffers the feed", + test_case.description + ); + drop(feed); + stop_api(rejecting).await; + stop_api(untrusted).await; + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_types.rs b/crates/sqlbuild-orchestration/tests/api/test_types.rs index a16e610540..e7b3657348 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_types.rs @@ -163,6 +163,19 @@ pub(crate) struct ProxyApiTestCase { pub(crate) expected_sessions: i64, } +pub(crate) struct ProxyProvisioningTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + /// Untrusted peer, missing username, another host, a taken name, and a newcomer under `reject`. + pub(crate) expected_refusals: [reqwest::StatusCode; 5], + /// Writes from another origin, the HTTPS twin of the origin, no origin, and the origin itself. + pub(crate) expected_write_statuses: [reqwest::StatusCode; 4], + /// The newcomer's role assignments as JSON rows. + pub(crate) expected_roles: &'static str, + /// The change feed's cache-control, buffering and content-type headers. + pub(crate) expected_feed_headers: [&'static str; 3], +} + pub(crate) struct ExternalSessionTestCase { pub(crate) description: &'static str, pub(crate) backend: Backend, diff --git a/fensu.toml b/fensu.toml index 9e9faafec2..3e98e109ec 100644 --- a/fensu.toml +++ b/fensu.toml @@ -1926,6 +1926,12 @@ path = "crates/sqlbuild-orchestration/src/api/_helpers/resources/plain_http.rs" symbols = ["warn_plain_http"] reason = "Locations, workers and remote publication share this client; it warns once per process on stderr, before any request, when a bearer token would travel over plain HTTP to a non-loopback host." +[[targets.rust.rule_exceptions]] +rule = "FPRSH011" +path = "crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs" +symbols = ["warn_plain_http_origin", "warn_untrusted_source", "warn_untrusted_overflow", "warn_taken_username"] +reason = "The server's operator reads trusted-proxy misconfiguration on stderr: a plain-HTTP origin at start-up, and once each the untrusted peers that send the username header and the usernames refused because another principal holds the name. Untrusted header values are never printed." + [[targets.rust.rule_exceptions]] rule = "FPRSS201" path = "crates/sqlbuild-orchestration/src/webhooks/models.rs" From ea43c34a32a5f24a3d466383c1d682c5fbd13df4 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:41:35 +0000 Subject: [PATCH 02/10] feat(ui): show the proxy's display name and sign-out link --- clients/typescript/src/schema.d.ts | 6 +++++ ui/src/lib/api/bootstrap.test.ts | 33 ++++++++++++++++++++++++ ui/src/lib/api/http-client.ts | 3 ++- ui/src/lib/api/types.ts | 2 ++ ui/src/lib/components/app-sidebar.svelte | 6 ++++- ui/src/lib/platform/sign-out.test.ts | 27 +++++++++++++++++++ ui/src/lib/platform/sign-out.ts | 14 ++++++++++ 7 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 ui/src/lib/api/bootstrap.test.ts create mode 100644 ui/src/lib/platform/sign-out.test.ts create mode 100644 ui/src/lib/platform/sign-out.ts diff --git a/clients/typescript/src/schema.d.ts b/clients/typescript/src/schema.d.ts index 6a1859dfb7..de289783db 100644 --- a/clients/typescript/src/schema.d.ts +++ b/clients/typescript/src/schema.d.ts @@ -1881,7 +1881,13 @@ export interface components { /** @description What the UI needs first: how people sign in, and what this person may see and do. */ ControlBootstrap: { access: components["schemas"]["PersonAccess"]; + /** @description The display name a trusted proxy reported for this request, if it reports one. */ + display_name?: string | null; + /** @description The email address a trusted proxy reported for this request, if it reports one. */ + email?: string | null; login_mode: components["schemas"]["LoginMode"]; + /** @description Where signing out goes when a trusted proxy owns the sign-in; absent means no sign-out link. */ + logout_url?: string | null; }; /** @description Estimated query cost of one group, such as a job, a warehouse size or a node. */ CostGroup: { diff --git a/ui/src/lib/api/bootstrap.test.ts b/ui/src/lib/api/bootstrap.test.ts new file mode 100644 index 0000000000..0122c4f125 --- /dev/null +++ b/ui/src/lib/api/bootstrap.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest'; +import { toBootstrap } from './http-client'; + +type BootstrapCase = { + description: string; + proxy: { display_name?: string; logout_url?: string }; + expected: { displayName: string; logoutUrl: string | undefined }; +}; + +const cases: BootstrapCase[] = [ + { + description: 'a proxy-reported display name and sign-out URL are shown', + proxy: { display_name: 'Orders Viewer', logout_url: 'https://sign-in.example.com/logout' }, + expected: { displayName: 'Orders Viewer', logoutUrl: 'https://sign-in.example.com/logout' } + }, + { + description: 'without them the username is shown and there is no sign-out URL', + proxy: {}, + expected: { displayName: 'orders-viewer', logoutUrl: undefined } + } +]; + +describe('toBootstrap', () => { + it.each(cases)('$description', ({ proxy, expected }) => { + const bootstrap = toBootstrap({ + login_mode: 'trusted_proxy', + access: { name: 'orders-viewer', principal_id: 'p', actions: [], locations: [] }, + ...proxy + }); + + expect({ displayName: bootstrap.user.displayName, logoutUrl: bootstrap.logoutUrl }).toEqual(expected); + }); +}); diff --git a/ui/src/lib/api/http-client.ts b/ui/src/lib/api/http-client.ts index 423eccd7ee..e112e575f8 100644 --- a/ui/src/lib/api/http-client.ts +++ b/ui/src/lib/api/http-client.ts @@ -141,7 +141,8 @@ export function toBootstrap(wire: Wire['ControlBootstrap']): Bootstrap { const authMode: AuthMode = wire.login_mode; return { authMode, - user: { kind: 'user', name: wire.access.name, displayName: wire.access.name }, + ...(wire.logout_url ? { logoutUrl: wire.logout_url } : {}), + user: { kind: 'user', name: wire.access.name, displayName: wire.display_name ?? wire.access.name }, capabilities: wire.access.actions as Capability[], locations: wire.access.locations.map( (location): Location => ({ diff --git a/ui/src/lib/api/types.ts b/ui/src/lib/api/types.ts index 57b6e679d5..9aef3bcd9b 100644 --- a/ui/src/lib/api/types.ts +++ b/ui/src/lib/api/types.ts @@ -109,6 +109,8 @@ export type Scope = { locationId: string }; export type Bootstrap = { serverVersion?: string; authMode: AuthMode; + /** Where signing out goes when a trusted proxy owns the sign-in. */ + logoutUrl?: string; user: CurrentUser; capabilities: Capability[]; locations: Location[]; diff --git a/ui/src/lib/components/app-sidebar.svelte b/ui/src/lib/components/app-sidebar.svelte index 28a9cd75d4..6f4718cc45 100644 --- a/ui/src/lib/components/app-sidebar.svelte +++ b/ui/src/lib/components/app-sidebar.svelte @@ -7,9 +7,11 @@ import SettingsIcon from '@lucide/svelte/icons/settings'; import { visibleNav, type NavBadge } from '$lib/nav'; import { app } from '$lib/state/app.svelte'; + import { signOutFor } from '$lib/platform/sign-out'; import ScopeSwitcher from './shell/scope-switcher.svelte'; const visibleGroups = $derived(visibleNav(app.client, app.capabilities)); + const signOut = $derived(signOutFor(app.bootstrap)); const badgeTone: Record = { muted: '#707782', @@ -87,7 +89,9 @@
{initials} {app.user.displayName}{#if app.user.role} · {app.user.role}{/if} - {#if app.signOut && app.bootstrap?.authMode !== 'disabled'} + {#if signOut?.kind === 'link'} + + {:else if signOut?.kind === 'session' && app.signOut} {/if}
diff --git a/ui/src/lib/platform/sign-out.test.ts b/ui/src/lib/platform/sign-out.test.ts new file mode 100644 index 0000000000..434f3b9ce6 --- /dev/null +++ b/ui/src/lib/platform/sign-out.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest'; +import { signOutFor, type SignOut } from './sign-out'; +import type { Bootstrap } from '$lib/api/types'; + +type SignOutCase = { + description: string; + bootstrap: Pick | null; + expected: SignOut; +}; + +const cases: SignOutCase[] = [ + { description: 'a password session ends on the server', bootstrap: { authMode: 'password' }, expected: { kind: 'session' } }, + { + description: 'a trusted proxy with a sign-out URL links to it', + bootstrap: { authMode: 'trusted_proxy', logoutUrl: 'https://sign-in.example.com/logout' }, + expected: { kind: 'link', href: 'https://sign-in.example.com/logout' } + }, + { description: 'a trusted proxy without one offers no sign-out', bootstrap: { authMode: 'trusted_proxy' }, expected: null }, + { description: 'local development has no sign-in', bootstrap: { authMode: 'disabled' }, expected: null }, + { description: 'before the bootstrap loads', bootstrap: null, expected: null } +]; + +describe('signOutFor', () => { + it.each(cases)('$description', ({ bootstrap, expected }) => { + expect(signOutFor(bootstrap)).toEqual(expected); + }); +}); diff --git a/ui/src/lib/platform/sign-out.ts b/ui/src/lib/platform/sign-out.ts new file mode 100644 index 0000000000..633654bcdb --- /dev/null +++ b/ui/src/lib/platform/sign-out.ts @@ -0,0 +1,14 @@ +import type { Bootstrap } from '$lib/api/types'; + +/** How a person signs out: end the server session, follow the proxy's sign-out link, or not at all. */ +export type SignOut = { kind: 'session' } | { kind: 'link'; href: string } | null; + +/** + * A trusted proxy owns its sign-in, so only its sign-out URL can end it; without one there is no + * sign-out. Local development has no sign-in. + */ +export function signOutFor(bootstrap: Pick | null): SignOut { + if (!bootstrap || bootstrap.authMode === 'disabled') return null; + if (bootstrap.authMode !== 'trusted_proxy') return { kind: 'session' }; + return bootstrap.logoutUrl ? { kind: 'link', href: bootstrap.logoutUrl } : null; +} From 5767db2d63a78fb28995d2db8d6ff5d79e52d29b Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:42:45 +0000 Subject: [PATCH 03/10] docs(server): sign in through a reverse proxy --- .../sqlbuild/references/docs/cli/server.md | 84 ++++++++++++++++++- website/src/content/docs/docs/cli/server.mdx | 83 +++++++++++++++++- 2 files changed, 165 insertions(+), 2 deletions(-) diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md index 16da2c00ef..31678aa79c 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md @@ -10,6 +10,7 @@ Online: https://sqlbuild.com/docs/cli/server/ - Configure the server - Serve over HTTPS +- Sign in through a reverse proxy - Receive platform events - Back up the control database - Upgrade @@ -67,7 +68,7 @@ executable = "/usr/local/bin/sqb" | `[server]` | `host` (default `127.0.0.1`), `port` (`8000`), `database_env` (`SQLBUILD_CONTROL_DATABASE_URL`), `password_origin`, `default_role` (`none`), `scheduler` (`true`) | | `[retention]` | `statistics_days`, `audit_days`, `snapshot_count`, `run_log_days`, `run_log_count`, `state_history_versions`; see [Set retention](#set-retention) | | `[oidc]` | `origin`, `issuer`, `client_id`, `identities`, and optionally `client_secret_env`, `certificate_authority`, `groups_claim` and `group_roles` | -| `[trusted_proxy]` | `origin`, `trusted_peers` and `identities` | +| `[trusted_proxy]` | `origin`, `trusted_peers`, and optionally `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | | `[[launchers.docker]]` | `location`, `target`, `server_url`, `max_workers`, `socket`, `location_container`, `executable`, and optional `run` and `pool_caps` tables; see [Limit worker containers](#limit-worker-containers) | | `[[launchers.local]]` | `location`, `target`, `server_url`, `max_workers`, absolute `project_dir` and `executable` paths, and an optional `pool_caps` table | @@ -97,6 +98,87 @@ warning: the bearer token for http://control.example.com travels unencrypted ove Connections to `localhost`, `127.0.0.1` or `::1` print no warning. +## Sign in through a reverse proxy + +A reverse proxy such as Apache or nginx can sign people in and tell the server who they are in a +request header. The server trusts that header only on requests whose socket peer is listed in +`trusted_peers`, so it never trusts a header that a browser sends straight to the server: + +```toml +[server] +host = "0.0.0.0" +port = 8000 + +[trusted_proxy] +origin = "https://control.example.com" +trusted_peers = ["127.0.0.1"] +username_header = "X-SQB-User" +display_name_header = "X-SQB-Display-Name" +proxy_logout_url = "https://sign-in.example.com/logout" +``` + +| Key | Meaning | +| --- | --- | +| `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | +| `trusted_peers` | The proxy's IP addresses. With the proxy on the same host as the server, this is `127.0.0.1`. | +| `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | +| `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | +| `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | +| `proxy_logout_url` | Where the UI's **Sign out** link goes. Only the proxy can end its own sign-in, so without this key the UI shows no sign-out link. | +| `[trusted_proxy.identities]` | Optional: binds a username to a principal you already created with `sqb admin create-principal`. | + +The proxy must authenticate every request, then set the username header itself, replacing any value +the browser sent. With Apache on the same host, forwarding port 80 to the server on port 8000: + +```apache + + # Your authentication: AuthType, AuthName, providers and Require valid-user + RequestHeader set X-SQB-User "expr=%{REMOTE_USER}" + +ProxyPass "/" "http://127.0.0.1:8000/" +ProxyPassReverse "/" "http://127.0.0.1:8000/" +``` + +- **Usernames.** The server trims and lowercases the username, which must be 1 to 128 characters of + `a`-`z`, `0`-`9`, `.`, `_`, `@`, `+` or `-`, starting with a letter or digit. A provisioned person + is named after their username, and an administrator grants more roles in the UI. A username that + already names another principal is refused rather than taken over; bind it under + `[trusted_proxy.identities]` to sign that person in. A disabled person stays refused. +- **Host header.** A proxy that doesn't pass on the browser's `Host` header, as Apache's + `mod_proxy` does by default, sends the browser's host in `X-Forwarded-Host`. The server accepts + that header from trusted peers, so no `ProxyPreserveHost` setting is needed. +- **Writes.** The server accepts a browser write only when its `Origin` header is exactly `origin`, + whether that is `http://` or `https://`. +- **Finding the proxy's address.** When a request carrying the username header comes from a peer + that is not in `trusted_peers`, the server ignores the header and logs the peer once, without the + header's value: + + ```text + warning: ignored the trusted-proxy username header x-sqb-user from 10.0.0.7, which is not in [trusted_proxy] trusted_peers; if 10.0.0.7 is your proxy, add it there + ``` + +- **No browser cookies.** The proxy authenticates every request, so the server issues no session + cookie to browsers in this mode, over `http://` or `https://`. +- **The CLI.** `sqb login` still needs an `https://` server URL, so that its session token never + crosses the network unencrypted. +- **Locations and workers.** They use bearer tokens, not the proxy. On the server's own host, give + them `http://127.0.0.1:8000` so their tokens stay on loopback. +- **Streaming.** The live-update feed sends `Cache-Control: no-cache, no-transform`, which stops + `mod_deflate` from compressing it, and `X-Accel-Buffering: no`. It sends a keep-alive comment + every 15 seconds, well within Apache's default 60-second `Timeout`. Long work, such as planning a + build or testing a connection, runs in the background while the UI polls for the result, so no + browser request waits on it. + +`[trusted_proxy]` cannot be combined with `password_origin` or `[oidc]`. The server refuses to +start when they are combined, when the username, display name and email headers are not distinct, +or when one of them is a header that browsers, proxies or the server set, such as `Cookie`, `Host`, +`Origin` or `X-Forwarded-For`. + +To check that streaming passes through the proxy unchanged, sign in through it in a browser, open +the developer tools' Network tab, select a location, and inspect the `changes` request. Its type is +`eventsource`, its response headers include `Cache-Control: no-cache, no-transform` and +`X-Accel-Buffering: no`, and it has no `Content-Encoding`. Its events keep arriving for minutes. + ## Receive platform events Set `SQLBUILD_PLATFORM_WEBHOOK_URL` in the server's environment to have it `POST` each platform diff --git a/website/src/content/docs/docs/cli/server.mdx b/website/src/content/docs/docs/cli/server.mdx index 45bbb0a0dd..17f55ccf65 100644 --- a/website/src/content/docs/docs/cli/server.mdx +++ b/website/src/content/docs/docs/cli/server.mdx @@ -48,7 +48,7 @@ executable = "/usr/local/bin/sqb" | `[server]` | `host` (default `127.0.0.1`), `port` (`8000`), `database_env` (`SQLBUILD_CONTROL_DATABASE_URL`), `password_origin`, `default_role` (`none`), `scheduler` (`true`) | | `[retention]` | `statistics_days`, `audit_days`, `snapshot_count`, `run_log_days`, `run_log_count`, `state_history_versions`; see [Set retention](#set-retention) | | `[oidc]` | `origin`, `issuer`, `client_id`, `identities`, and optionally `client_secret_env`, `certificate_authority`, `groups_claim` and `group_roles` | -| `[trusted_proxy]` | `origin`, `trusted_peers` and `identities` | +| `[trusted_proxy]` | `origin`, `trusted_peers`, and optionally `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | | `[[launchers.docker]]` | `location`, `target`, `server_url`, `max_workers`, `socket`, `location_container`, `executable`, and optional `run` and `pool_caps` tables; see [Limit worker containers](#limit-worker-containers) | | `[[launchers.local]]` | `location`, `target`, `server_url`, `max_workers`, absolute `project_dir` and `executable` paths, and an optional `pool_caps` table | @@ -78,6 +78,87 @@ warning: the bearer token for http://control.example.com travels unencrypted ove Connections to `localhost`, `127.0.0.1` or `::1` print no warning. +## Sign in through a reverse proxy + +A reverse proxy such as Apache or nginx can sign people in and tell the server who they are in a +request header. The server trusts that header only on requests whose socket peer is listed in +`trusted_peers`, so it never trusts a header that a browser sends straight to the server: + +```toml +[server] +host = "0.0.0.0" +port = 8000 + +[trusted_proxy] +origin = "https://control.example.com" +trusted_peers = ["127.0.0.1"] +username_header = "X-SQB-User" +display_name_header = "X-SQB-Display-Name" +proxy_logout_url = "https://sign-in.example.com/logout" +``` + +| Key | Meaning | +| --- | --- | +| `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | +| `trusted_peers` | The proxy's IP addresses. With the proxy on the same host as the server, this is `127.0.0.1`. | +| `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | +| `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | +| `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | +| `proxy_logout_url` | Where the UI's **Sign out** link goes. Only the proxy can end its own sign-in, so without this key the UI shows no sign-out link. | +| `[trusted_proxy.identities]` | Optional: binds a username to a principal you already created with `sqb admin create-principal`. | + +The proxy must authenticate every request, then set the username header itself, replacing any value +the browser sent. With Apache on the same host, forwarding port 80 to the server on port 8000: + +```apache + + # Your authentication: AuthType, AuthName, providers and Require valid-user + RequestHeader set X-SQB-User "expr=%{REMOTE_USER}" + +ProxyPass "/" "http://127.0.0.1:8000/" +ProxyPassReverse "/" "http://127.0.0.1:8000/" +``` + +- **Usernames.** The server trims and lowercases the username, which must be 1 to 128 characters of + `a`-`z`, `0`-`9`, `.`, `_`, `@`, `+` or `-`, starting with a letter or digit. A provisioned person + is named after their username, and an administrator grants more roles in the UI. A username that + already names another principal is refused rather than taken over; bind it under + `[trusted_proxy.identities]` to sign that person in. A disabled person stays refused. +- **Host header.** A proxy that doesn't pass on the browser's `Host` header, as Apache's + `mod_proxy` does by default, sends the browser's host in `X-Forwarded-Host`. The server accepts + that header from trusted peers, so no `ProxyPreserveHost` setting is needed. +- **Writes.** The server accepts a browser write only when its `Origin` header is exactly `origin`, + whether that is `http://` or `https://`. +- **Finding the proxy's address.** When a request carrying the username header comes from a peer + that is not in `trusted_peers`, the server ignores the header and logs the peer once, without the + header's value: + + ```text + warning: ignored the trusted-proxy username header x-sqb-user from 10.0.0.7, which is not in [trusted_proxy] trusted_peers; if 10.0.0.7 is your proxy, add it there + ``` + +- **No browser cookies.** The proxy authenticates every request, so the server issues no session + cookie to browsers in this mode, over `http://` or `https://`. +- **The CLI.** `sqb login` still needs an `https://` server URL, so that its session token never + crosses the network unencrypted. +- **Locations and workers.** They use bearer tokens, not the proxy. On the server's own host, give + them `http://127.0.0.1:8000` so their tokens stay on loopback. +- **Streaming.** The live-update feed sends `Cache-Control: no-cache, no-transform`, which stops + `mod_deflate` from compressing it, and `X-Accel-Buffering: no`. It sends a keep-alive comment + every 15 seconds, well within Apache's default 60-second `Timeout`. Long work, such as planning a + build or testing a connection, runs in the background while the UI polls for the result, so no + browser request waits on it. + +`[trusted_proxy]` cannot be combined with `password_origin` or `[oidc]`. The server refuses to +start when they are combined, when the username, display name and email headers are not distinct, +or when one of them is a header that browsers, proxies or the server set, such as `Cookie`, `Host`, +`Origin` or `X-Forwarded-For`. + +To check that streaming passes through the proxy unchanged, sign in through it in a browser, open +the developer tools' Network tab, select a location, and inspect the `changes` request. Its type is +`eventsource`, its response headers include `Cache-Control: no-cache, no-transform` and +`X-Accel-Buffering: no`, and it has no `Content-Encoding`. Its events keep arriving for minutes. + ## Receive platform events Set `SQLBUILD_PLATFORM_WEBHOOK_URL` in the server's environment to have it `POST` each platform From 7c05485df668567427ed38c7b5f607f2707d87e9 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:47:01 +0000 Subject: [PATCH 04/10] fix(server): trusted-proxy writes under any host name, loopback peers by default, case-insensitive name check - A request from a trusted peer may use any host name the proxy serves; a write needs the X-SQB-CSRF header, which the UI now always sends, or the configured Origin. The server still allows no cross-origin requests, so a cross-site page cannot send the header. Password, OIDC and untrusted-peer requests keep the exact Host and Origin checks. - trusted_peers defaults to 127.0.0.1 and ::1 when unset. - A newcomer whose username matches another principal's name in any case is refused rather than provisioned, without a schema change. - Proxy-Authorization, Via, X-Forwarded-Proto, X-Real-IP and any Sec- header are reserved identity-header names. --- .../tests/native_commands/test_proxy.rs | 6 ++ .../authentication/password_transport.rs | 47 +++++--- .../_helpers/authentication/proxy_settings.rs | 13 ++- .../_helpers/authentication/trusted_proxy.rs | 5 +- .../src/api/constants.rs | 15 ++- .../sqlbuild-orchestration/src/api/models.rs | 8 +- .../authorization/_helpers/proxy_people.rs | 4 +- .../tests/api/test_proxy.rs | 6 -- .../tests/api/test_proxy_provisioning.rs | 100 +++++++++++++----- .../tests/api/test_types.rs | 12 ++- ui/src/lib/api/csrf.test.ts | 15 +++ ui/src/lib/api/http-client.ts | 7 +- 12 files changed, 176 insertions(+), 62 deletions(-) create mode 100644 ui/src/lib/api/csrf.test.ts diff --git a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs index 2ecdd6fa8b..a72a44d1b9 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs @@ -105,6 +105,12 @@ fn given_invalid_or_conflicting_server_configuration_when_a_standalone_server_st arguments: &[], expected_error: "[trusted_proxy] username_header cannot be cookie", }, + ServerConfigurationTestCase { + description: "a fetch-metadata header a browser sets", + configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\nusername_header = \"Sec-Fetch-User\"\n", + arguments: &[], + expected_error: "[trusted_proxy] username_header cannot be sec-fetch-user", + }, ServerConfigurationTestCase { description: "the display name in the username header", configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\nusername_header = \"X-Example-User\"\ndisplay_name_header = \"x-example-user\"\n", diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs index c5df18c6d6..e516870952 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs @@ -10,12 +10,12 @@ use axum::{Extension, Json}; use uuid::Uuid; use crate::api::constants::{ - EVENT_STREAM_MEDIA_TYPE, FORWARDED_HOST_HEADER, PASSWORD_COOKIE, PASSWORD_CSRF_COOKIE, - PASSWORD_CSRF_HEADER, STREAM_BUFFERING_HEADER, STREAM_CACHE_CONTROL, + EVENT_STREAM_MEDIA_TYPE, PASSWORD_COOKIE, PASSWORD_CSRF_COOKIE, PASSWORD_CSRF_HEADER, + STREAM_BUFFERING_HEADER, STREAM_CACHE_CONTROL, }; use crate::api::errors::ApiError; use crate::api::models::{ - AuthenticationDenial, BrowserOrigin, ExternalIdentityResponse, ForwardedHostPeers, + AuthenticationDenial, BrowserOrigin, ExternalIdentityResponse, ProxyPeers, }; use crate::credentials::constants::PASSWORD_SESSION_SECONDS; use crate::credentials::main::sessions::authenticate_session::authenticate_session; @@ -43,19 +43,16 @@ pub(crate) async fn guard( request_id: Uuid::now_v7(), ip_address: Some(peer.ip().to_canonical()), }; - let authority = origin.0.split_once("://").map(|(_, authority)| authority); - let forwarded_by_proxy = request + let from_proxy: bool = request .extensions() - .get::() - .is_some_and(|ForwardedHostPeers(peers)| peers.contains(&peer.ip().to_canonical())); - let valid_host = single_header(request.headers(), header::HOST.as_str()) == authority - || forwarded_by_proxy - && single_header(request.headers(), FORWARDED_HOST_HEADER) == authority; - let valid_origin = match single_header(request.headers(), header::ORIGIN.as_str()) { - Some(value) => value == origin.0, - None => request.method().is_safe() && !request.headers().contains_key(header::ORIGIN), + .get::() + .is_some_and(|ProxyPeers(peers)| peers.contains(&peer.ip().to_canonical())); + let allowed: bool = if from_proxy { + proxy_request_allowed(&request, &origin) + } else { + browser_request_allowed(&request, &origin) }; - let mut response = if !valid_host || !valid_origin { + let mut response = if !allowed { deny(&context)? } else { request.extensions_mut().insert(context); @@ -69,6 +66,28 @@ pub(crate) async fn guard( Ok(response) } +/// A browser request for this origin's host whose write, if any, comes from the origin itself. +fn browser_request_allowed(request: &Request, origin: &BrowserOrigin) -> bool { + let authority: Option<&str> = origin.0.split_once("://").map(|(_, authority)| authority); + single_header(request.headers(), header::HOST.as_str()) == authority + && origin_allows(request, origin) +} + +/// A proxied request under any host name; a write needs the origin or the CSRF header, which needs CORS. +fn proxy_request_allowed(request: &Request, origin: &BrowserOrigin) -> bool { + origin_allows(request, origin) + || single_header(request.headers(), PASSWORD_CSRF_HEADER) + .is_some_and(|proof| !proof.is_empty()) +} + +/// A write from the origin itself, or a read that names no other origin. +fn origin_allows(request: &Request, origin: &BrowserOrigin) -> bool { + match single_header(request.headers(), header::ORIGIN.as_str()) { + Some(value) => value == origin.0, + None => request.method().is_safe() && !request.headers().contains_key(header::ORIGIN), + } +} + /// Never store authenticated responses; let no proxy cache, compress or buffer an event stream. pub(crate) fn private_cache_control(response: &mut Response) { let streamed = response diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs index f88a425945..da900fb5fe 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs @@ -11,8 +11,8 @@ use crate::api::_helpers::authentication::proxy_warnings::{ warn_taken_username, warn_untrusted_overflow, warn_untrusted_source, }; use crate::api::constants::{ - HTTP_SCHEME, HTTPS_SCHEME, PROXY_NOTED_SOURCES, PROXY_PROFILE_CHARS, PROXY_RESERVED_HEADERS, - PROXY_USER_HEADER, PROXY_USERNAME_CHARS, + HTTP_SCHEME, HTTPS_SCHEME, LOOPBACK_PROXY_PEERS, PROXY_NOTED_SOURCES, PROXY_PROFILE_CHARS, + PROXY_RESERVED_HEADER_PREFIX, PROXY_RESERVED_HEADERS, PROXY_USER_HEADER, PROXY_USERNAME_CHARS, }; use crate::api::models::{ProxyProfile, TrustedProxyAuthentication, UnknownProxyUsers}; use crate::store::errors::ControlError; @@ -39,6 +39,11 @@ enum Note { Quiet, } +/// The proxy peers when `[trusted_proxy] trusted_peers` is not set: a proxy on the same host. +pub(crate) fn default_trusted_peers() -> BTreeSet { + BTreeSet::from(LOOPBACK_PROXY_PEERS) +} + /// The username header when `[trusted_proxy] username_header` is not set. pub(crate) fn default_username_header() -> String { PROXY_USER_HEADER.to_owned() @@ -196,7 +201,9 @@ fn header_name(value: &str, key: &str) -> Result { let name = HeaderName::from_bytes(value.trim().as_bytes()).map_err(|_| { ControlError::Invalid(format!("[trusted_proxy] {key} is not a valid header name")) })?; - if PROXY_RESERVED_HEADERS.contains(&name.as_str()) { + if PROXY_RESERVED_HEADERS.contains(&name.as_str()) + || name.as_str().starts_with(PROXY_RESERVED_HEADER_PREFIX) + { return Err(ControlError::Invalid(format!( "[trusted_proxy] {key} cannot be {name}: browsers, proxies or the server set it" ))); diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs index 2816f2092e..4e45bace86 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs @@ -16,8 +16,7 @@ use crate::api::_helpers::authentication::proxy_warnings::warn_plain_http_origin use crate::api::constants::HTTP_SCHEME; use crate::api::errors::ApiError; use crate::api::models::{ - BrowserLoginMethod, BrowserOrigin, ForwardedHostPeers, ProxyLogoutUrl, - TrustedProxyAuthentication, + BrowserLoginMethod, BrowserOrigin, ProxyLogoutUrl, ProxyPeers, TrustedProxyAuthentication, }; use crate::authorization::main::resolve_proxy_person::resolve_proxy_person; use crate::authorization::models::ProxyPerson; @@ -48,7 +47,7 @@ pub(crate) fn router( } Ok(routes .layer(Extension(origin)) - .layer(Extension(ForwardedHostPeers(Arc::new( + .layer(Extension(ProxyPeers(Arc::new( settings.trusted_peers.clone(), )))) .layer(Extension(settings))) diff --git a/crates/sqlbuild-orchestration/src/api/constants.rs b/crates/sqlbuild-orchestration/src/api/constants.rs index 0b39455fb1..93c1e13b4a 100644 --- a/crates/sqlbuild-orchestration/src/api/constants.rs +++ b/crates/sqlbuild-orchestration/src/api/constants.rs @@ -15,7 +15,7 @@ pub(crate) const PASSWORD_CSRF_COOKIE: &str = "__Host-sqb-csrf"; pub(crate) const PASSWORD_CSRF_HEADER: &str = "x-sqb-csrf"; pub(crate) const PROXY_USER_HEADER: &str = "x-sqb-user"; /// Headers a trusted proxy's identity headers may not reuse: browsers, the proxy or this server own them. -pub(crate) const PROXY_RESERVED_HEADERS: [&str; 14] = [ +pub(crate) const PROXY_RESERVED_HEADERS: [&str; 18] = [ "accept", "authorization", "connection", @@ -25,14 +25,23 @@ pub(crate) const PROXY_RESERVED_HEADERS: [&str; 14] = [ "forwarded", "host", "origin", + "proxy-authorization", "referer", "user-agent", + "via", "x-forwarded-for", "x-forwarded-host", + "x-forwarded-proto", + "x-real-ip", PASSWORD_CSRF_HEADER, ]; -/// The browser host a proxy that rewrites `Host` reports, as Apache's `mod_proxy` does by default. -pub(crate) const FORWARDED_HOST_HEADER: &str = "x-forwarded-host"; +/// The prefix of the fetch-metadata headers browsers set, which identity headers may not reuse. +pub(crate) const PROXY_RESERVED_HEADER_PREFIX: &str = "sec-"; +/// The peers a trusted proxy on the server's own host connects from, by IPv4 or IPv6 loopback. +pub(crate) const LOOPBACK_PROXY_PEERS: [std::net::IpAddr; 2] = [ + std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + std::net::IpAddr::V6(std::net::Ipv6Addr::LOCALHOST), +]; /// The longest proxy username, after trimming and lowercasing. pub(crate) const PROXY_USERNAME_CHARS: usize = 128; /// The longest display name or email address a proxy may report. diff --git a/crates/sqlbuild-orchestration/src/api/models.rs b/crates/sqlbuild-orchestration/src/api/models.rs index ff7bebeba3..ce62356994 100644 --- a/crates/sqlbuild-orchestration/src/api/models.rs +++ b/crates/sqlbuild-orchestration/src/api/models.rs @@ -315,6 +315,10 @@ pub(crate) struct BrowserOrigin(pub(crate) String); #[serde(deny_unknown_fields)] pub struct TrustedProxyAuthentication { pub origin: String, + /// The proxy's addresses; both loopback addresses when unset, for a proxy on the same host. + #[serde( + default = "crate::api::_helpers::authentication::proxy_settings::default_trusted_peers" + )] pub trusted_peers: std::collections::BTreeSet, /// Usernames pre-bound to existing principals; a binding wins over provisioning. #[serde(default)] @@ -359,9 +363,9 @@ pub(crate) struct ProxyProfile { #[derive(Clone, Debug)] pub(crate) struct ProxyLogoutUrl(pub(crate) String); -/// Peers trusted to report the browser's host in `X-Forwarded-Host`, as a proxy that rewrites `Host` does. +/// Peers whose requests a trusted proxy authenticated, under whatever host name it serves. #[derive(Clone, Debug)] -pub(crate) struct ForwardedHostPeers( +pub(crate) struct ProxyPeers( pub(crate) std::sync::Arc>, ); diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs index 78dd6961a1..438aea2976 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs @@ -35,7 +35,7 @@ pub(crate) async fn principal_enabled( Ok(people.first().map(|person| person["disabled_at"].is_null())) } -/// Creates the person with the installation-wide viewer role, or false when the name is taken. +/// Creates the person with the viewer role, or false when a principal's name matches in any case. pub(crate) async fn provision_viewer( store: &ControlStore, context: &AuditContext, @@ -43,7 +43,7 @@ pub(crate) async fn provision_viewer( ) -> Result { let (transaction, taken) = query( begin(store, TransactionMode::Write).await?, - "SELECT principal_id FROM sqb_principals WHERE name=$1", + "SELECT principal_id FROM sqb_principals WHERE lower(name)=$1", vec![Parameter::Text(username.into())], ) .await?; diff --git a/crates/sqlbuild-orchestration/tests/api/test_proxy.rs b/crates/sqlbuild-orchestration/tests/api/test_proxy.rs index bd91da170a..977cbce8f5 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_proxy.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_proxy.rs @@ -182,12 +182,6 @@ fn given_explicit_proxy_bindings_when_real_peers_and_live_people_are_checked_the header::ORIGIN, header::HeaderValue::from_static("https://other.example.com"), )])), - request(&api.url) - .header("x-sqb-user", value("subject")) - .headers(header::HeaderMap::from_iter([( - header::HOST, - header::HeaderValue::from_static("other.example.com"), - )])), request(&untrusted.url) .header("x-sqb-user", value("subject")) .header("x-forwarded-for", value("untrusted_peer")) diff --git a/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs b/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs index d476890413..f025c47dc9 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs @@ -3,12 +3,13 @@ use reqwest::{Client, StatusCode, header}; use serde_json::{Value, json}; -use crate::api::models::UnknownProxyUsers; +use crate::api::models::{TrustedProxyAuthentication, UnknownProxyUsers}; use crate::api::tests::helpers::stop_api; use crate::api::tests::proxy_provisioning_helpers::{ - LOGOUT_URL, NAME_HEADER, ORIGIN, USER_HEADER, forwarded, rows, settings, start, + LOGOUT_URL, NAME_HEADER, ORIGIN, PUBLIC_HOST, USER_HEADER, forwarded, rows, settings, start, }; -use crate::api::tests::test_types::ProxyProvisioningTestCase; +use crate::api::tests::test_types::{ProxyPeersDefaultTestCase, ProxyProvisioningTestCase}; +use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::tests::role_helpers::role_fixture; use crate::store::main::migrate_store::migrate_store; use crate::store::models::Parameter; @@ -23,11 +24,14 @@ fn given_a_host_rewriting_http_proxy_when_people_sign_in_then_newcomers_become_v description: "SQLite proxy provisioning", backend: Backend::Sqlite, expected_refusals: [StatusCode::UNAUTHORIZED; 5], + expected_other_host_read: StatusCode::OK, expected_write_statuses: [ StatusCode::UNAUTHORIZED, StatusCode::UNAUTHORIZED, StatusCode::UNAUTHORIZED, StatusCode::UNPROCESSABLE_ENTITY, + StatusCode::UNPROCESSABLE_ENTITY, + StatusCode::UNPROCESSABLE_ENTITY, ], expected_roles: r#"[{"role_key": "viewer", "location_id": null, "target": null}]"#, expected_feed_headers: ["no-cache, no-transform", "no", "text/event-stream"], @@ -36,11 +40,14 @@ fn given_a_host_rewriting_http_proxy_when_people_sign_in_then_newcomers_become_v description: "PostgreSQL proxy provisioning", backend: Backend::Postgres, expected_refusals: [StatusCode::UNAUTHORIZED; 5], + expected_other_host_read: StatusCode::OK, expected_write_statuses: [ StatusCode::UNAUTHORIZED, StatusCode::UNAUTHORIZED, StatusCode::UNAUTHORIZED, StatusCode::UNPROCESSABLE_ENTITY, + StatusCode::UNPROCESSABLE_ENTITY, + StatusCode::UNPROCESSABLE_ENTITY, ], expected_roles: r#"[{"role_key": "viewer", "location_id": null, "target": null}]"#, expected_feed_headers: ["no-cache, no-transform", "no", "text/event-stream"], @@ -54,6 +61,9 @@ fn given_a_host_rewriting_http_proxy_when_people_sign_in_then_newcomers_become_v let store = &fixture.store; migrate_store(store).await.expect("migrate"); let roles = role_fixture(store).await; + create_principal(store, &roles.context, "Orders-Lead") + .await + .expect("a principal named in mixed case"); let api = start( store, settings("127.0.0.1", UnknownProxyUsers::ProvisionViewer), @@ -87,12 +97,11 @@ fn given_a_host_rewriting_http_proxy_when_people_sign_in_then_newcomers_become_v .await .expect("no username") .status(); - let wrong_host_status = bootstrap(&api.url) - .header("x-forwarded-host", "other.example.com") - .header(USER_HEADER, "orders-viewer") + let case_taken_status = bootstrap(&api.url) + .header(USER_HEADER, "orders-lead") .send() .await - .expect("another host") + .expect("a name another principal holds in another case") .status(); let taken_status = bootstrap(&api.url) .header(USER_HEADER, "support-person") @@ -110,16 +119,16 @@ fn given_a_host_rewriting_http_proxy_when_people_sign_in_then_newcomers_become_v [ untrusted_status, missing_status, - wrong_host_status, + case_taken_status, taken_status, rejected_status ], test_case.expected_refusals, - "{}: untrusted peer, missing username, other host, taken name, reject mode", + "{}: untrusted peer, missing username, name taken in another case, taken name, reject mode", test_case.description ); assert_eq!( - rows(store, "SELECT COUNT(*) AS people FROM sqb_principals WHERE name IN ('orders-viewer','orders-newcomer')", vec![]).await, + rows(store, "SELECT COUNT(*) AS people FROM sqb_principals WHERE name IN ('orders-viewer','orders-newcomer','orders-lead')", vec![]).await, json!([{"people": 0}]), "{}: refused requests provision nobody", test_case.description @@ -168,30 +177,49 @@ fn given_a_host_rewriting_http_proxy_when_people_sign_in_then_newcomers_become_v "{}: exactly the installation-wide viewer role", test_case.description ); - let write = |origin: Option<&str>| { - let request = forwarded( - &client, - reqwest::Method::POST, - format!("{}/api/control/runs", api.url), - ) + let other_host_read = bootstrap(&api.url) + .header("x-forwarded-host", "control-short") .header(USER_HEADER, "orders-viewer") - .json(&json!({})); - origin.into_iter().fold(request, |request, origin| { + .send() + .await + .expect("the UI under another host name") + .status(); + assert_eq!( + other_host_read, test_case.expected_other_host_read, + "{}: a proxy serves the UI under any host name", + test_case.description + ); + let write = |(origin, host, proof): (Option<&str>, &str, Option<&str>)| { + let request = client + .post(format!("{}/api/control/runs", api.url)) + .header("x-forwarded-host", host) + .header(USER_HEADER, "orders-viewer") + .json(&json!({})); + let request = origin.into_iter().fold(request, |request, origin| { request.header(header::ORIGIN, origin) + }); + proof.into_iter().fold(request, |request, proof| { + request.header("x-sqb-csrf", proof) }) }; let mut write_statuses = Vec::new(); - for origin in [ - Some("http://other.example.com"), - Some("https://control.example.com"), - None, - Some(ORIGIN), + for attempt in [ + (Some("http://other.example.com"), PUBLIC_HOST, None), + (Some("https://control.example.com"), PUBLIC_HOST, None), + (None, PUBLIC_HOST, None), + (Some(ORIGIN), PUBLIC_HOST, None), + ( + Some("http://control-short"), + "control-short", + Some("trusted-proxy"), + ), + (None, "control-short", Some("trusted-proxy")), ] { - write_statuses.push(write(origin).send().await.expect("write").status()); + write_statuses.push(write(attempt).send().await.expect("write").status()); } assert_eq!( write_statuses, test_case.expected_write_statuses, - "{}: only the configured http origin may write", + "{}: a cross-site form post, the https twin and an unproven write are refused; the origin or the CSRF header writes", test_case.description ); let feed = forwarded( @@ -235,3 +263,25 @@ fn given_a_host_rewriting_http_proxy_when_people_sign_in_then_newcomers_become_v }); } } + +#[test] +fn given_a_trusted_proxy_without_trusted_peers_when_configured_then_both_loopback_addresses_are_trusted() + { + let test_cases = [ProxyPeersDefaultTestCase { + description: "a proxy on the same host connects over either loopback address", + configuration: json!({"origin": ORIGIN}), + expected_peers: &["127.0.0.1", "::1"], + }]; + for test_case in test_cases { + let settings: TrustedProxyAuthentication = + serde_json::from_value(test_case.configuration).expect("proxy settings"); + + let peers: Vec = settings + .trusted_peers + .iter() + .map(ToString::to_string) + .collect(); + + assert_eq!(peers, test_case.expected_peers, "{}", test_case.description); + } +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_types.rs b/crates/sqlbuild-orchestration/tests/api/test_types.rs index e7b3657348..23c96e52ec 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_types.rs @@ -168,14 +168,22 @@ pub(crate) struct ProxyProvisioningTestCase { pub(crate) backend: Backend, /// Untrusted peer, missing username, another host, a taken name, and a newcomer under `reject`. pub(crate) expected_refusals: [reqwest::StatusCode; 5], - /// Writes from another origin, the HTTPS twin of the origin, no origin, and the origin itself. - pub(crate) expected_write_statuses: [reqwest::StatusCode; 4], + /// A read under another host name the proxy serves. + pub(crate) expected_other_host_read: reqwest::StatusCode, + /// Cross-site post, HTTPS twin, no proof, the origin, then the CSRF header under another host. + pub(crate) expected_write_statuses: [reqwest::StatusCode; 6], /// The newcomer's role assignments as JSON rows. pub(crate) expected_roles: &'static str, /// The change feed's cache-control, buffering and content-type headers. pub(crate) expected_feed_headers: [&'static str; 3], } +pub(crate) struct ProxyPeersDefaultTestCase { + pub(crate) description: &'static str, + pub(crate) configuration: serde_json::Value, + pub(crate) expected_peers: &'static [&'static str], +} + pub(crate) struct ExternalSessionTestCase { pub(crate) description: &'static str, pub(crate) backend: Backend, diff --git a/ui/src/lib/api/csrf.test.ts b/ui/src/lib/api/csrf.test.ts new file mode 100644 index 0000000000..da10aa1108 --- /dev/null +++ b/ui/src/lib/api/csrf.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { PROXY_CSRF_PROOF, csrfToken } from './http-client'; + +type CsrfCase = { description: string; cookies: string; expected: string }; + +const cases: CsrfCase[] = [ + { description: 'a sign-in cookie supplies the token', cookies: 'theme=dark; __Host-sqb-csrf=abc=def', expected: 'abc=def' }, + { description: 'behind a trusted proxy, with no cookie, writes send the proxy proof', cookies: 'theme=dark', expected: PROXY_CSRF_PROOF } +]; + +describe('csrfToken', () => { + it.each(cases)('$description', ({ cookies, expected }) => { + expect(csrfToken(cookies)).toBe(expected); + }); +}); diff --git a/ui/src/lib/api/http-client.ts b/ui/src/lib/api/http-client.ts index e112e575f8..f3d0a239f2 100644 --- a/ui/src/lib/api/http-client.ts +++ b/ui/src/lib/api/http-client.ts @@ -1269,13 +1269,16 @@ function errorText(error: unknown, response: Response): string { return typeof message === 'string' ? message : `${response.status} ${response.statusText}`; } -/** The CSRF token the server sets in a readable cookie at sign-in; writes send it back. */ +/** What writes send when no sign-in cookie holds a token: behind a trusted proxy, the header itself is the proof. */ +export const PROXY_CSRF_PROOF = 'trusted-proxy'; + +/** The CSRF token the server sets in a readable cookie at sign-in, or the trusted-proxy proof; writes send it back. */ export function csrfToken(cookies: string): string { for (const cookie of cookies.split(';')) { const [name, ...value] = cookie.trim().split('='); if (name === '__Host-sqb-csrf') return value.join('='); } - return ''; + return PROXY_CSRF_PROOF; } /** Signs in with a password; resolves to whether the server accepted it. */ From 105139c81e351ca6b3428d643c1b79fafee1d977 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:47:03 +0000 Subject: [PATCH 05/10] docs(server): reverse-proxy usernames, identity headers, loopback binding and access removal --- .../sqlbuild/references/docs/cli/server.md | 54 ++++++++++++------- website/src/content/docs/docs/cli/server.mdx | 54 ++++++++++++------- 2 files changed, 68 insertions(+), 40 deletions(-) diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md index 31678aa79c..91336d94d2 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md @@ -68,7 +68,7 @@ executable = "/usr/local/bin/sqb" | `[server]` | `host` (default `127.0.0.1`), `port` (`8000`), `database_env` (`SQLBUILD_CONTROL_DATABASE_URL`), `password_origin`, `default_role` (`none`), `scheduler` (`true`) | | `[retention]` | `statistics_days`, `audit_days`, `snapshot_count`, `run_log_days`, `run_log_count`, `state_history_versions`; see [Set retention](#set-retention) | | `[oidc]` | `origin`, `issuer`, `client_id`, `identities`, and optionally `client_secret_env`, `certificate_authority`, `groups_claim` and `group_roles` | -| `[trusted_proxy]` | `origin`, `trusted_peers`, and optionally `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | +| `[trusted_proxy]` | `origin`, and optionally `trusted_peers` (`127.0.0.1` and `::1`), `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | | `[[launchers.docker]]` | `location`, `target`, `server_url`, `max_workers`, `socket`, `location_container`, `executable`, and optional `run` and `pool_caps` tables; see [Limit worker containers](#limit-worker-containers) | | `[[launchers.local]]` | `location`, `target`, `server_url`, `max_workers`, absolute `project_dir` and `executable` paths, and an optional `pool_caps` table | @@ -102,16 +102,16 @@ Connections to `localhost`, `127.0.0.1` or `::1` print no warning. A reverse proxy such as Apache or nginx can sign people in and tell the server who they are in a request header. The server trusts that header only on requests whose socket peer is listed in -`trusted_peers`, so it never trusts a header that a browser sends straight to the server: +`trusted_peers`, so it never trusts a header that a browser sends straight to the server. With the +proxy on the same host, bind the server to loopback so that only local processes reach it: ```toml [server] -host = "0.0.0.0" +host = "127.0.0.1" port = 8000 [trusted_proxy] origin = "https://control.example.com" -trusted_peers = ["127.0.0.1"] username_header = "X-SQB-User" display_name_header = "X-SQB-Display-Name" proxy_logout_url = "https://sign-in.example.com/logout" @@ -120,35 +120,48 @@ proxy_logout_url = "https://sign-in.example.com/logout" | Key | Meaning | | --- | --- | | `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | -| `trusted_peers` | The proxy's IP addresses. With the proxy on the same host as the server, this is `127.0.0.1`. | +| `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6. | | `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | | `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | | `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | | `proxy_logout_url` | Where the UI's **Sign out** link goes. Only the proxy can end its own sign-in, so without this key the UI shows no sign-out link. | | `[trusted_proxy.identities]` | Optional: binds a username to a principal you already created with `sqb admin create-principal`. | -The proxy must authenticate every request, then set the username header itself, replacing any value -the browser sent. With Apache on the same host, forwarding port 80 to the server on port 8000: +The proxy must authenticate every request, then set every identity header you configured itself. +A header the proxy leaves alone passes through from the browser, so set the username header and +set or unset the display name and email headers on every request. With Apache on the same host, +forwarding port 80 to the server on port 8000: ```apache # Your authentication: AuthType, AuthName, providers and Require valid-user RequestHeader set X-SQB-User "expr=%{REMOTE_USER}" + # Set this from your provider's display name, or unset it when you have none + RequestHeader unset X-SQB-Display-Name ProxyPass "/" "http://127.0.0.1:8000/" ProxyPassReverse "/" "http://127.0.0.1:8000/" ``` -- **Usernames.** The server trims and lowercases the username, which must be 1 to 128 characters of - `a`-`z`, `0`-`9`, `.`, `_`, `@`, `+` or `-`, starting with a letter or digit. A provisioned person - is named after their username, and an administrator grants more roles in the UI. A username that - already names another principal is refused rather than taken over; bind it under - `[trusted_proxy.identities]` to sign that person in. A disabled person stays refused. -- **Host header.** A proxy that doesn't pass on the browser's `Host` header, as Apache's - `mod_proxy` does by default, sends the browser's host in `X-Forwarded-Host`. The server accepts - that header from trusted peers, so no `ProxyPreserveHost` setting is needed. -- **Writes.** The server accepts a browser write only when its `Origin` header is exactly `origin`, - whether that is `http://` or `https://`. +- **Who can sign in.** Any process that can connect to the server from a trusted peer address can + sign in as anyone by sending the username header. Keep the server's port reachable only from the + proxy: bind it to `127.0.0.1` when they share a host, or firewall it. +- **Usernames are case-insensitive.** The server trims and lowercases the username, so `Admin` and + `admin` are one person; your identity provider must treat them as the same account. A username + must be 1 to 128 characters of `a`-`z`, `0`-`9`, `.`, `_`, `@`, `+` or `-`, starting with a + letter or digit. Keys under `[trusted_proxy.identities]` are lowercased too; before this release + they matched the header's exact text, so check that no two keys now differ only in case. +- **New people.** A provisioned person is named after their username, and an administrator grants + more roles in the UI. A username that matches another principal's name in any case is refused + rather than taken over; bind it under `[trusted_proxy.identities]` to sign that person in. +- **Removing people.** `unknown_users = "reject"` stops new people from being provisioned; it + doesn't remove people already provisioned. Disable a principal to remove their access. + Removing someone at the proxy doesn't end their `sqb login` sessions: they last until they expire + or the principal is disabled. +- **Host names and writes.** The proxy can serve the UI under any host name, such as a short name, + the full name or an IP address. A browser write is accepted when it carries the `X-SQB-CSRF` + header, which the UI always sends and which a page on another site cannot send, or when its + `Origin` header is exactly `origin`. The server allows no cross-origin requests. - **Finding the proxy's address.** When a request carrying the username header comes from a peer that is not in `trusted_peers`, the server ignores the header and logs the peer once, without the header's value: @@ -170,9 +183,10 @@ ProxyPassReverse "/" "http://127.0.0.1:8000/" browser request waits on it. `[trusted_proxy]` cannot be combined with `password_origin` or `[oidc]`. The server refuses to -start when they are combined, when the username, display name and email headers are not distinct, -or when one of them is a header that browsers, proxies or the server set, such as `Cookie`, `Host`, -`Origin` or `X-Forwarded-For`. +start when they are combined, when `trusted_peers` is an empty list, when the username, display +name and email headers are not distinct, or when one of them is a header that browsers, proxies or +the server set, such as `Cookie`, `Host`, `Origin`, `Via`, `X-Forwarded-For`, `X-Real-IP` or any +`Sec-` header. To check that streaming passes through the proxy unchanged, sign in through it in a browser, open the developer tools' Network tab, select a location, and inspect the `changes` request. Its type is diff --git a/website/src/content/docs/docs/cli/server.mdx b/website/src/content/docs/docs/cli/server.mdx index 17f55ccf65..4db44a5155 100644 --- a/website/src/content/docs/docs/cli/server.mdx +++ b/website/src/content/docs/docs/cli/server.mdx @@ -48,7 +48,7 @@ executable = "/usr/local/bin/sqb" | `[server]` | `host` (default `127.0.0.1`), `port` (`8000`), `database_env` (`SQLBUILD_CONTROL_DATABASE_URL`), `password_origin`, `default_role` (`none`), `scheduler` (`true`) | | `[retention]` | `statistics_days`, `audit_days`, `snapshot_count`, `run_log_days`, `run_log_count`, `state_history_versions`; see [Set retention](#set-retention) | | `[oidc]` | `origin`, `issuer`, `client_id`, `identities`, and optionally `client_secret_env`, `certificate_authority`, `groups_claim` and `group_roles` | -| `[trusted_proxy]` | `origin`, `trusted_peers`, and optionally `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | +| `[trusted_proxy]` | `origin`, and optionally `trusted_peers` (`127.0.0.1` and `::1`), `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | | `[[launchers.docker]]` | `location`, `target`, `server_url`, `max_workers`, `socket`, `location_container`, `executable`, and optional `run` and `pool_caps` tables; see [Limit worker containers](#limit-worker-containers) | | `[[launchers.local]]` | `location`, `target`, `server_url`, `max_workers`, absolute `project_dir` and `executable` paths, and an optional `pool_caps` table | @@ -82,16 +82,16 @@ Connections to `localhost`, `127.0.0.1` or `::1` print no warning. A reverse proxy such as Apache or nginx can sign people in and tell the server who they are in a request header. The server trusts that header only on requests whose socket peer is listed in -`trusted_peers`, so it never trusts a header that a browser sends straight to the server: +`trusted_peers`, so it never trusts a header that a browser sends straight to the server. With the +proxy on the same host, bind the server to loopback so that only local processes reach it: ```toml [server] -host = "0.0.0.0" +host = "127.0.0.1" port = 8000 [trusted_proxy] origin = "https://control.example.com" -trusted_peers = ["127.0.0.1"] username_header = "X-SQB-User" display_name_header = "X-SQB-Display-Name" proxy_logout_url = "https://sign-in.example.com/logout" @@ -100,35 +100,48 @@ proxy_logout_url = "https://sign-in.example.com/logout" | Key | Meaning | | --- | --- | | `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | -| `trusted_peers` | The proxy's IP addresses. With the proxy on the same host as the server, this is `127.0.0.1`. | +| `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6. | | `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | | `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | | `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | | `proxy_logout_url` | Where the UI's **Sign out** link goes. Only the proxy can end its own sign-in, so without this key the UI shows no sign-out link. | | `[trusted_proxy.identities]` | Optional: binds a username to a principal you already created with `sqb admin create-principal`. | -The proxy must authenticate every request, then set the username header itself, replacing any value -the browser sent. With Apache on the same host, forwarding port 80 to the server on port 8000: +The proxy must authenticate every request, then set every identity header you configured itself. +A header the proxy leaves alone passes through from the browser, so set the username header and +set or unset the display name and email headers on every request. With Apache on the same host, +forwarding port 80 to the server on port 8000: ```apache # Your authentication: AuthType, AuthName, providers and Require valid-user RequestHeader set X-SQB-User "expr=%{REMOTE_USER}" + # Set this from your provider's display name, or unset it when you have none + RequestHeader unset X-SQB-Display-Name ProxyPass "/" "http://127.0.0.1:8000/" ProxyPassReverse "/" "http://127.0.0.1:8000/" ``` -- **Usernames.** The server trims and lowercases the username, which must be 1 to 128 characters of - `a`-`z`, `0`-`9`, `.`, `_`, `@`, `+` or `-`, starting with a letter or digit. A provisioned person - is named after their username, and an administrator grants more roles in the UI. A username that - already names another principal is refused rather than taken over; bind it under - `[trusted_proxy.identities]` to sign that person in. A disabled person stays refused. -- **Host header.** A proxy that doesn't pass on the browser's `Host` header, as Apache's - `mod_proxy` does by default, sends the browser's host in `X-Forwarded-Host`. The server accepts - that header from trusted peers, so no `ProxyPreserveHost` setting is needed. -- **Writes.** The server accepts a browser write only when its `Origin` header is exactly `origin`, - whether that is `http://` or `https://`. +- **Who can sign in.** Any process that can connect to the server from a trusted peer address can + sign in as anyone by sending the username header. Keep the server's port reachable only from the + proxy: bind it to `127.0.0.1` when they share a host, or firewall it. +- **Usernames are case-insensitive.** The server trims and lowercases the username, so `Admin` and + `admin` are one person; your identity provider must treat them as the same account. A username + must be 1 to 128 characters of `a`-`z`, `0`-`9`, `.`, `_`, `@`, `+` or `-`, starting with a + letter or digit. Keys under `[trusted_proxy.identities]` are lowercased too; before this release + they matched the header's exact text, so check that no two keys now differ only in case. +- **New people.** A provisioned person is named after their username, and an administrator grants + more roles in the UI. A username that matches another principal's name in any case is refused + rather than taken over; bind it under `[trusted_proxy.identities]` to sign that person in. +- **Removing people.** `unknown_users = "reject"` stops new people from being provisioned; it + doesn't remove people already provisioned. Disable a principal to remove their access. + Removing someone at the proxy doesn't end their `sqb login` sessions: they last until they expire + or the principal is disabled. +- **Host names and writes.** The proxy can serve the UI under any host name, such as a short name, + the full name or an IP address. A browser write is accepted when it carries the `X-SQB-CSRF` + header, which the UI always sends and which a page on another site cannot send, or when its + `Origin` header is exactly `origin`. The server allows no cross-origin requests. - **Finding the proxy's address.** When a request carrying the username header comes from a peer that is not in `trusted_peers`, the server ignores the header and logs the peer once, without the header's value: @@ -150,9 +163,10 @@ ProxyPassReverse "/" "http://127.0.0.1:8000/" browser request waits on it. `[trusted_proxy]` cannot be combined with `password_origin` or `[oidc]`. The server refuses to -start when they are combined, when the username, display name and email headers are not distinct, -or when one of them is a header that browsers, proxies or the server set, such as `Cookie`, `Host`, -`Origin` or `X-Forwarded-For`. +start when they are combined, when `trusted_peers` is an empty list, when the username, display +name and email headers are not distinct, or when one of them is a header that browsers, proxies or +the server set, such as `Cookie`, `Host`, `Origin`, `Via`, `X-Forwarded-For`, `X-Real-IP` or any +`Sec-` header. To check that streaming passes through the proxy unchanged, sign in through it in a browser, open the developer tools' Network tab, select a location, and inspect the `changes` request. Its type is From 106ac9f25dd3d29a82db65470761fd031d167caa Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:47:21 +0000 Subject: [PATCH 06/10] test(server): prove only a loopback TCP peer asserts a proxy identity by default Drive the sign-in routes in process with a chosen socket peer, so the default `trusted_peers` is checked against real non-loopback IPv4, IPv6 and IPv4-mapped peers, against forwarding headers that claim loopback, and against a server without `[trusted_proxy]`. State in the server docs that the default lets any process on the host assert an identity, and that listing the proxy's own address narrows it. --- Cargo.lock | 1 + Cargo.toml | 2 + crates/sqlbuild-orchestration/Cargo.toml | 1 + .../tests/api/proxy_provisioning/helpers.rs | 8 + .../tests/api/test_proxy_provisioning.rs | 174 +++++++++++++++++- .../tests/api/test_types.rs | 11 ++ .../sqlbuild/references/docs/cli/server.md | 2 +- website/src/content/docs/docs/cli/server.mdx | 2 +- 8 files changed, 196 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44d9da8daf..ee606c5947 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4394,6 +4394,7 @@ dependencies = [ "thiserror 2.0.21", "tokio", "toml", + "tower", "tower-http", "utoipa", "uuid", diff --git a/Cargo.toml b/Cargo.toml index 9a8fc2b6b0..aac6c8e5f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -88,6 +88,8 @@ axum = { version = "0.8", default-features = false, features = ["http1", "json", axum-server = { version = "0.8", default-features = false, features = ["tls-rustls-no-provider"] } # Compresses the server's larger JSON reads and UI assets for browsers. tower-http = { version = "0.6", default-features = false, features = ["compression-gzip"] } +# Tests drive the API router in process, with a chosen socket peer. +tower = { version = "0.5", default-features = false, features = ["util"] } fensu-policy = "=0.22.0" # Fensu's Python facts and core rules without their Python bindings: the default `python` # feature adds PyO3, rusqlite, flate2 and sha2. diff --git a/crates/sqlbuild-orchestration/Cargo.toml b/crates/sqlbuild-orchestration/Cargo.toml index ce822cc0b6..9c68b9f6d3 100644 --- a/crates/sqlbuild-orchestration/Cargo.toml +++ b/crates/sqlbuild-orchestration/Cargo.toml @@ -46,6 +46,7 @@ proptest.workspace = true rcgen.workspace = true rusqlite = { workspace = true, features = ["functions"] } tempfile.workspace = true +tower.workspace = true [lints] workspace = true diff --git a/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs b/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs index f75ddbe4cf..fd74772ced 100644 --- a/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs @@ -35,6 +35,14 @@ pub(crate) fn settings( } } +/// `[trusted_proxy]` with only its required origin, so `trusted_peers` takes its loopback default. +pub(crate) fn default_proxy_login() -> HumanLogin { + HumanLogin::TrustedProxy( + serde_json::from_value(json!({"origin": ORIGIN, "username_header": USER_HEADER})) + .expect("proxy settings with the default peers"), + ) +} + pub(crate) async fn start(store: &ControlStore, settings: TrustedProxyAuthentication) -> TestApi { start_api_with_authentication( store, diff --git a/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs b/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs index f025c47dc9..5f21236a84 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs @@ -1,14 +1,23 @@ //! A proxy that rewrites `Host` over plain HTTP signs people in, provisioning newcomers as viewers. +use axum::body::Body; +use axum::extract::ConnectInfo; use reqwest::{Client, StatusCode, header}; use serde_json::{Value, json}; +use tower::ServiceExt; -use crate::api::models::{TrustedProxyAuthentication, UnknownProxyUsers}; +use crate::api::_helpers::authentication::configure::configure; +use crate::api::models::{ + ApiAuthentication, HumanLogin, TrustedProxyAuthentication, UnknownProxyUsers, +}; use crate::api::tests::helpers::stop_api; use crate::api::tests::proxy_provisioning_helpers::{ - LOGOUT_URL, NAME_HEADER, ORIGIN, PUBLIC_HOST, USER_HEADER, forwarded, rows, settings, start, + LOGOUT_URL, NAME_HEADER, ORIGIN, PUBLIC_HOST, USER_HEADER, default_proxy_login, forwarded, + rows, settings, start, +}; +use crate::api::tests::test_types::{ + ProxyPeerTrustTestCase, ProxyPeersDefaultTestCase, ProxyProvisioningTestCase, }; -use crate::api::tests::test_types::{ProxyPeersDefaultTestCase, ProxyProvisioningTestCase}; use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::tests::role_helpers::role_fixture; use crate::store::main::migrate_store::migrate_store; @@ -285,3 +294,162 @@ fn given_a_trusted_proxy_without_trusted_peers_when_configured_then_both_loopbac assert_eq!(peers, test_case.expected_peers, "{}", test_case.description); } } + +#[test] +fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loopback_tcp_peer_signs_in() + { + let test_cases = [ + ProxyPeerTrustTestCase { + description: "IPv4 loopback peer, the default proxy on the same host", + login: default_proxy_login(), + peer: "127.0.0.1", + forwarding_headers: &[], + username: "orders-ipv4-loopback", + expected_status: StatusCode::OK, + expected_provisioned: true, + }, + ProxyPeerTrustTestCase { + description: "IPv6 loopback peer, the default proxy on the same host", + login: default_proxy_login(), + peer: "::1", + forwarding_headers: &[], + username: "orders-ipv6-loopback", + expected_status: StatusCode::OK, + expected_provisioned: true, + }, + ProxyPeerTrustTestCase { + description: "IPv4-mapped loopback peer from a dual-stack listener", + login: default_proxy_login(), + peer: "::ffff:127.0.0.1", + forwarding_headers: &[], + username: "orders-mapped-loopback", + expected_status: StatusCode::OK, + expected_provisioned: true, + }, + ProxyPeerTrustTestCase { + description: "IPv4 non-loopback peer not in trusted_peers", + login: default_proxy_login(), + peer: "192.0.2.24", + forwarding_headers: &[], + username: "orders-ipv4-remote", + expected_status: StatusCode::UNAUTHORIZED, + expected_provisioned: false, + }, + ProxyPeerTrustTestCase { + description: "IPv6 non-loopback peer not in trusted_peers", + login: default_proxy_login(), + peer: "2001:db8::24", + forwarding_headers: &[], + username: "orders-ipv6-remote", + expected_status: StatusCode::UNAUTHORIZED, + expected_provisioned: false, + }, + ProxyPeerTrustTestCase { + description: "IPv4-mapped non-loopback peer from a dual-stack listener", + login: default_proxy_login(), + peer: "::ffff:192.0.2.24", + forwarding_headers: &[], + username: "orders-mapped-remote", + expected_status: StatusCode::UNAUTHORIZED, + expected_provisioned: false, + }, + ProxyPeerTrustTestCase { + description: "IPv4 non-loopback peer claiming a loopback client in forwarding headers", + login: default_proxy_login(), + peer: "192.0.2.24", + forwarding_headers: &[ + ("x-forwarded-for", "127.0.0.1"), + ("x-real-ip", "127.0.0.1"), + ("forwarded", "for=127.0.0.1"), + ], + username: "orders-ipv4-forwarded", + expected_status: StatusCode::UNAUTHORIZED, + expected_provisioned: false, + }, + ProxyPeerTrustTestCase { + description: "IPv6 non-loopback peer claiming a loopback client in forwarding headers", + login: default_proxy_login(), + peer: "2001:db8::24", + forwarding_headers: &[ + ("x-forwarded-for", "::1"), + ("x-real-ip", "::1"), + ("forwarded", "for=\"[::1]\""), + ], + username: "orders-ipv6-forwarded", + expected_status: StatusCode::UNAUTHORIZED, + expected_provisioned: false, + }, + ProxyPeerTrustTestCase { + description: "password sign-in without [trusted_proxy], header from IPv4 loopback", + login: HumanLogin::Password(format!("https://{PUBLIC_HOST}")), + peer: "127.0.0.1", + forwarding_headers: &[], + username: "orders-password-ipv4", + expected_status: StatusCode::UNAUTHORIZED, + expected_provisioned: false, + }, + ProxyPeerTrustTestCase { + description: "password sign-in without [trusted_proxy], header from IPv6 loopback", + login: HumanLogin::Password(format!("https://{PUBLIC_HOST}")), + peer: "::1", + forwarding_headers: &[], + username: "orders-password-ipv6", + expected_status: StatusCode::UNAUTHORIZED, + expected_provisioned: false, + }, + ]; + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + for test_case in test_cases { + let (_, routes, _) = configure( + store, + ApiAuthentication { + login: test_case.login, + ..ApiAuthentication::default() + }, + "127.0.0.1:8080".parse().expect("listener"), + ) + .await + .expect("sign-in routes"); + let peer = std::net::SocketAddr::new(test_case.peer.parse().expect("peer IP"), 40_000); + let application = routes.with_state(store.clone()); + let request = axum::http::Request::get("/api/control/bootstrap") + .header(header::HOST, PUBLIC_HOST) + .header("x-forwarded-host", PUBLIC_HOST) + .header(USER_HEADER, test_case.username); + let request = test_case + .forwarding_headers + .iter() + .fold(request, |request, (name, value)| { + request.header(*name, *value) + }); + let mut request = request.body(Body::empty()).expect("request"); + request.extensions_mut().insert(ConnectInfo(peer)); + + let response = application.oneshot(request).await.expect("response"); + + assert_eq!( + response.status(), + test_case.expected_status, + "{}", + test_case.description + ); + assert_eq!( + rows( + store, + "SELECT COUNT(*) AS people FROM sqb_principals WHERE name = $1", + vec![Parameter::Text(test_case.username.into())], + ) + .await, + json!([{"people": i64::from(test_case.expected_provisioned)}]), + "{}: provisioned", + test_case.description + ); + } + close_test_store(fixture).await; + }); +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_types.rs b/crates/sqlbuild-orchestration/tests/api/test_types.rs index 23c96e52ec..f4b3eff94f 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_types.rs @@ -178,6 +178,17 @@ pub(crate) struct ProxyProvisioningTestCase { pub(crate) expected_feed_headers: [&'static str; 3], } +/// One identity-header request from one socket peer to a server signing people in one way. +pub(crate) struct ProxyPeerTrustTestCase { + pub(crate) description: &'static str, + pub(crate) login: crate::api::models::HumanLogin, + pub(crate) peer: &'static str, + pub(crate) forwarding_headers: &'static [(&'static str, &'static str)], + pub(crate) username: &'static str, + pub(crate) expected_status: reqwest::StatusCode, + pub(crate) expected_provisioned: bool, +} + pub(crate) struct ProxyPeersDefaultTestCase { pub(crate) description: &'static str, pub(crate) configuration: serde_json::Value, diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md index 91336d94d2..e3018dc3d1 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md @@ -120,7 +120,7 @@ proxy_logout_url = "https://sign-in.example.com/logout" | Key | Meaning | | --- | --- | | `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | -| `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6. | +| `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6, so any process on the server's host can send the header and sign in as anyone. Setting `trusted_peers` narrows this to the addresses you list: a proxy on another host, listed by its own address, keeps local processes out. The server takes the peer from the connection, never from `X-Forwarded-For` or `Forwarded`. | | `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | | `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | | `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | diff --git a/website/src/content/docs/docs/cli/server.mdx b/website/src/content/docs/docs/cli/server.mdx index 4db44a5155..6017530ebd 100644 --- a/website/src/content/docs/docs/cli/server.mdx +++ b/website/src/content/docs/docs/cli/server.mdx @@ -100,7 +100,7 @@ proxy_logout_url = "https://sign-in.example.com/logout" | Key | Meaning | | --- | --- | | `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | -| `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6. | +| `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6, so any process on the server's host can send the header and sign in as anyone. Setting `trusted_peers` narrows this to the addresses you list: a proxy on another host, listed by its own address, keeps local processes out. The server takes the peer from the connection, never from `X-Forwarded-For` or `Forwarded`. | | `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | | `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | | `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | From cb16ebac3e181003dd47d05369b20c17df9e098e Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:50:13 +0000 Subject: [PATCH 07/10] refactor(orchestration): group authorization entry points by concern The trusted-proxy resolver made `authorization/main` hold 21 modules, one over the container limit. Group them one level deep, as `credentials/main` already is: `roles` for role definitions, assignments and administrator grants; `decisions` for per-person, scope and row decisions and the security audit; `people` for the first administrator, proxy usernames and each person's access. Only module paths change. --- .../src/native_commands/main/_run_admin.rs | 4 ++-- .../main/acknowledge_person_run.rs | 2 +- .../main/list_person_acknowledgements.rs | 2 +- .../_helpers/authentication/trusted_proxy.rs | 2 +- .../api/_helpers/resources/administrators.rs | 8 +++---- .../src/api/_helpers/resources/audit.rs | 2 +- .../src/api/_helpers/resources/changes.rs | 4 ++-- .../_helpers/resources/person_bootstrap.rs | 2 +- .../src/api/main/serve_api.rs | 2 +- .../_helpers/administrator_roles.rs | 2 +- .../authorization/_helpers/administrators.rs | 2 +- .../main/{ => decisions}/authorize_listing.rs | 2 +- .../main/{ => decisions}/authorize_person.rs | 2 +- .../main/{ => decisions}/begin_authorized.rs | 2 +- .../{ => decisions}/decide_person_scopes.rs | 0 .../{ => decisions}/deny_authorization.rs | 0 .../src/authorization/main/decisions/mod.rs | 11 +++++++++ .../{ => decisions}/person_holds_target.rs | 0 .../{ => decisions}/read_security_audit.rs | 2 +- .../main/{ => decisions}/refuse_unknown.rs | 2 +- .../main/{ => decisions}/row_in_target.rs | 2 +- .../src/authorization/main/mod.rs | 24 +++---------------- .../main/{ => people}/bootstrap_user.rs | 0 .../src/authorization/main/people/mod.rs | 5 ++++ .../main/{ => people}/read_person_access.rs | 0 .../main/{ => people}/resolve_proxy_person.rs | 0 .../main/{ => roles}/assign_builtin_role.rs | 2 +- .../main/{ => roles}/change_administrator.rs | 2 +- .../main/{ => roles}/compile_roles.rs | 0 .../main/{ => roles}/grant_admin.rs | 0 .../main/{ => roles}/list_role_definitions.rs | 2 +- .../main/{ => roles}/list_role_holdings.rs | 2 +- .../src/authorization/main/roles/mod.rs | 11 +++++++++ .../main/{ => roles}/person_assigns_roles.rs | 0 .../main/{ => roles}/publish_custom_roles.rs | 0 .../main/{ => roles}/publish_group_roles.rs | 0 .../main/identities/development_person.rs | 2 +- .../main/identities/list_people.rs | 2 +- .../declarations/_helpers/trigger_scope.rs | 2 +- .../main/change_person_trigger.rs | 4 ++-- .../src/declarations/main/list_person_jobs.rs | 2 +- .../main/list_person_trigger_changes.rs | 2 +- .../declarations/main/list_person_triggers.rs | 2 +- .../declarations/main/publish_definitions.rs | 2 +- .../src/declarations/main/read_person_job.rs | 2 +- .../main/read_person_providers.rs | 2 +- .../_helpers/location/connection_tests.rs | 2 +- .../platform/_helpers/plans/plan_access.rs | 2 +- .../health/read_person_location_health.rs | 2 +- .../main/installation/read_installation.rs | 2 +- .../list_person_platform_events.rs | 2 +- .../read_person_mirrored_totals.rs | 2 +- .../main/person_reads/read_person_problems.rs | 2 +- .../runs/_helpers/lifecycle/publications.rs | 2 +- .../src/runs/_helpers/requests/adhoc.rs | 4 ++-- .../src/runs/_helpers/requests/cancel.rs | 2 +- .../src/runs/_helpers/requests/manual_job.rs | 6 ++--- .../src/runs/_helpers/requests/permissions.rs | 2 +- .../src/runs/_helpers/requests/plan.rs | 4 ++-- .../src/runs/_helpers/requests/rerun.rs | 4 ++-- .../main/listings/list_person_run_nodes.rs | 2 +- .../runs/main/listings/list_person_runs.rs | 2 +- .../src/scheduler/main/list_person_ticks.rs | 2 +- .../src/sensors/main/read_person_sensor.rs | 4 ++-- .../main/reads/list_person_snapshots.rs | 4 ++-- .../src/snapshots/main/reads/listing_read.rs | 2 +- .../main/reads/read_person_node_sql.rs | 2 +- .../main/write_sets/holds_on_nodes.rs | 2 +- .../src/warehouse_history/_helpers/checks.rs | 2 +- .../warehouse_history/_helpers/run_recall.rs | 4 ++-- .../main/read_person_check.rs | 2 +- .../main/read_person_cost_summary.rs | 2 +- .../main/read_person_maintenance.rs | 2 +- .../main/read_person_microbatch_coverage.rs | 2 +- .../main/read_person_node_costs.rs | 2 +- .../main/read_person_node_runs.rs | 2 +- .../main/read_person_run_node_error.rs | 2 +- .../main/person_reads/read_person_catalog.rs | 2 +- .../read_person_column_lineage.rs | 2 +- .../person_reads/read_person_fingerprint.rs | 2 +- .../person_reads/read_person_node_status.rs | 2 +- .../person_reads/read_person_statistics.rs | 2 +- .../tests/api/oidc/helpers.rs | 2 +- .../tests/api/plans/helpers.rs | 2 +- .../tests/api/test_catalog_reads.rs | 2 +- .../tests/api/test_column_lineage.rs | 2 +- .../tests/api/test_external_sessions.rs | 2 +- .../tests/api/test_location_health.rs | 2 +- .../tests/api/test_person_location_work.rs | 2 +- .../tests/api/test_person_plans.rs | 2 +- .../tests/api/test_person_sessions.rs | 2 +- .../tests/api/test_providers.rs | 2 +- .../tests/api/test_reads.rs | 4 ++-- .../tests/api/test_trigger_upcoming.rs | 2 +- .../tests/api/warehouse_history/helpers.rs | 2 +- .../tests/credentials/roles/helpers.rs | 4 ++-- .../tests/credentials/test_administrators.rs | 2 +- .../tests/credentials/test_audit.rs | 4 ++-- .../tests/credentials/test_project_roles.rs | 6 ++--- .../tests/credentials/test_recovery.rs | 4 +++- .../tests/platform/test_installation.rs | 2 +- .../tests/platform/test_problems.rs | 2 +- .../tests/runs/helpers.rs | 4 ++-- .../tests/runs/test_group_retries.rs | 2 +- .../tests/runs/test_permissions.rs | 4 ++-- .../main/compile_project_roles.rs | 2 +- fensu.toml | 2 +- 107 files changed, 145 insertions(+), 134 deletions(-) rename crates/sqlbuild-orchestration/src/authorization/main/{ => decisions}/authorize_listing.rs (94%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => decisions}/authorize_person.rs (96%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => decisions}/begin_authorized.rs (90%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => decisions}/decide_person_scopes.rs (100%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => decisions}/deny_authorization.rs (100%) create mode 100644 crates/sqlbuild-orchestration/src/authorization/main/decisions/mod.rs rename crates/sqlbuild-orchestration/src/authorization/main/{ => decisions}/person_holds_target.rs (100%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => decisions}/read_security_audit.rs (93%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => decisions}/refuse_unknown.rs (95%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => decisions}/row_in_target.rs (95%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => people}/bootstrap_user.rs (100%) create mode 100644 crates/sqlbuild-orchestration/src/authorization/main/people/mod.rs rename crates/sqlbuild-orchestration/src/authorization/main/{ => people}/read_person_access.rs (100%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => people}/resolve_proxy_person.rs (100%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => roles}/assign_builtin_role.rs (91%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => roles}/change_administrator.rs (93%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => roles}/compile_roles.rs (100%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => roles}/grant_admin.rs (100%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => roles}/list_role_definitions.rs (93%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => roles}/list_role_holdings.rs (95%) create mode 100644 crates/sqlbuild-orchestration/src/authorization/main/roles/mod.rs rename crates/sqlbuild-orchestration/src/authorization/main/{ => roles}/person_assigns_roles.rs (100%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => roles}/publish_custom_roles.rs (100%) rename crates/sqlbuild-orchestration/src/authorization/main/{ => roles}/publish_group_roles.rs (100%) diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_admin.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_admin.rs index db8739dd5f..3adc7665aa 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_admin.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_admin.rs @@ -2,8 +2,8 @@ use crate::adhoc::main::adhoc_planner::adhoc_planner; use serde_json::{Value, json}; -use sqlbuild_orchestration::authorization::main::bootstrap_user::bootstrap_user; -use sqlbuild_orchestration::authorization::main::grant_admin::grant_admin; +use sqlbuild_orchestration::authorization::main::people::bootstrap_user::bootstrap_user; +use sqlbuild_orchestration::authorization::main::roles::grant_admin::grant_admin; use sqlbuild_orchestration::credentials::main::identities::create_principal::create_principal; use sqlbuild_orchestration::credentials::main::locations::create_location::create_location; use sqlbuild_orchestration::credentials::main::sessions::set_password::set_password; diff --git a/crates/sqlbuild-orchestration/src/acknowledgements/main/acknowledge_person_run.rs b/crates/sqlbuild-orchestration/src/acknowledgements/main/acknowledge_person_run.rs index cbd42eca59..f8ed4a8d57 100644 --- a/crates/sqlbuild-orchestration/src/acknowledgements/main/acknowledge_person_run.rs +++ b/crates/sqlbuild-orchestration/src/acknowledgements/main/acknowledge_person_run.rs @@ -4,7 +4,7 @@ use serde_json::json; use uuid::Uuid; use crate::acknowledgements::models::AcknowledgementRequest; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; diff --git a/crates/sqlbuild-orchestration/src/acknowledgements/main/list_person_acknowledgements.rs b/crates/sqlbuild-orchestration/src/acknowledgements/main/list_person_acknowledgements.rs index 2e51fb07b3..77948a3d3c 100644 --- a/crates/sqlbuild-orchestration/src/acknowledgements/main/list_person_acknowledgements.rs +++ b/crates/sqlbuild-orchestration/src/acknowledgements/main/list_person_acknowledgements.rs @@ -6,7 +6,7 @@ use chrono::{DateTime, Duration, Utc}; use uuid::Uuid; use crate::acknowledgements::models::RunAcknowledgement; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit, query::query}; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs index 4e45bace86..d23f504d5b 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs @@ -18,7 +18,7 @@ use crate::api::errors::ApiError; use crate::api::models::{ BrowserLoginMethod, BrowserOrigin, ProxyLogoutUrl, ProxyPeers, TrustedProxyAuthentication, }; -use crate::authorization::main::resolve_proxy_person::resolve_proxy_person; +use crate::authorization::main::people::resolve_proxy_person::resolve_proxy_person; use crate::authorization::models::ProxyPerson; use crate::credentials::models::{AuditContext, AuthenticatedPerson}; use crate::store::errors::ControlError; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/administrators.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/administrators.rs index bfcc0dd7ee..6897aa5d5c 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/administrators.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/administrators.rs @@ -8,10 +8,10 @@ use crate::api::errors::ApiError; use crate::api::models::{ LoginMode, MutationResponse, ServerFacts, ServerRetention, ServerSettings, }; -use crate::authorization::main::assign_builtin_role::assign_builtin_role; -use crate::authorization::main::change_administrator::change_administrator; -use crate::authorization::main::list_role_definitions::list_role_definitions; -use crate::authorization::main::list_role_holdings::list_role_holdings; +use crate::authorization::main::roles::assign_builtin_role::assign_builtin_role; +use crate::authorization::main::roles::change_administrator::change_administrator; +use crate::authorization::main::roles::list_role_definitions::list_role_definitions; +use crate::authorization::main::roles::list_role_holdings::list_role_holdings; use crate::credentials::main::identities::list_people::list_people; use crate::credentials::models::AuthenticatedPerson; use crate::credentials::models::{ diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/audit.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/audit.rs index 1cf398f92d..fd0f1b1433 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/audit.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/audit.rs @@ -5,7 +5,7 @@ use axum::{Extension, Json}; use crate::api::errors::ApiError; use crate::api::models::ReadAuditQuery; -use crate::authorization::main::read_security_audit::read_security_audit; +use crate::authorization::main::decisions::read_security_audit::read_security_audit; use crate::credentials::models::AuthenticatedPerson; use crate::credentials::models::{AuditContext, SecurityAuditEvent}; use crate::store::models::ControlStore; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs index b0c442c555..4ba6bdebf7 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/changes.rs @@ -17,8 +17,8 @@ use crate::api::_helpers::authentication::password_transport::session_credential use crate::api::constants::{STREAM_BUFFERING_HEADER, STREAM_CACHE_CONTROL}; use crate::api::errors::ApiError; use crate::api::models::{ChangeFeed, ChangeNotice, ChangeStream, ChangeSubscriber}; -use crate::authorization::main::authorize_listing::authorize_listing; -use crate::authorization::main::person_holds_target::person_holds_target; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::person_holds_target::person_holds_target; use crate::credentials::main::sessions::authenticate_session::authenticate_session; use crate::credentials::main::tokens::authenticate_token::authenticate_token; use crate::credentials::models::{ diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs index 187843212d..5b477f8bd5 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs @@ -5,7 +5,7 @@ use axum::{Extension, Json, extract::State}; use crate::api::errors::ApiError; use crate::api::models::{ControlBootstrap, LoginMode, ProxyLogoutUrl, ProxyProfile}; -use crate::authorization::main::read_person_access::read_person_access; +use crate::authorization::main::people::read_person_access::read_person_access; use crate::credentials::models::{AuthenticatedPerson, DefaultRole}; use crate::store::models::ControlStore; diff --git a/crates/sqlbuild-orchestration/src/api/main/serve_api.rs b/crates/sqlbuild-orchestration/src/api/main/serve_api.rs index 5bc7517ace..234faa387a 100644 --- a/crates/sqlbuild-orchestration/src/api/main/serve_api.rs +++ b/crates/sqlbuild-orchestration/src/api/main/serve_api.rs @@ -8,7 +8,7 @@ use crate::api::_helpers::resources::application::{application_router, developme use crate::api::_helpers::resources::changes; use crate::api::main::openapi_document::openapi_document; use crate::api::models::{ApiAuthentication, GroupRole, ServerFacts}; -use crate::authorization::main::publish_group_roles::publish_group_roles; +use crate::authorization::main::roles::publish_group_roles::publish_group_roles; use crate::node_states::main::start_node_states::start_node_states; use crate::runs::types::RunHandoff; use crate::store::errors::ControlError; diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/administrator_roles.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/administrator_roles.rs index 700d64f5a2..5002a82e3a 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/administrator_roles.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/administrator_roles.rs @@ -4,7 +4,7 @@ use serde_json::json; use uuid::Uuid; use crate::authorization::_helpers::administrator_changes::apply_change; -use crate::authorization::main::deny_authorization::deny; +use crate::authorization::main::decisions::deny_authorization::deny; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{ AdministratorChange, AuditContext, BuiltinRole, RoleAssignmentRequest, RoleKey, diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/administrators.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/administrators.rs index a427309cbf..e84dfc3789 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/administrators.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/administrators.rs @@ -3,7 +3,7 @@ use serde_json::json; use uuid::Uuid; -use crate::authorization::main::deny_authorization::deny; +use crate::authorization::main::decisions::deny_authorization::deny; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::AuditContext; use crate::store::errors::ControlError; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/authorize_listing.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/authorize_listing.rs similarity index 94% rename from crates/sqlbuild-orchestration/src/authorization/main/authorize_listing.rs rename to crates/sqlbuild-orchestration/src/authorization/main/decisions/authorize_listing.rs index 1801ec9f17..6d66edc645 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/authorize_listing.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/decisions/authorize_listing.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use uuid::Uuid; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::store::errors::ControlError; use crate::store::main::query::query; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/authorize_person.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/authorize_person.rs similarity index 96% rename from crates/sqlbuild-orchestration/src/authorization/main/authorize_person.rs rename to crates/sqlbuild-orchestration/src/authorization/main/decisions/authorize_person.rs index b8ca2c0170..9e0700c740 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/authorize_person.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/decisions/authorize_person.rs @@ -7,7 +7,7 @@ use crate::authorization::_helpers::custom_roles::denial_reason; use crate::authorization::_helpers::person_grants::{ GrantDecision, decide_grant, person_role_rows, }; -use crate::authorization::main::deny_authorization::deny; +use crate::authorization::main::decisions::deny_authorization::deny; use crate::credentials::models::{AuditContext, DefaultRole, PermissionScope}; use crate::store::errors::ControlError; use crate::store::models::ControlTransaction; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/begin_authorized.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/begin_authorized.rs similarity index 90% rename from crates/sqlbuild-orchestration/src/authorization/main/begin_authorized.rs rename to crates/sqlbuild-orchestration/src/authorization/main/decisions/begin_authorized.rs index 545f1de591..42e0f5d2cc 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/begin_authorized.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/decisions/begin_authorized.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{AuditContext, DefaultRole, PermissionScope}; use crate::store::errors::ControlError; use crate::store::main::begin::begin; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/decide_person_scopes.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/decide_person_scopes.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/decide_person_scopes.rs rename to crates/sqlbuild-orchestration/src/authorization/main/decisions/decide_person_scopes.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/deny_authorization.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/deny_authorization.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/deny_authorization.rs rename to crates/sqlbuild-orchestration/src/authorization/main/decisions/deny_authorization.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/decisions/mod.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/mod.rs new file mode 100644 index 0000000000..7c947f3f4e --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/decisions/mod.rs @@ -0,0 +1,11 @@ +//! Authorization decisions for one person, scope or row, and the security audit they write. + +pub(crate) mod authorize_listing; +pub(crate) mod authorize_person; +pub(crate) mod begin_authorized; +pub(crate) mod decide_person_scopes; +pub(crate) mod deny_authorization; +pub(crate) mod person_holds_target; +pub mod read_security_audit; +pub(crate) mod refuse_unknown; +pub(crate) mod row_in_target; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/person_holds_target.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/person_holds_target.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/person_holds_target.rs rename to crates/sqlbuild-orchestration/src/authorization/main/decisions/person_holds_target.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/read_security_audit.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/read_security_audit.rs similarity index 93% rename from crates/sqlbuild-orchestration/src/authorization/main/read_security_audit.rs rename to crates/sqlbuild-orchestration/src/authorization/main/decisions/read_security_audit.rs index 2d6b927695..9cc9aeec5a 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/read_security_audit.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/decisions/read_security_audit.rs @@ -3,7 +3,7 @@ use uuid::Uuid; use crate::authorization::_helpers::principal_names::principal_names; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::main::audit::read_audit_events::read_audit_events; use crate::credentials::models::{ Action, AuditContext, DefaultRole, PermissionScope, SecurityAuditEvent, diff --git a/crates/sqlbuild-orchestration/src/authorization/main/refuse_unknown.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/refuse_unknown.rs similarity index 95% rename from crates/sqlbuild-orchestration/src/authorization/main/refuse_unknown.rs rename to crates/sqlbuild-orchestration/src/authorization/main/decisions/refuse_unknown.rs index bafb0a9e6a..36cf4f3367 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/refuse_unknown.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/decisions/refuse_unknown.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use uuid::Uuid; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::store::errors::ControlError; use crate::store::main::query::query; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/row_in_target.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/row_in_target.rs similarity index 95% rename from crates/sqlbuild-orchestration/src/authorization/main/row_in_target.rs rename to crates/sqlbuild-orchestration/src/authorization/main/decisions/row_in_target.rs index 0ac63bfd3d..f6aafc59a2 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/row_in_target.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/decisions/row_in_target.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit, query::query}; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/mod.rs b/crates/sqlbuild-orchestration/src/authorization/main/mod.rs index 6013d50fa4..155e9bd2a1 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/mod.rs @@ -1,21 +1,3 @@ -pub mod assign_builtin_role; -pub(crate) mod authorize_listing; -pub(crate) mod authorize_person; -pub(crate) mod begin_authorized; -pub mod bootstrap_user; -pub mod change_administrator; -pub mod compile_roles; -pub(crate) mod decide_person_scopes; -pub(crate) mod deny_authorization; -pub mod grant_admin; -pub mod list_role_definitions; -pub mod list_role_holdings; -pub(crate) mod person_assigns_roles; -pub(crate) mod person_holds_target; -pub(crate) mod publish_custom_roles; -pub(crate) mod publish_group_roles; -pub(crate) mod read_person_access; -pub mod read_security_audit; -pub(crate) mod refuse_unknown; -pub(crate) mod resolve_proxy_person; -pub(crate) mod row_in_target; +pub mod decisions; +pub mod people; +pub mod roles; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/bootstrap_user.rs b/crates/sqlbuild-orchestration/src/authorization/main/people/bootstrap_user.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/bootstrap_user.rs rename to crates/sqlbuild-orchestration/src/authorization/main/people/bootstrap_user.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/people/mod.rs b/crates/sqlbuild-orchestration/src/authorization/main/people/mod.rs new file mode 100644 index 0000000000..f7b71a1aa1 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/people/mod.rs @@ -0,0 +1,5 @@ +//! The people who sign in: the first administrator, proxy usernames and each person's access. + +pub mod bootstrap_user; +pub(crate) mod read_person_access; +pub(crate) mod resolve_proxy_person; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/read_person_access.rs b/crates/sqlbuild-orchestration/src/authorization/main/people/read_person_access.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/read_person_access.rs rename to crates/sqlbuild-orchestration/src/authorization/main/people/read_person_access.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/resolve_proxy_person.rs b/crates/sqlbuild-orchestration/src/authorization/main/people/resolve_proxy_person.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/resolve_proxy_person.rs rename to crates/sqlbuild-orchestration/src/authorization/main/people/resolve_proxy_person.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/assign_builtin_role.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/assign_builtin_role.rs similarity index 91% rename from crates/sqlbuild-orchestration/src/authorization/main/assign_builtin_role.rs rename to crates/sqlbuild-orchestration/src/authorization/main/roles/assign_builtin_role.rs index 30d8c58e13..83a1a7fdd1 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/assign_builtin_role.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/roles/assign_builtin_role.rs @@ -3,7 +3,7 @@ use uuid::Uuid; use crate::authorization::_helpers::administrator_roles::assign_role_in; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{ Action, AuditContext, DefaultRole, PermissionScope, RoleAssignmentRequest, }; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/change_administrator.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/change_administrator.rs similarity index 93% rename from crates/sqlbuild-orchestration/src/authorization/main/change_administrator.rs rename to crates/sqlbuild-orchestration/src/authorization/main/roles/change_administrator.rs index ee105edfd8..a059306b7a 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/change_administrator.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/roles/change_administrator.rs @@ -3,7 +3,7 @@ use uuid::Uuid; use crate::authorization::_helpers::administrator_changes::apply_change; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{ Action, AdministratorChange, AuditContext, DefaultRole, PermissionScope, }; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/compile_roles.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/compile_roles.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/compile_roles.rs rename to crates/sqlbuild-orchestration/src/authorization/main/roles/compile_roles.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/grant_admin.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/grant_admin.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/grant_admin.rs rename to crates/sqlbuild-orchestration/src/authorization/main/roles/grant_admin.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/list_role_definitions.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/list_role_definitions.rs similarity index 93% rename from crates/sqlbuild-orchestration/src/authorization/main/list_role_definitions.rs rename to crates/sqlbuild-orchestration/src/authorization/main/roles/list_role_definitions.rs index a84bfa99b8..b86f110ad4 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/list_role_definitions.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/roles/list_role_definitions.rs @@ -3,7 +3,7 @@ use uuid::Uuid; use crate::authorization::_helpers::role_overview::{read_role_facts, role_overviews}; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{ Action, AuditContext, DefaultRole, PermissionScope, RoleOverview, }; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/list_role_holdings.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/list_role_holdings.rs similarity index 95% rename from crates/sqlbuild-orchestration/src/authorization/main/list_role_holdings.rs rename to crates/sqlbuild-orchestration/src/authorization/main/roles/list_role_holdings.rs index 28207113a2..772da4e9e4 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/list_role_holdings.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/roles/list_role_holdings.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{ Action, AuditContext, DefaultRole, PermissionScope, RoleHoldings, }; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/roles/mod.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/mod.rs new file mode 100644 index 0000000000..1f969e72eb --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/roles/mod.rs @@ -0,0 +1,11 @@ +//! Role definitions, assignments and administrator grants. + +pub mod assign_builtin_role; +pub mod change_administrator; +pub mod compile_roles; +pub mod grant_admin; +pub mod list_role_definitions; +pub mod list_role_holdings; +pub(crate) mod person_assigns_roles; +pub(crate) mod publish_custom_roles; +pub(crate) mod publish_group_roles; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/person_assigns_roles.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/person_assigns_roles.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/person_assigns_roles.rs rename to crates/sqlbuild-orchestration/src/authorization/main/roles/person_assigns_roles.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/publish_custom_roles.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/publish_custom_roles.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/publish_custom_roles.rs rename to crates/sqlbuild-orchestration/src/authorization/main/roles/publish_custom_roles.rs diff --git a/crates/sqlbuild-orchestration/src/authorization/main/publish_group_roles.rs b/crates/sqlbuild-orchestration/src/authorization/main/roles/publish_group_roles.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/authorization/main/publish_group_roles.rs rename to crates/sqlbuild-orchestration/src/authorization/main/roles/publish_group_roles.rs diff --git a/crates/sqlbuild-orchestration/src/credentials/main/identities/development_person.rs b/crates/sqlbuild-orchestration/src/credentials/main/identities/development_person.rs index 587416b462..bd4d561292 100644 --- a/crates/sqlbuild-orchestration/src/credentials/main/identities/development_person.rs +++ b/crates/sqlbuild-orchestration/src/credentials/main/identities/development_person.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::grant_admin::grant_admin; +use crate::authorization::main::roles::grant_admin::grant_admin; use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::models::AuditContext; use crate::store::errors::ControlError; diff --git a/crates/sqlbuild-orchestration/src/credentials/main/identities/list_people.rs b/crates/sqlbuild-orchestration/src/credentials/main/identities/list_people.rs index de67a734f9..b752f8e567 100644 --- a/crates/sqlbuild-orchestration/src/credentials/main/identities/list_people.rs +++ b/crates/sqlbuild-orchestration/src/credentials/main/identities/list_people.rs @@ -6,7 +6,7 @@ use chrono::{DateTime, Utc}; use serde_json::json; use uuid::Uuid; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{ Action, AuditContext, DefaultRole, PermissionScope, PersonSummary, }; diff --git a/crates/sqlbuild-orchestration/src/declarations/_helpers/trigger_scope.rs b/crates/sqlbuild-orchestration/src/declarations/_helpers/trigger_scope.rs index 2e80a96822..1bea4d03d9 100644 --- a/crates/sqlbuild-orchestration/src/declarations/_helpers/trigger_scope.rs +++ b/crates/sqlbuild-orchestration/src/declarations/_helpers/trigger_scope.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::refuse_unknown::refuse_unknown; +use crate::authorization::main::decisions::refuse_unknown::refuse_unknown; use crate::credentials::models::{Action, AuditContext, PermissionScope}; use crate::declarations::models::{TriggerChange, TriggerChangeRequest}; use crate::runs::main::requests::frozen_job_request::frozen_job_request; diff --git a/crates/sqlbuild-orchestration/src/declarations/main/change_person_trigger.rs b/crates/sqlbuild-orchestration/src/declarations/main/change_person_trigger.rs index 25f8cc75ac..f8831a18fc 100644 --- a/crates/sqlbuild-orchestration/src/declarations/main/change_person_trigger.rs +++ b/crates/sqlbuild-orchestration/src/declarations/main/change_person_trigger.rs @@ -3,8 +3,8 @@ use serde_json::json; use uuid::Uuid; -use crate::authorization::main::authorize_person::authorize_person; -use crate::authorization::main::deny_authorization::deny; +use crate::authorization::main::decisions::authorize_person::authorize_person; +use crate::authorization::main::decisions::deny_authorization::deny; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::declarations::_helpers::operator_change::change_trigger_in; use crate::declarations::_helpers::trigger_scope::trigger_scope; diff --git a/crates/sqlbuild-orchestration/src/declarations/main/list_person_jobs.rs b/crates/sqlbuild-orchestration/src/declarations/main/list_person_jobs.rs index 6f6acdcb4e..027af76f47 100644 --- a/crates/sqlbuild-orchestration/src/declarations/main/list_person_jobs.rs +++ b/crates/sqlbuild-orchestration/src/declarations/main/list_person_jobs.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::declarations::_helpers::reads::jobs_in; use crate::declarations::models::{JobRecord, ServerPoolCaps}; diff --git a/crates/sqlbuild-orchestration/src/declarations/main/list_person_trigger_changes.rs b/crates/sqlbuild-orchestration/src/declarations/main/list_person_trigger_changes.rs index a890145e2b..1fc8262945 100644 --- a/crates/sqlbuild-orchestration/src/declarations/main/list_person_trigger_changes.rs +++ b/crates/sqlbuild-orchestration/src/declarations/main/list_person_trigger_changes.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::row_in_target::row_in_target; +use crate::authorization::main::decisions::row_in_target::row_in_target; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::declarations::_helpers::reads::trigger_changes_in; use crate::declarations::models::PersonTriggerChange; diff --git a/crates/sqlbuild-orchestration/src/declarations/main/list_person_triggers.rs b/crates/sqlbuild-orchestration/src/declarations/main/list_person_triggers.rs index 94a4f0c976..a3c991c61b 100644 --- a/crates/sqlbuild-orchestration/src/declarations/main/list_person_triggers.rs +++ b/crates/sqlbuild-orchestration/src/declarations/main/list_person_triggers.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::declarations::_helpers::reads::{latest_ticks_in, triggers_in}; use crate::declarations::_helpers::trigger_state::upcoming_times; diff --git a/crates/sqlbuild-orchestration/src/declarations/main/publish_definitions.rs b/crates/sqlbuild-orchestration/src/declarations/main/publish_definitions.rs index 4c181629a4..663b280081 100644 --- a/crates/sqlbuild-orchestration/src/declarations/main/publish_definitions.rs +++ b/crates/sqlbuild-orchestration/src/declarations/main/publish_definitions.rs @@ -2,7 +2,7 @@ use std::collections::BTreeSet; -use crate::authorization::main::publish_custom_roles::publish_custom_roles; +use crate::authorization::main::roles::publish_custom_roles::publish_custom_roles; use crate::declarations::_helpers::development::{pause_triggers, trigger_ids}; use crate::declarations::_helpers::publication::publish_projections; use crate::declarations::models::Definitions; diff --git a/crates/sqlbuild-orchestration/src/declarations/main/read_person_job.rs b/crates/sqlbuild-orchestration/src/declarations/main/read_person_job.rs index d07f82d9c0..686c8415a6 100644 --- a/crates/sqlbuild-orchestration/src/declarations/main/read_person_job.rs +++ b/crates/sqlbuild-orchestration/src/declarations/main/read_person_job.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::declarations::_helpers::job_detail::{ critical_nodes, cursor_type, declared_settings, members_in_order, snapshot_relations, diff --git a/crates/sqlbuild-orchestration/src/declarations/main/read_person_providers.rs b/crates/sqlbuild-orchestration/src/declarations/main/read_person_providers.rs index ac6c99c887..140f43a045 100644 --- a/crates/sqlbuild-orchestration/src/declarations/main/read_person_providers.rs +++ b/crates/sqlbuild-orchestration/src/declarations/main/read_person_providers.rs @@ -3,7 +3,7 @@ use serde::Deserialize; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::declarations::_helpers::job_detail::Caps; use crate::declarations::_helpers::reads::{jobs_in, with_provider_jobs}; diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/location/connection_tests.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/location/connection_tests.rs index d82453735b..dd7a5685cd 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/location/connection_tests.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/location/connection_tests.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::store::errors::ControlError; use crate::store::models::ControlTransaction; diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/plans/plan_access.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/plans/plan_access.rs index d4d486f202..0f5a11f537 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/plans/plan_access.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/plans/plan_access.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{Action, AuditContext, DefaultRole}; use crate::platform::main::work::_read_target_work::read_target_work; use crate::platform::models::{LocationWork, LocationWorkOutcome, LocationWorkRecord}; diff --git a/crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs b/crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs index b4c378456a..37771872c6 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::declarations::main::current_jobs::current_jobs; use crate::declarations::models::ServerPoolCaps; diff --git a/crates/sqlbuild-orchestration/src/platform/main/installation/read_installation.rs b/crates/sqlbuild-orchestration/src/platform/main/installation/read_installation.rs index 1ebe8141af..73a3f0f273 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/installation/read_installation.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/installation/read_installation.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::platform::_helpers::maintenance::watchdog::store_bytes; use crate::platform::models::{InstallationRecord, StorageKind, StoredInstallation}; diff --git a/crates/sqlbuild-orchestration/src/platform/main/person_reads/list_person_platform_events.rs b/crates/sqlbuild-orchestration/src/platform/main/person_reads/list_person_platform_events.rs index cf6d0ae132..55c9a33a9a 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/person_reads/list_person_platform_events.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/person_reads/list_person_platform_events.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use uuid::Uuid; -use crate::authorization::main::person_holds_target::person_holds_target; +use crate::authorization::main::decisions::person_holds_target::person_holds_target; use crate::credentials::models::{Action, DefaultRole}; use crate::platform::_helpers::health::event_history::event_history; use crate::platform::models::{PersonPlatformEvent, PersonPlatformEventPage}; diff --git a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_mirrored_totals.rs b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_mirrored_totals.rs index 7cdc22e827..f870f486b5 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_mirrored_totals.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_mirrored_totals.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use serde_json::Value; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::platform::models::MirroredTotal; use crate::store::errors::ControlError; diff --git a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_problems.rs b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_problems.rs index 3ee2d71fed..02d2bf9131 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_problems.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_problems.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use uuid::Uuid; -use crate::authorization::main::person_holds_target::person_holds_target; +use crate::authorization::main::decisions::person_holds_target::person_holds_target; use crate::credentials::models::{Action, DefaultRole}; use crate::platform::_helpers::health::problems::{late_ticks, scan_problems}; use crate::platform::models::PlatformProblems; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/publications.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/publications.rs index f7ba72e1f4..0e13f13e9a 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/publications.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/publications.rs @@ -8,7 +8,7 @@ use serde_json::Value; use tokio::sync::OnceCell; use uuid::Uuid; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::declarations::main::frozen_definitions::frozen_definitions; use crate::runs::constants::PUBLICATIONS_PER_TARGET; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs index 87164fd31f..358846377c 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs @@ -5,8 +5,8 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::json; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; -use crate::authorization::main::decide_person_scopes::decide_person_scopes; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::decide_person_scopes::decide_person_scopes; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{Action, AuditContext, DefaultRole}; use crate::runs::_helpers::lifecycle::publications::{cached_publication, current_publication}; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/cancel.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/cancel.rs index 47413fa054..a4181b4e44 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/cancel.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/cancel.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::runs::_helpers::lifecycle::change_run::change_run_in; use crate::runs::_helpers::requests::permissions::authorize_execution; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/manual_job.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/manual_job.rs index 5fbdaeec41..3e0ffa7e2f 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/manual_job.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/manual_job.rs @@ -3,9 +3,9 @@ use serde_json::json; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; -use crate::authorization::main::authorize_person::authorize_person; -use crate::authorization::main::refuse_unknown::refuse_unknown; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_person::authorize_person; +use crate::authorization::main::decisions::refuse_unknown::refuse_unknown; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::runs::_helpers::requests::permissions::authorize_execution; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/permissions.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/permissions.rs index 4d10e7f258..369f147d55 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/permissions.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/permissions.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use uuid::Uuid; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::runs::_helpers::requests::job::frozen_group_children; use crate::runs::constants::VARS_SETTING; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/plan.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/plan.rs index f624bbfd3b..cb0ca4ef81 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/plan.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/plan.rs @@ -3,8 +3,8 @@ use chrono::Duration; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::platform::constants::{LOCATION_SILENCE_SECONDS, PLAN_EXPIRY_SECONDS, PLAN_QUEUE_LIMIT}; use crate::platform::main::work::enqueue_location_work::enqueue_location_work; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/rerun.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/rerun.rs index 980a3fe273..c588b6be25 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/rerun.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/rerun.rs @@ -5,8 +5,8 @@ use std::collections::BTreeSet; use serde_json::from_value; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::runs::_helpers::requests::permissions::authorize_execution; use crate::runs::models::{RerunRequest, RunCommand, RunKind, RunOrigin, RunRequest, RunStatus}; diff --git a/crates/sqlbuild-orchestration/src/runs/main/listings/list_person_run_nodes.rs b/crates/sqlbuild-orchestration/src/runs/main/listings/list_person_run_nodes.rs index 91e8cbbf0c..90850bcb01 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/listings/list_person_run_nodes.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/listings/list_person_run_nodes.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::row_in_target::row_in_target; +use crate::authorization::main::decisions::row_in_target::row_in_target; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::runs::_helpers::lifecycle::reads::run_nodes_in; use crate::runs::models::RunNodeRecord; diff --git a/crates/sqlbuild-orchestration/src/runs/main/listings/list_person_runs.rs b/crates/sqlbuild-orchestration/src/runs/main/listings/list_person_runs.rs index 46c0249b48..2f48a4f13c 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/listings/list_person_runs.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/listings/list_person_runs.rs @@ -3,7 +3,7 @@ use crate::runs::types::RunsListing; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::runs::_helpers::lifecycle::reads::list_runs_in; use crate::runs::models::RunRecord; diff --git a/crates/sqlbuild-orchestration/src/scheduler/main/list_person_ticks.rs b/crates/sqlbuild-orchestration/src/scheduler/main/list_person_ticks.rs index ed5c77655f..a26302566f 100644 --- a/crates/sqlbuild-orchestration/src/scheduler/main/list_person_ticks.rs +++ b/crates/sqlbuild-orchestration/src/scheduler/main/list_person_ticks.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::row_in_target::row_in_target; +use crate::authorization::main::decisions::row_in_target::row_in_target; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::scheduler::_helpers::reads::ticks_in; use crate::scheduler::models::TickRecord; diff --git a/crates/sqlbuild-orchestration/src/sensors/main/read_person_sensor.rs b/crates/sqlbuild-orchestration/src/sensors/main/read_person_sensor.rs index 14ab096e2d..ebcd33716d 100644 --- a/crates/sqlbuild-orchestration/src/sensors/main/read_person_sensor.rs +++ b/crates/sqlbuild-orchestration/src/sensors/main/read_person_sensor.rs @@ -5,8 +5,8 @@ use std::collections::BTreeMap; use sqlbuild_core::redaction::main::redact_text::redact_text; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; -use crate::authorization::main::person_holds_target::person_holds_target; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::person_holds_target::person_holds_target; use crate::credentials::models::{Action, AuditContext, DefaultRole}; use crate::sensors::_helpers::facts::definition_fingerprint; use crate::sensors::models::{ diff --git a/crates/sqlbuild-orchestration/src/snapshots/main/reads/list_person_snapshots.rs b/crates/sqlbuild-orchestration/src/snapshots/main/reads/list_person_snapshots.rs index 566f70a4d8..672cb67ef8 100644 --- a/crates/sqlbuild-orchestration/src/snapshots/main/reads/list_person_snapshots.rs +++ b/crates/sqlbuild-orchestration/src/snapshots/main/reads/list_person_snapshots.rs @@ -2,8 +2,8 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; -use crate::authorization::main::person_assigns_roles::person_assigns_roles; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; +use crate::authorization::main::roles::person_assigns_roles::person_assigns_roles; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::snapshots::_helpers::published_listing::{ published_changes, published_connections, published_snapshots, diff --git a/crates/sqlbuild-orchestration/src/snapshots/main/reads/listing_read.rs b/crates/sqlbuild-orchestration/src/snapshots/main/reads/listing_read.rs index d04bcc8406..57f6b94ef7 100644 --- a/crates/sqlbuild-orchestration/src/snapshots/main/reads/listing_read.rs +++ b/crates/sqlbuild-orchestration/src/snapshots/main/reads/listing_read.rs @@ -4,7 +4,7 @@ use std::future::Future; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; diff --git a/crates/sqlbuild-orchestration/src/snapshots/main/reads/read_person_node_sql.rs b/crates/sqlbuild-orchestration/src/snapshots/main/reads/read_person_node_sql.rs index 7b8d1ed5d2..d3e16695a9 100644 --- a/crates/sqlbuild-orchestration/src/snapshots/main/reads/read_person_node_sql.rs +++ b/crates/sqlbuild-orchestration/src/snapshots/main/reads/read_person_node_sql.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use serde_json::{Value, json}; use uuid::Uuid; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::snapshots::_helpers::reading::attach_sources; diff --git a/crates/sqlbuild-orchestration/src/snapshots/main/write_sets/holds_on_nodes.rs b/crates/sqlbuild-orchestration/src/snapshots/main/write_sets/holds_on_nodes.rs index c149045542..26ff5c9380 100644 --- a/crates/sqlbuild-orchestration/src/snapshots/main/write_sets/holds_on_nodes.rs +++ b/crates/sqlbuild-orchestration/src/snapshots/main/write_sets/holds_on_nodes.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use uuid::Uuid; -use crate::authorization::main::decide_person_scopes::decide_person_scopes; +use crate::authorization::main::decisions::decide_person_scopes::decide_person_scopes; use crate::credentials::models::{Action, PermissionScope}; use crate::store::errors::ControlError; use crate::store::models::ControlTransaction; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs index 92065c1a7d..e7997ea2bf 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs @@ -6,7 +6,7 @@ use serde::Deserialize; use serde_json::json; use uuid::Uuid; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::store::errors::ControlError; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs index 840050a339..1ad4e981b4 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs @@ -5,8 +5,8 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; -use crate::authorization::main::authorize_person::authorize_person; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::runs::constants::{MEMBER_RECOVERED_EVENT, MEMBER_RETRYING_EVENT}; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check.rs index 43ffbf10b4..beeeebba87 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs index 833fcdd59f..42d1183223 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use chrono::{Duration, Utc}; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_maintenance.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_maintenance.rs index a74a92e6e8..c35229f065 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_maintenance.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_maintenance.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_microbatch_coverage.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_microbatch_coverage.rs index a89c679521..937551a38d 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_microbatch_coverage.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_microbatch_coverage.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_costs.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_costs.rs index d442f4b87b..741618f5bf 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_costs.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_costs.rs @@ -3,7 +3,7 @@ use chrono::{Duration, Utc}; use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_runs.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_runs.rs index d2481e9ad5..0c15639332 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_runs.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_runs.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::runs::models::NodeRunRecord; use crate::store::errors::ControlError; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_node_error.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_node_error.rs index 8b0db84818..c11547dd32 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_node_error.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_node_error.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use uuid::Uuid; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::runs::models::{RunChange, RunChangeRequest, RunNodeFailure}; diff --git a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_catalog.rs b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_catalog.rs index 8324b44276..b326273386 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_catalog.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_catalog.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; diff --git a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_column_lineage.rs b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_column_lineage.rs index 2c7a9a1b86..2b8f2e2cd4 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_column_lineage.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_column_lineage.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::snapshots::main::reads::read_current_record::read_current_record; use crate::snapshots::main::reads::read_snapshot_documents::read_snapshot_documents; diff --git a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_fingerprint.rs b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_fingerprint.rs index 284e1cd0a5..8f0f613f87 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_fingerprint.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_fingerprint.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::store::errors::ControlError; use crate::store::main::commit::commit; diff --git a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_node_status.rs b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_node_status.rs index 07ff3e48c6..1f7e467750 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_node_status.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_node_status.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::snapshots::main::reads::read_current_record::read_current_record; use crate::snapshots::main::reads::read_snapshot_nodes::read_snapshot_nodes; diff --git a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_statistics.rs b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_statistics.rs index f34acda4cd..d39cfe8068 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_statistics.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_statistics.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::authorize_listing::authorize_listing; +use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; diff --git a/crates/sqlbuild-orchestration/tests/api/oidc/helpers.rs b/crates/sqlbuild-orchestration/tests/api/oidc/helpers.rs index 6d5e257bf9..54d20c1e60 100644 --- a/crates/sqlbuild-orchestration/tests/api/oidc/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/oidc/helpers.rs @@ -23,7 +23,7 @@ use crate::api::models::{ApiAuthentication, HumanLogin, OidcAuthentication}; use crate::api::tests::helpers::start_api_with_authentication; use crate::api::tests::oidc_test_types::{BrowserFlow, ProviderFault, ProviderState, TestProvider}; use crate::api::types::OidcIdToken; -use crate::authorization::main::begin_authorized::begin_authorized; +use crate::authorization::main::decisions::begin_authorized::begin_authorized; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::store::errors::ControlError; use crate::store::main::commit::commit; diff --git a/crates/sqlbuild-orchestration/tests/api/plans/helpers.rs b/crates/sqlbuild-orchestration/tests/api/plans/helpers.rs index a933e0eb71..c693b359d4 100644 --- a/crates/sqlbuild-orchestration/tests/api/plans/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/plans/helpers.rs @@ -2,7 +2,7 @@ use uuid::Uuid; -use crate::authorization::main::assign_builtin_role::assign_builtin_role; +use crate::authorization::main::roles::assign_builtin_role::assign_builtin_role; use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::main::sessions::set_password::set_password; use crate::credentials::models::{ diff --git a/crates/sqlbuild-orchestration/tests/api/test_catalog_reads.rs b/crates/sqlbuild-orchestration/tests/api/test_catalog_reads.rs index 03bb9e16fd..96e8cb7bf2 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_catalog_reads.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_catalog_reads.rs @@ -5,7 +5,7 @@ use uuid::Uuid; use crate::api::tests::test_types::WarehouseMetadataTestCase; use crate::authorization::main::{ - assign_builtin_role::assign_builtin_role, bootstrap_user::bootstrap_user, + people::bootstrap_user::bootstrap_user, roles::assign_builtin_role::assign_builtin_role, }; use crate::credentials::main::{ identities::create_principal::create_principal, sessions::login_password::login_password, diff --git a/crates/sqlbuild-orchestration/tests/api/test_column_lineage.rs b/crates/sqlbuild-orchestration/tests/api/test_column_lineage.rs index 0a1d6ae2c9..c5a1123ebc 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_column_lineage.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_column_lineage.rs @@ -4,7 +4,7 @@ use serde_json::json; use uuid::Uuid; use crate::api::tests::test_types::ColumnLineageTestCase; -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::credentials::tests::location_helpers::create_location; diff --git a/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs b/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs index d03fe4e2d6..5b0ab4664f 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs @@ -11,7 +11,7 @@ use crate::api::models::{ }; use crate::api::tests::helpers::{start_api_with_authentication, stop_api}; use crate::api::tests::test_types::ExternalSessionTestCase; -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; use crate::credentials::main::{ identities::create_principal::create_principal, locations::create_location::create_location, }; diff --git a/crates/sqlbuild-orchestration/tests/api/test_location_health.rs b/crates/sqlbuild-orchestration/tests/api/test_location_health.rs index 8166d424f7..0bd69d9ce9 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_location_health.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_location_health.rs @@ -1,4 +1,4 @@ -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; use crate::credentials::main::tokens::issue_token::issue_token; use crate::credentials::models::{AuditContext, CredentialScope, DefaultRole}; use crate::platform::main::health::read_person_location_health::read_person_location_health; diff --git a/crates/sqlbuild-orchestration/tests/api/test_person_location_work.rs b/crates/sqlbuild-orchestration/tests/api/test_person_location_work.rs index 0d72ba8d3d..d45c01d9ca 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_person_location_work.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_person_location_work.rs @@ -4,7 +4,7 @@ use uuid::Uuid; use crate::api::tests::test_types::LocationWorkTestCase; use crate::authorization::main::{ - assign_builtin_role::assign_builtin_role, bootstrap_user::bootstrap_user, + people::bootstrap_user::bootstrap_user, roles::assign_builtin_role::assign_builtin_role, }; use crate::credentials::main::{ identities::create_principal::create_principal, sessions::login_password::login_password, diff --git a/crates/sqlbuild-orchestration/tests/api/test_person_plans.rs b/crates/sqlbuild-orchestration/tests/api/test_person_plans.rs index 4b45899618..2856326738 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_person_plans.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_person_plans.rs @@ -9,7 +9,7 @@ use uuid::Uuid; use crate::api::tests::plans_helpers::{ask, person, plan_request, register_instance, run_rows}; use crate::api::tests::test_types::{PlanDiffTestCase, PlanTestCase}; use crate::api::tests::work_helpers::execute; -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; use crate::credentials::models::{AuditContext, BuiltinRole}; use crate::credentials::tests::location_helpers::create_location; use crate::platform::_helpers::maintenance::retention::retain; diff --git a/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs b/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs index f5e9a3a37c..9ea504b258 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs @@ -12,7 +12,7 @@ use crate::api::tests::person_sessions_helpers::{ use crate::api::tests::person_sessions_test_types::SessionRoleCase; use crate::api::tests::test_types::LocationWorkTestCase; use crate::authorization::main::{ - assign_builtin_role::assign_builtin_role, bootstrap_user::bootstrap_user, + people::bootstrap_user::bootstrap_user, roles::assign_builtin_role::assign_builtin_role, }; use crate::credentials::main::{ identities::create_principal::create_principal, sessions::login_password::login_password, diff --git a/crates/sqlbuild-orchestration/tests/api/test_providers.rs b/crates/sqlbuild-orchestration/tests/api/test_providers.rs index 21de021109..5499a9e5ca 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_providers.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_providers.rs @@ -4,7 +4,7 @@ use serde_json::json; use uuid::Uuid; use crate::api::tests::test_types::ProvidersTestCase; -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::credentials::tests::location_helpers::create_location; diff --git a/crates/sqlbuild-orchestration/tests/api/test_reads.rs b/crates/sqlbuild-orchestration/tests/api/test_reads.rs index 6de532a2a5..e1374f9042 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_reads.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_reads.rs @@ -1,7 +1,7 @@ //! Real HTTP reads keep both location and target scope, including guessed nested resource IDs. -use crate::authorization::main::assign_builtin_role::assign_builtin_role; -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; +use crate::authorization::main::roles::assign_builtin_role::assign_builtin_role; use crate::credentials::main::identities::create_principal::create_principal; use crate::declarations::main::list_person_triggers::list_person_triggers; use crate::scheduler::tests::contracts::ticks::helpers::{calendar_text, calendar_time}; diff --git a/crates/sqlbuild-orchestration/tests/api/test_trigger_upcoming.rs b/crates/sqlbuild-orchestration/tests/api/test_trigger_upcoming.rs index f7e49509b8..fe195a3370 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_trigger_upcoming.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_trigger_upcoming.rs @@ -5,7 +5,7 @@ use serde_json::json; use uuid::Uuid; use crate::api::tests::test_types::UpcomingTestCase; -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::credentials::tests::location_helpers::create_location; use crate::declarations::main::list_person_triggers::list_person_triggers; diff --git a/crates/sqlbuild-orchestration/tests/api/warehouse_history/helpers.rs b/crates/sqlbuild-orchestration/tests/api/warehouse_history/helpers.rs index 67319966ff..d5fdc1f20c 100644 --- a/crates/sqlbuild-orchestration/tests/api/warehouse_history/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/warehouse_history/helpers.rs @@ -10,7 +10,7 @@ use crate::api::models::{ApiAuthentication, HumanLogin}; use crate::api::tests::helpers::start_api_with_authentication; use crate::api::tests::test_types::TestApi; use crate::authorization::main::{ - assign_builtin_role::assign_builtin_role, bootstrap_user::bootstrap_user, + people::bootstrap_user::bootstrap_user, roles::assign_builtin_role::assign_builtin_role, }; use crate::credentials::main::{ identities::create_principal::create_principal, sessions::login_password::login_password, diff --git a/crates/sqlbuild-orchestration/tests/credentials/roles/helpers.rs b/crates/sqlbuild-orchestration/tests/credentials/roles/helpers.rs index f7baf18137..b41c4678bd 100644 --- a/crates/sqlbuild-orchestration/tests/credentials/roles/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/credentials/roles/helpers.rs @@ -4,8 +4,8 @@ use serde_json::{Value, json}; use uuid::Uuid; use crate::authorization::main::{ - assign_builtin_role::assign_builtin_role, authorize_person::authorize_person, - bootstrap_user::bootstrap_user, + decisions::authorize_person::authorize_person, people::bootstrap_user::bootstrap_user, + roles::assign_builtin_role::assign_builtin_role, }; use crate::credentials::main::{ identities::create_principal::create_principal, sessions::login_password::login_password, diff --git a/crates/sqlbuild-orchestration/tests/credentials/test_administrators.rs b/crates/sqlbuild-orchestration/tests/credentials/test_administrators.rs index 0c76ec1d78..ccd81e2e60 100644 --- a/crates/sqlbuild-orchestration/tests/credentials/test_administrators.rs +++ b/crates/sqlbuild-orchestration/tests/credentials/test_administrators.rs @@ -5,7 +5,7 @@ use serde_json::{Value, json}; use uuid::Uuid; use crate::authorization::main::{ - bootstrap_user::bootstrap_user, change_administrator::change_administrator, + people::bootstrap_user::bootstrap_user, roles::change_administrator::change_administrator, }; use crate::credentials::main::{ identities::create_principal::create_principal, sessions::login_password::login_password, diff --git a/crates/sqlbuild-orchestration/tests/credentials/test_audit.rs b/crates/sqlbuild-orchestration/tests/credentials/test_audit.rs index b101ac85c7..44d9537cb8 100644 --- a/crates/sqlbuild-orchestration/tests/credentials/test_audit.rs +++ b/crates/sqlbuild-orchestration/tests/credentials/test_audit.rs @@ -15,8 +15,8 @@ use std::sync::{ use uuid::Uuid; use crate::authorization::main::{ - assign_builtin_role::assign_builtin_role, bootstrap_user::bootstrap_user, - read_security_audit::read_security_audit, + decisions::read_security_audit::read_security_audit, people::bootstrap_user::bootstrap_user, + roles::assign_builtin_role::assign_builtin_role, }; use crate::credentials::main::{ audit::append_audit::append_audit, identities::create_principal::create_principal, diff --git a/crates/sqlbuild-orchestration/tests/credentials/test_project_roles.rs b/crates/sqlbuild-orchestration/tests/credentials/test_project_roles.rs index e0e96d094e..1189eace22 100644 --- a/crates/sqlbuild-orchestration/tests/credentials/test_project_roles.rs +++ b/crates/sqlbuild-orchestration/tests/credentials/test_project_roles.rs @@ -6,9 +6,9 @@ use serde_json::json; use uuid::Uuid; use crate::api::models::GroupRole; -use crate::authorization::main::compile_roles::compile_roles; -use crate::authorization::main::list_role_definitions::list_role_definitions; -use crate::authorization::main::publish_group_roles::publish_group_roles; +use crate::authorization::main::roles::compile_roles::compile_roles; +use crate::authorization::main::roles::list_role_definitions::list_role_definitions; +use crate::authorization::main::roles::publish_group_roles::publish_group_roles; use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::models::{Action, RoleAssignmentRequest, RoleKey}; use crate::credentials::tests::role_helpers::{ diff --git a/crates/sqlbuild-orchestration/tests/credentials/test_recovery.rs b/crates/sqlbuild-orchestration/tests/credentials/test_recovery.rs index d95942fe54..b478faab4e 100644 --- a/crates/sqlbuild-orchestration/tests/credentials/test_recovery.rs +++ b/crates/sqlbuild-orchestration/tests/credentials/test_recovery.rs @@ -3,7 +3,9 @@ use serde_json::{Value, json}; use uuid::Uuid; -use crate::authorization::main::{bootstrap_user::bootstrap_user, grant_admin::grant_admin}; +use crate::authorization::main::{ + people::bootstrap_user::bootstrap_user, roles::grant_admin::grant_admin, +}; use crate::credentials::main::{ sessions::authenticate_bound_person::authenticate_bound_person, sessions::authenticate_session::authenticate_session, sessions::login_password::login_password, diff --git a/crates/sqlbuild-orchestration/tests/platform/test_installation.rs b/crates/sqlbuild-orchestration/tests/platform/test_installation.rs index dec6d6cc89..c63da4cb65 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_installation.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_installation.rs @@ -1,4 +1,4 @@ -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::models::AuditContext; use crate::platform::main::installation::read_installation::read_installation; diff --git a/crates/sqlbuild-orchestration/tests/platform/test_problems.rs b/crates/sqlbuild-orchestration/tests/platform/test_problems.rs index 7fdf46f88a..9b9dbce5a3 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_problems.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_problems.rs @@ -1,5 +1,5 @@ use crate::authorization::main::{ - assign_builtin_role::assign_builtin_role, bootstrap_user::bootstrap_user, + people::bootstrap_user::bootstrap_user, roles::assign_builtin_role::assign_builtin_role, }; use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::models::{AuditContext, BuiltinRole, DefaultRole, RoleAssignmentRequest}; diff --git a/crates/sqlbuild-orchestration/tests/runs/helpers.rs b/crates/sqlbuild-orchestration/tests/runs/helpers.rs index 4e0186c9b6..0118584bcd 100644 --- a/crates/sqlbuild-orchestration/tests/runs/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/runs/helpers.rs @@ -3,8 +3,8 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::api::errors::ApiError; -use crate::authorization::main::assign_builtin_role::assign_builtin_role; -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; +use crate::authorization::main::roles::assign_builtin_role::assign_builtin_role; use crate::credentials::main::identities::create_principal::create_principal; use crate::credentials::models::{AuditContext, BuiltinRole, RoleAssignmentRequest}; use crate::credentials::tests::location_helpers::create_location; diff --git a/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs b/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs index a572d3db96..a9ef53cb85 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use serde_json::json; use uuid::Uuid; -use crate::authorization::main::bootstrap_user::bootstrap_user; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::credentials::tests::location_helpers::create_location; use crate::runs::_helpers::lifecycle::reads::list_runs_in; diff --git a/crates/sqlbuild-orchestration/tests/runs/test_permissions.rs b/crates/sqlbuild-orchestration/tests/runs/test_permissions.rs index f1845cd435..daadb28d2a 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_permissions.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_permissions.rs @@ -4,8 +4,8 @@ use serde_json::json; use uuid::Uuid; use crate::authorization::main::{ - assign_builtin_role::assign_builtin_role, bootstrap_user::bootstrap_user, - change_administrator::change_administrator, + people::bootstrap_user::bootstrap_user, roles::assign_builtin_role::assign_builtin_role, + roles::change_administrator::change_administrator, }; use crate::credentials::main::{ identities::create_principal::create_principal, sessions::login_password::login_password, diff --git a/crates/sqlbuild-python-project/src/project_snapshot/main/compile_project_roles.rs b/crates/sqlbuild-python-project/src/project_snapshot/main/compile_project_roles.rs index 64f3cbcaa2..542cf1be49 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/main/compile_project_roles.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/main/compile_project_roles.rs @@ -5,7 +5,7 @@ use crate::project_snapshot::_helpers::snapshot::snapshot_roles::ROLES_FILE; use pyo3::exceptions::PyValueError; use pyo3::prelude::{PyResult, Python}; use sqlbuild_analysis::graph::models::ProjectGraph; -use sqlbuild_orchestration::authorization::main::compile_roles::compile_roles; +use sqlbuild_orchestration::authorization::main::roles::compile_roles::compile_roles; use sqlbuild_orchestration::snapshots::models::SnapshotInput; use sqlbuild_python_base::native_host::main::write_console::write_console; use std::path::Path; diff --git a/fensu.toml b/fensu.toml index 3e98e109ec..a087795f62 100644 --- a/fensu.toml +++ b/fensu.toml @@ -1363,7 +1363,7 @@ paths = ["crates/sqlbuild-orchestration/src/api/_helpers/resources/administrator reason = "Each function is one utoipa-annotated axum route: OpenAPI needs one annotated handler per operation, and each body only checks the caller's scope and calls one store operation. Scope checks and store work live in their shared owners." [[dupes.allowlist]] -paths = ["crates/sqlbuild-orchestration/src/authorization/main/list_role_definitions.rs", "crates/sqlbuild-orchestration/src/authorization/main/read_security_audit.rs", "crates/sqlbuild-orchestration/src/credentials/_helpers/active_session.rs", "crates/sqlbuild-orchestration/src/declarations/_helpers/reads.rs", "crates/sqlbuild-orchestration/src/declarations/main/published_job.rs", "crates/sqlbuild-orchestration/src/declarations/main/list_person_jobs.rs", "crates/sqlbuild-orchestration/src/declarations/main/list_person_trigger_changes.rs", "crates/sqlbuild-orchestration/src/declarations/main/list_person_triggers.rs", "crates/sqlbuild-orchestration/src/declarations/main/list_triggers.rs", "crates/sqlbuild-orchestration/src/platform/main/work/read_location_work.rs", "crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs", "crates/sqlbuild-orchestration/src/platform/main/health/location_health.rs", "crates/sqlbuild-orchestration/src/snapshots/main/reads/current_snapshot_record.rs", "crates/sqlbuild-orchestration/src/runs/main/listings/list_person_runs.rs", "crates/sqlbuild-orchestration/src/runs/main/listings/list_person_run_nodes.rs", "crates/sqlbuild-orchestration/src/runs/main/listings/list_run_nodes.rs", "crates/sqlbuild-orchestration/src/runs/main/listings/list_runs.rs", "crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs", "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs", "crates/sqlbuild-orchestration/src/scheduler/main/list_person_ticks.rs", "crates/sqlbuild-orchestration/src/store/main/read_records.rs", "crates/sqlbuild-orchestration/src/platform/main/work/location_work.rs", "crates/sqlbuild-orchestration/src/scheduler/main/list_ticks.rs", "crates/sqlbuild-orchestration/src/sensors/_helpers/attempts.rs", "crates/sqlbuild-orchestration/src/sensors/_helpers/facts.rs", "crates/sqlbuild-orchestration/src/snapshots/main/reads/read_current_record.rs", "crates/sqlbuild-orchestration/src/snapshots/main/reads/read_snapshot_documents.rs", "crates/sqlbuild-orchestration/src/snapshots/main/reads/read_snapshot_nodes.rs", "crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_catalog.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_checks.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_maintenance.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_microbatch_coverage.rs", "crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_statistics.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_runs.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_events.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statements.rs", "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/node_runs.rs"] +paths = ["crates/sqlbuild-orchestration/src/authorization/main/roles/list_role_definitions.rs", "crates/sqlbuild-orchestration/src/authorization/main/decisions/read_security_audit.rs", "crates/sqlbuild-orchestration/src/credentials/_helpers/active_session.rs", "crates/sqlbuild-orchestration/src/declarations/_helpers/reads.rs", "crates/sqlbuild-orchestration/src/declarations/main/published_job.rs", "crates/sqlbuild-orchestration/src/declarations/main/list_person_jobs.rs", "crates/sqlbuild-orchestration/src/declarations/main/list_person_trigger_changes.rs", "crates/sqlbuild-orchestration/src/declarations/main/list_person_triggers.rs", "crates/sqlbuild-orchestration/src/declarations/main/list_triggers.rs", "crates/sqlbuild-orchestration/src/platform/main/work/read_location_work.rs", "crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs", "crates/sqlbuild-orchestration/src/platform/main/health/location_health.rs", "crates/sqlbuild-orchestration/src/snapshots/main/reads/current_snapshot_record.rs", "crates/sqlbuild-orchestration/src/runs/main/listings/list_person_runs.rs", "crates/sqlbuild-orchestration/src/runs/main/listings/list_person_run_nodes.rs", "crates/sqlbuild-orchestration/src/runs/main/listings/list_run_nodes.rs", "crates/sqlbuild-orchestration/src/runs/main/listings/list_runs.rs", "crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs", "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs", "crates/sqlbuild-orchestration/src/scheduler/main/list_person_ticks.rs", "crates/sqlbuild-orchestration/src/store/main/read_records.rs", "crates/sqlbuild-orchestration/src/platform/main/work/location_work.rs", "crates/sqlbuild-orchestration/src/scheduler/main/list_ticks.rs", "crates/sqlbuild-orchestration/src/sensors/_helpers/attempts.rs", "crates/sqlbuild-orchestration/src/sensors/_helpers/facts.rs", "crates/sqlbuild-orchestration/src/snapshots/main/reads/read_current_record.rs", "crates/sqlbuild-orchestration/src/snapshots/main/reads/read_snapshot_documents.rs", "crates/sqlbuild-orchestration/src/snapshots/main/reads/read_snapshot_nodes.rs", "crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_catalog.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_checks.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_maintenance.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_microbatch_coverage.rs", "crates/sqlbuild-orchestration/src/warehouse_metadata/main/person_reads/read_person_statistics.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_runs.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_events.rs", "crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statements.rs", "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/node_runs.rs"] reason = "Each is one control-store read with its own SQL and record type. Transactions, person authorization and decoding go through the shared begin_authorized, row_in_target, query_records, read_records and query_bodies helpers; what remains alike is the call shape." [[dupes.allowlist]] From 8cd06db0fabea8d5e52a12181b9d654a912814dc Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:15:16 +0000 Subject: [PATCH 08/10] test(server): prove a non-loopback peer's username header is logged and ignored Start the server on this machine's routed address with the default trusted peers and send the username header to it, with a forwarding header claiming loopback. The server refuses both requests, logs the peer once and never logs the username. Drop history wording from the server page. --- .../tests/native_commands/test_proxy.rs | 84 ++++++++++++++++++- .../tests/native_commands/test_types.rs | 10 +++ .../sqlbuild/references/docs/cli/server.md | 4 +- website/src/content/docs/docs/cli/server.mdx | 4 +- 4 files changed, 97 insertions(+), 5 deletions(-) diff --git a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs index a72a44d1b9..6356bbb834 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs @@ -4,7 +4,9 @@ use reqwest::{Client, StatusCode, header}; use serde_json::{Value, json}; use crate::helpers::{api_ready, start_control_in, wait_for_exit}; -use crate::test_types::{ProxyCliTestCase, ProxyStartupTestCase, ServerConfigurationTestCase}; +use crate::test_types::{ + ProxyCliTestCase, ProxyRemotePeerTestCase, ProxyStartupTestCase, ServerConfigurationTestCase, +}; #[test] fn given_an_owner_configured_proxy_when_requests_carry_a_subject_then_only_explicit_people_resolve_without_sessions_or_machine_authority() @@ -327,3 +329,83 @@ fn given_an_http_proxy_origin_and_an_unconfigured_proxy_address_when_requests_ar }); } } + +#[test] +fn given_the_default_trusted_peers_when_a_non_loopback_peer_sends_the_username_header_then_it_is_ignored_and_logged_once() + { + let test_cases = [ProxyRemotePeerTestCase { + description: "a request from another address of this machine is not from loopback", + configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\n", + username: "orders-remote-reader", + expected_status: StatusCode::UNAUTHORIZED, + expected_warnings: 1, + }]; + // The address this machine routes from; connecting a UDP socket sends nothing. + let route = std::net::UdpSocket::bind("0.0.0.0:0").expect("UDP socket"); + route.connect("192.0.2.1:9").expect("a non-loopback route"); + let host = route.local_addr().expect("route address").ip().to_string(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + for test_case in test_cases { + runtime.block_on(async { + let directory = tempfile::tempdir().expect("proxy installation"); + std::fs::write( + directory.path().join("server.toml"), + test_case.configuration, + ) + .expect("server configuration"); + let mut control = start_control_in( + directory, + &[ + "server", + "--host", + &host, + "--port", + "0", + "--no-scheduler", + "--config", + "server.toml", + ], + ); + let url = api_ready(&mut control).await; + let client = Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .expect("HTTP client"); + let mut statuses = Vec::new(); + for _ in 0..2 { + let response = client + .get(format!("{url}/api/control/bootstrap")) + .header("x-forwarded-host", "control.example.com") + .header("x-forwarded-for", "127.0.0.1") + .header("x-sqb-user", test_case.username) + .send() + .await + .expect("remote request"); + statuses.push(response.status()); + } + let log = std::fs::read_to_string(&control.stderr).expect("server log"); + let warning = format!( + "warning: ignored the trusted-proxy username header x-sqb-user from {host}, which is not in [trusted_proxy] trusted_peers" + ); + assert_eq!( + ( + statuses, + log.matches(&warning).count(), + log.contains(test_case.username) + ), + ( + vec![test_case.expected_status; 2], + test_case.expected_warnings, + false + ), + "{}: {log}", + test_case.description + ); + #[cfg(unix)] + crate::helpers::terminate(&mut control).await; + }); + } +} diff --git a/crates/sqlbuild-cli/tests/native_commands/test_types.rs b/crates/sqlbuild-cli/tests/native_commands/test_types.rs index fc3fc1b52d..4b62dde3cb 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_types.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_types.rs @@ -60,6 +60,16 @@ pub(crate) struct ProxyStartupTestCase { pub(crate) expected_warnings: &'static [(&'static str, usize)], } +/// A server with the default `trusted_peers`, reached over a non-loopback address of this machine. +pub(crate) struct ProxyRemotePeerTestCase { + pub(crate) description: &'static str, + pub(crate) configuration: &'static str, + /// The username the remote requests carry, which the log must never show. + pub(crate) username: &'static str, + pub(crate) expected_status: reqwest::StatusCode, + pub(crate) expected_warnings: usize, +} + pub(crate) struct ServerConfigurationTestCase { pub(crate) description: &'static str, pub(crate) configuration: &'static str, diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md index e3018dc3d1..63a9bf3ce9 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md @@ -149,8 +149,8 @@ ProxyPassReverse "/" "http://127.0.0.1:8000/" - **Usernames are case-insensitive.** The server trims and lowercases the username, so `Admin` and `admin` are one person; your identity provider must treat them as the same account. A username must be 1 to 128 characters of `a`-`z`, `0`-`9`, `.`, `_`, `@`, `+` or `-`, starting with a - letter or digit. Keys under `[trusted_proxy.identities]` are lowercased too; before this release - they matched the header's exact text, so check that no two keys now differ only in case. + letter or digit. Keys under `[trusted_proxy.identities]` are lowercased too, so no two keys may + differ only in case. - **New people.** A provisioned person is named after their username, and an administrator grants more roles in the UI. A username that matches another principal's name in any case is refused rather than taken over; bind it under `[trusted_proxy.identities]` to sign that person in. diff --git a/website/src/content/docs/docs/cli/server.mdx b/website/src/content/docs/docs/cli/server.mdx index 6017530ebd..b825321347 100644 --- a/website/src/content/docs/docs/cli/server.mdx +++ b/website/src/content/docs/docs/cli/server.mdx @@ -129,8 +129,8 @@ ProxyPassReverse "/" "http://127.0.0.1:8000/" - **Usernames are case-insensitive.** The server trims and lowercases the username, so `Admin` and `admin` are one person; your identity provider must treat them as the same account. A username must be 1 to 128 characters of `a`-`z`, `0`-`9`, `.`, `_`, `@`, `+` or `-`, starting with a - letter or digit. Keys under `[trusted_proxy.identities]` are lowercased too; before this release - they matched the header's exact text, so check that no two keys now differ only in case. + letter or digit. Keys under `[trusted_proxy.identities]` are lowercased too, so no two keys may + differ only in case. - **New people.** A provisioned person is named after their username, and an administrator grants more roles in the UI. A username that matches another principal's name in any case is refused rather than taken over; bind it under `[trusted_proxy.identities]` to sign that person in. From b227bdb89b001fe9f68d07de4611dbaec5e6455a Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:48:07 +0000 Subject: [PATCH 09/10] fix(server): serve trusted proxy peers only under their own host names A DNS-rebinding page in a browser on a trusted-peer host reaches the server under its own host name, and could then send the username and CSRF headers. Refuse every request from a trusted peer, reads included, unless its real Host is 127.0.0.1, localhost or [::1] with any port, the host of `origin`, or a name in the new `allowed_hosts` list, which only a proxy that keeps the browser's host name needs. X-Forwarded-Host never counts. A refused Host gets 403 and is logged once with the setting that allows it. The CSRF rule and the loopback trusted_peers default are unchanged. --- .../tests/native_commands/test_proxy.rs | 56 ++++-- .../tests/native_commands/test_types.rs | 4 +- .../authentication/password_transport.rs | 30 ++- .../_helpers/authentication/proxy_settings.rs | 64 ++++++- .../_helpers/authentication/proxy_warnings.rs | 12 ++ .../_helpers/authentication/trusted_proxy.rs | 9 +- .../src/api/constants.rs | 2 + .../sqlbuild-orchestration/src/api/models.rs | 9 +- .../tests/api/person_sessions/helpers.rs | 1 + .../tests/api/proxy_provisioning/helpers.rs | 41 +++- .../tests/api/test_contracts.rs | 2 + .../tests/api/test_external_sessions.rs | 1 + .../tests/api/test_proxy.rs | 2 + .../tests/api/test_proxy_hosts.rs | 177 ++++++++++++++++++ .../tests/api/test_proxy_provisioning.rs | 44 ++--- .../tests/api/test_types.rs | 12 ++ fensu.toml | 4 +- .../sqlbuild/references/docs/cli/server.md | 21 ++- website/src/content/docs/docs/cli/server.mdx | 21 ++- 19 files changed, 417 insertions(+), 95 deletions(-) create mode 100644 crates/sqlbuild-orchestration/tests/api/test_proxy_hosts.rs diff --git a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs index 6356bbb834..1745301963 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs @@ -95,6 +95,12 @@ fn given_invalid_or_conflicting_server_configuration_when_a_standalone_server_st arguments: &[], expected_error: "requires explicit trusted peer IP addresses", }, + ServerConfigurationTestCase { + description: "an allowed host written as a URL", + configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\nallowed_hosts = [\"https://control-short\"]\n", + arguments: &[], + expected_error: "[trusted_proxy] allowed_hosts lists host names without a scheme, port or path; 'https://control-short' is not one", + }, ServerConfigurationTestCase { description: "neither an HTTP nor an HTTPS external origin", configuration: "[trusted_proxy]\norigin = \"ftp://control.example.com\"\ntrusted_peers = [\"127.0.0.1\"]\n", @@ -246,23 +252,38 @@ fn given_invalid_or_conflicting_server_configuration_when_a_standalone_server_st } #[test] -fn given_an_http_proxy_origin_and_an_unconfigured_proxy_address_when_requests_arrive_then_startup_warns_and_each_peer_is_logged_once() +fn given_a_misconfigured_proxy_when_requests_arrive_then_startup_warns_and_each_refusal_is_logged_once() { - let test_cases = [ProxyStartupTestCase { - description: "the proxy's real address differs from trusted_peers", - configuration: "[trusted_proxy]\norigin = \"http://control.example.com\"\ntrusted_peers = [\"192.0.2.1\"]\nusername_header = \"X-Example-User\"\n", - username: "orders-confidential-reader", - expected_warnings: &[ - ( - "warning: the trusted-proxy origin http://control.example.com is plain HTTP", - 1, - ), - ( - "warning: ignored the trusted-proxy username header x-example-user from 127.0.0.1, which is not in [trusted_proxy] trusted_peers", + let test_cases = [ + ProxyStartupTestCase { + description: "the proxy's real address differs from trusted_peers", + configuration: "[trusted_proxy]\norigin = \"http://control.example.com\"\ntrusted_peers = [\"192.0.2.1\"]\nusername_header = \"X-Example-User\"\n", + username: "orders-confidential-reader", + host: "127.0.0.1", + expected_status: StatusCode::UNAUTHORIZED, + expected_warnings: &[ + ( + "warning: the trusted-proxy origin http://control.example.com is plain HTTP", + 1, + ), + ( + "warning: ignored the trusted-proxy username header x-example-user from 127.0.0.1, which is not in [trusted_proxy] trusted_peers", + 1, + ), + ], + }, + ProxyStartupTestCase { + description: "a trusted peer's Host names neither this server nor allowed_hosts", + configuration: "[trusted_proxy]\norigin = \"https://control.example.com\"\nusername_header = \"X-Example-User\"\n", + username: "orders-rebound-reader", + host: "evil.example:8000", + expected_status: StatusCode::FORBIDDEN, + expected_warnings: &[( + "warning: refused a request from trusted proxy peer 127.0.0.1 with Host 'evil.example:8000', which is not a loopback name, the [trusted_proxy] origin's host or in [trusted_proxy] allowed_hosts; if your proxy keeps the browser's host name (ProxyPreserveHost On), add it to allowed_hosts", 1, - ), - ], - }]; + )], + }, + ]; let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -297,11 +318,12 @@ fn given_an_http_proxy_origin_and_an_unconfigured_proxy_address_when_requests_ar for _ in 0..2 { let response = client .get(format!("{url}/api/control/bootstrap")) + .header(header::HOST, test_case.host) .header("x-forwarded-host", "control.example.com") .header("x-example-user", test_case.username) .send() .await - .expect("untrusted proxy request"); + .expect("refused proxy request"); statuses.push(response.status()); } let log = std::fs::read_to_string(&control.stderr).expect("server log"); @@ -317,7 +339,7 @@ fn given_an_http_proxy_origin_and_an_unconfigured_proxy_address_when_requests_ar log.contains(test_case.username) ), ( - vec![StatusCode::UNAUTHORIZED; 2], + vec![test_case.expected_status; 2], test_case.expected_warnings, false ), diff --git a/crates/sqlbuild-cli/tests/native_commands/test_types.rs b/crates/sqlbuild-cli/tests/native_commands/test_types.rs index 4b62dde3cb..b0bac34d91 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_types.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_types.rs @@ -55,8 +55,10 @@ pub(crate) struct ProxyCliTestCase { pub(crate) struct ProxyStartupTestCase { pub(crate) description: &'static str, pub(crate) configuration: &'static str, - /// The username the untrusted requests carry, which the log must never show. + /// The username the refused requests carry, which the log must never show. pub(crate) username: &'static str, + pub(crate) host: &'static str, + pub(crate) expected_status: reqwest::StatusCode, pub(crate) expected_warnings: &'static [(&'static str, usize)], } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs index e516870952..930b37c4e0 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs @@ -9,20 +9,20 @@ use axum::response::{IntoResponse, Response}; use axum::{Extension, Json}; use uuid::Uuid; +use crate::api::_helpers::authentication::proxy_settings::ProxySettings; use crate::api::constants::{ EVENT_STREAM_MEDIA_TYPE, PASSWORD_COOKIE, PASSWORD_CSRF_COOKIE, PASSWORD_CSRF_HEADER, STREAM_BUFFERING_HEADER, STREAM_CACHE_CONTROL, }; use crate::api::errors::ApiError; -use crate::api::models::{ - AuthenticationDenial, BrowserOrigin, ExternalIdentityResponse, ProxyPeers, -}; +use crate::api::models::{AuthenticationDenial, BrowserOrigin, ExternalIdentityResponse}; use crate::credentials::constants::PASSWORD_SESSION_SECONDS; use crate::credentials::main::sessions::authenticate_session::authenticate_session; use crate::credentials::models::{AuditContext, AuthenticatedPerson, IssuedSession, SessionAccess}; use crate::store::errors::ControlError; use crate::store::models::ControlStore; +/// Refuses a trusted peer under another site's `Host`, as a DNS-rebinding page sends, then checks writes. pub(crate) async fn guard( Extension(origin): Extension, mut request: Request, @@ -43,11 +43,25 @@ pub(crate) async fn guard( request_id: Uuid::now_v7(), ip_address: Some(peer.ip().to_canonical()), }; - let from_proxy: bool = request + let proxy: Option> = request .extensions() - .get::() - .is_some_and(|ProxyPeers(peers)| peers.contains(&peer.ip().to_canonical())); - let allowed: bool = if from_proxy { + .get::>() + .filter(|settings| settings.trusted_peers.contains(&peer.ip().to_canonical())) + .cloned(); + if let Some(settings) = &proxy { + let host = single_header(request.headers(), header::HOST.as_str()); + if !settings.host_allowed(host) { + settings.note_refused_host(host, peer.ip().to_canonical()); + return Err(ApiError { + status: StatusCode::FORBIDDEN, + message: "the Host header does not name this server; add the proxy's host name to \ + [trusted_proxy] allowed_hosts" + .into(), + decision_id: None, + }); + } + } + let allowed: bool = if proxy.is_some() { proxy_request_allowed(&request, &origin) } else { browser_request_allowed(&request, &origin) @@ -73,7 +87,7 @@ fn browser_request_allowed(request: &Request, origin: &BrowserOrigin) -> bool { && origin_allows(request, origin) } -/// A proxied request under any host name; a write needs the origin or the CSRF header, which needs CORS. +/// A proxied request for an allowed host; a write needs the origin or the CSRF header, which needs CORS. fn proxy_request_allowed(request: &Request, origin: &BrowserOrigin) -> bool { origin_allows(request, origin) || single_header(request.headers(), PASSWORD_CSRF_HEADER) diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs index da900fb5fe..9d42df07cd 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_settings.rs @@ -4,21 +4,25 @@ use std::collections::{BTreeMap, BTreeSet}; use std::net::IpAddr; use std::sync::Mutex; +use axum::http::uri::Authority; use axum::http::{HeaderMap, HeaderName}; use uuid::Uuid; use crate::api::_helpers::authentication::proxy_warnings::{ - warn_taken_username, warn_untrusted_overflow, warn_untrusted_source, + warn_refused_host, warn_taken_username, warn_untrusted_overflow, warn_untrusted_source, }; use crate::api::constants::{ - HTTP_SCHEME, HTTPS_SCHEME, LOOPBACK_PROXY_PEERS, PROXY_NOTED_SOURCES, PROXY_PROFILE_CHARS, - PROXY_RESERVED_HEADER_PREFIX, PROXY_RESERVED_HEADERS, PROXY_USER_HEADER, PROXY_USERNAME_CHARS, + HTTP_SCHEME, HTTPS_SCHEME, LOOPBACK_PROXY_PEERS, PROXY_LOOPBACK_HOSTS, PROXY_NOTED_SOURCES, + PROXY_PROFILE_CHARS, PROXY_RESERVED_HEADER_PREFIX, PROXY_RESERVED_HEADERS, PROXY_USER_HEADER, + PROXY_USERNAME_CHARS, }; use crate::api::models::{ProxyProfile, TrustedProxyAuthentication, UnknownProxyUsers}; use crate::store::errors::ControlError; pub(crate) struct ProxySettings { pub(crate) trusted_peers: BTreeSet, + /// Lowercase host names a trusted peer's `Host` may carry, with any port. + allowed_hosts: BTreeSet, /// Canonical usernames bound to existing principals. pub(crate) identities: BTreeMap, pub(crate) username_header: HeaderName, @@ -30,6 +34,8 @@ pub(crate) struct ProxySettings { noted_sources: Mutex>, /// Usernames already logged for naming another principal. noted_usernames: Mutex>, + /// Refused `Host` values already logged. + noted_hosts: Mutex>, } /// Whether an item is logged now: the first time, or the one time the log fills up. @@ -96,6 +102,26 @@ impl ProxySettings { .into(), )); } + let origin = reqwest::Url::parse(&settings.origin).map_err(|_| { + ControlError::Invalid( + "trusted-proxy authentication requires an HTTP or HTTPS origin".into(), + ) + })?; + let origin_host = origin.host_str().map(str::to_ascii_lowercase); + let mut allowed_hosts: BTreeSet = PROXY_LOOPBACK_HOSTS + .iter() + .map(|host| (*host).to_owned()) + .chain(origin_host) + .collect(); + for host in &settings.allowed_hosts { + allowed_hosts.insert(host_name(host).ok_or_else(|| { + ControlError::Invalid(format!( + "[trusted_proxy] allowed_hosts lists host names without a scheme, port or \ + path; '{}' is not one", + host.escape_default() + )) + })?); + } let mut identities: BTreeMap = BTreeMap::new(); for (subject, principal) in settings.identities { let username = canonical_username(&subject).ok_or_else(|| { @@ -119,6 +145,7 @@ impl ProxySettings { .into_iter() .map(|peer| peer.to_canonical()) .collect(), + allowed_hosts, identities, username_header, display_name_header, @@ -134,6 +161,7 @@ impl ProxySettings { .transpose()?, noted_sources: Mutex::new(BTreeSet::new()), noted_usernames: Mutex::new(BTreeSet::new()), + noted_hosts: Mutex::new(BTreeSet::new()), }) } @@ -146,6 +174,26 @@ impl ProxySettings { } } + /// Whether a trusted peer's real `Host` is a loopback name, the origin's host or an allowed host. + pub(crate) fn host_allowed(&self, host: Option<&str>) -> bool { + host.map(str::parse::).is_some_and(|parsed| { + parsed.is_ok_and(|authority| { + !authority.as_str().contains('@') + && self + .allowed_hosts + .contains(&authority.host().to_ascii_lowercase()) + }) + }) + } + + /// Logs each refused `Host` value once, with the setting that allows it. + pub(crate) fn note_refused_host(&self, host: Option<&str>, peer: IpAddr) { + let key = host.unwrap_or_default().to_owned(); + if let Note::First = note(&self.noted_hosts, key) { + warn_refused_host(host, peer); + } + } + /// Logs each refused username that already names another principal once. pub(crate) fn note_taken_username(&self, username: &str) { if let Note::First = note(&self.noted_usernames, username.to_owned()) { @@ -197,6 +245,16 @@ fn profile_value(headers: &HeaderMap, name: &HeaderName) -> Option { usable.then(|| text.to_owned()) } +/// A configured host name, lowercased, when it carries no scheme, port, user or path. +fn host_name(value: &str) -> Option { + match value.trim().parse::() { + Ok(authority) if authority.port().is_none() && !authority.as_str().contains('@') => { + Some(authority.host().to_ascii_lowercase()) + } + Ok(_) | Err(_) => None, + } +} + fn header_name(value: &str, key: &str) -> Result { let name = HeaderName::from_bytes(value.trim().as_bytes()).map_err(|_| { ControlError::Invalid(format!("[trusted_proxy] {key} is not a valid header name")) diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs index 5a3039336e..8d06c42b7c 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs @@ -31,3 +31,15 @@ pub(crate) fn warn_taken_username(username: &str) { principal; bind it under [trusted_proxy.identities] to sign that person in" ); } + +pub(crate) fn warn_refused_host(host: Option<&str>, peer: IpAddr) { + let host = host.map_or_else( + || "(none)".to_owned(), + |host| format!("'{}'", host.escape_default()), + ); + eprintln!( + "warning: refused a request from trusted proxy peer {peer} with Host {host}, which is not \ + a loopback name, the [trusted_proxy] origin's host or in [trusted_proxy] allowed_hosts; if \ + your proxy keeps the browser's host name (ProxyPreserveHost On), add it to allowed_hosts" + ); +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs index d23f504d5b..0fc14f1dcb 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs @@ -16,7 +16,7 @@ use crate::api::_helpers::authentication::proxy_warnings::warn_plain_http_origin use crate::api::constants::HTTP_SCHEME; use crate::api::errors::ApiError; use crate::api::models::{ - BrowserLoginMethod, BrowserOrigin, ProxyLogoutUrl, ProxyPeers, TrustedProxyAuthentication, + BrowserLoginMethod, BrowserOrigin, ProxyLogoutUrl, TrustedProxyAuthentication, }; use crate::authorization::main::people::resolve_proxy_person::resolve_proxy_person; use crate::authorization::models::ProxyPerson; @@ -45,12 +45,7 @@ pub(crate) fn router( if let Some(url) = settings.logout_url.clone() { routes = routes.layer(Extension(ProxyLogoutUrl(url))); } - Ok(routes - .layer(Extension(origin)) - .layer(Extension(ProxyPeers(Arc::new( - settings.trusted_peers.clone(), - )))) - .layer(Extension(settings))) + Ok(routes.layer(Extension(origin)).layer(Extension(settings))) } /// Logs untrusted peers that send the username header before any check can refuse them. diff --git a/crates/sqlbuild-orchestration/src/api/constants.rs b/crates/sqlbuild-orchestration/src/api/constants.rs index 93c1e13b4a..cd6dcafdf7 100644 --- a/crates/sqlbuild-orchestration/src/api/constants.rs +++ b/crates/sqlbuild-orchestration/src/api/constants.rs @@ -42,6 +42,8 @@ pub(crate) const LOOPBACK_PROXY_PEERS: [std::net::IpAddr; 2] = [ std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), std::net::IpAddr::V6(std::net::Ipv6Addr::LOCALHOST), ]; +/// The `Host` names a proxy on the server's own host sends, with any port, besides the origin's. +pub(crate) const PROXY_LOOPBACK_HOSTS: [&str; 3] = ["127.0.0.1", "localhost", "[::1]"]; /// The longest proxy username, after trimming and lowercasing. pub(crate) const PROXY_USERNAME_CHARS: usize = 128; /// The longest display name or email address a proxy may report. diff --git a/crates/sqlbuild-orchestration/src/api/models.rs b/crates/sqlbuild-orchestration/src/api/models.rs index ce62356994..1296244539 100644 --- a/crates/sqlbuild-orchestration/src/api/models.rs +++ b/crates/sqlbuild-orchestration/src/api/models.rs @@ -320,6 +320,9 @@ pub struct TrustedProxyAuthentication { default = "crate::api::_helpers::authentication::proxy_settings::default_trusted_peers" )] pub trusted_peers: std::collections::BTreeSet, + /// Host names a Host-preserving proxy sends, beyond loopback names and the origin's host. + #[serde(default)] + pub allowed_hosts: Vec, /// Usernames pre-bound to existing principals; a binding wins over provisioning. #[serde(default)] pub identities: std::collections::BTreeMap, @@ -363,12 +366,6 @@ pub(crate) struct ProxyProfile { #[derive(Clone, Debug)] pub(crate) struct ProxyLogoutUrl(pub(crate) String); -/// Peers whose requests a trusted proxy authenticated, under whatever host name it serves. -#[derive(Clone, Debug)] -pub(crate) struct ProxyPeers( - pub(crate) std::sync::Arc>, -); - /// Exact issuer/subject bindings authenticate existing people; beta group mappings grant roles. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] diff --git a/crates/sqlbuild-orchestration/tests/api/person_sessions/helpers.rs b/crates/sqlbuild-orchestration/tests/api/person_sessions/helpers.rs index f5de4d0917..cd305eef0f 100644 --- a/crates/sqlbuild-orchestration/tests/api/person_sessions/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/person_sessions/helpers.rs @@ -35,6 +35,7 @@ pub(crate) async fn browser_sessions( store, ApiAuthentication { login: HumanLogin::TrustedProxy(TrustedProxyAuthentication { + allowed_hosts: Vec::new(), origin: origin.into(), trusted_peers: BTreeSet::from(["127.0.0.1".parse().expect("socket peer")]), identities: BTreeMap::from([("orders-person".into(), person)]), diff --git a/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs b/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs index fd74772ced..b9b234480a 100644 --- a/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/proxy_provisioning/helpers.rs @@ -2,9 +2,12 @@ use std::collections::{BTreeMap, BTreeSet}; +use axum::extract::ConnectInfo; use reqwest::{Client, RequestBuilder}; use serde_json::{Value, json}; +use tower::ServiceExt; +use crate::api::_helpers::authentication::configure::configure; use crate::api::models::{ ApiAuthentication, HumanLogin, TrustedProxyAuthentication, UnknownProxyUsers, }; @@ -25,6 +28,7 @@ pub(crate) fn settings( ) -> TrustedProxyAuthentication { TrustedProxyAuthentication { origin: ORIGIN.into(), + allowed_hosts: Vec::new(), trusted_peers: BTreeSet::from([trusted_peer.parse().expect("peer IP")]), identities: BTreeMap::new(), username_header: "X-Example-User".into(), @@ -35,14 +39,43 @@ pub(crate) fn settings( } } -/// `[trusted_proxy]` with only its required origin, so `trusted_peers` takes its loopback default. -pub(crate) fn default_proxy_login() -> HumanLogin { +/// `[trusted_proxy]` with its origin and `allowed_hosts`, so `trusted_peers` takes its loopback default. +pub(crate) fn proxy_login(allowed_hosts: &[&str]) -> HumanLogin { HumanLogin::TrustedProxy( - serde_json::from_value(json!({"origin": ORIGIN, "username_header": USER_HEADER})) - .expect("proxy settings with the default peers"), + serde_json::from_value(json!({ + "origin": ORIGIN, + "username_header": USER_HEADER, + "allowed_hosts": allowed_hosts, + })) + .expect("proxy settings with the default peers"), ) } +/// Sends `request` through the sign-in routes `login` configures, as if it arrived from `peer`. +pub(crate) async fn send_from_peer( + store: &ControlStore, + login: HumanLogin, + (peer, mut request): (&str, axum::http::Request), +) -> axum::response::Response { + let (_, routes, _) = configure( + store, + ApiAuthentication { + login, + ..ApiAuthentication::default() + }, + "127.0.0.1:8080".parse().expect("listener"), + ) + .await + .expect("sign-in routes"); + let peer = std::net::SocketAddr::new(peer.parse().expect("peer IP"), 40_000); + request.extensions_mut().insert(ConnectInfo(peer)); + routes + .with_state(store.clone()) + .oneshot(request) + .await + .expect("response") +} + pub(crate) async fn start(store: &ControlStore, settings: TrustedProxyAuthentication) -> TestApi { start_api_with_authentication( store, diff --git a/crates/sqlbuild-orchestration/tests/api/test_contracts.rs b/crates/sqlbuild-orchestration/tests/api/test_contracts.rs index ba12ed0de0..ea45183fa8 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_contracts.rs @@ -92,6 +92,8 @@ mod test_person_sessions; mod test_providers; #[path = "test_proxy.rs"] mod test_proxy; +#[path = "test_proxy_hosts.rs"] +mod test_proxy_hosts; #[path = "test_proxy_provisioning.rs"] mod test_proxy_provisioning; #[path = "test_publish_encoding.rs"] diff --git a/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs b/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs index 5b0ab4664f..c7b8e2b68d 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_external_sessions.rs @@ -63,6 +63,7 @@ fn given_proxy_people_when_administrators_and_roles_change_then_live_authority_h .expect("second person"); let origin = inputs["origin"].as_str().expect("origin"); let settings = TrustedProxyAuthentication { + allowed_hosts: Vec::new(), origin: origin.into(), trusted_peers: BTreeSet::from(["127.0.0.1".parse().expect("peer")]), identities: BTreeMap::from([ diff --git a/crates/sqlbuild-orchestration/tests/api/test_proxy.rs b/crates/sqlbuild-orchestration/tests/api/test_proxy.rs index 977cbce8f5..bea9d30e73 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_proxy.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_proxy.rs @@ -63,6 +63,7 @@ fn given_explicit_proxy_bindings_when_real_peers_and_live_people_are_checked_the .await .expect("known person"); let settings = TrustedProxyAuthentication { + allowed_hosts: Vec::new(), origin: value("origin").into(), trusted_peers: BTreeSet::from([test_case.trusted_peer.parse().expect("proxy IP")]), identities: BTreeMap::from([ @@ -95,6 +96,7 @@ fn given_explicit_proxy_bindings_when_real_peers_and_live_people_are_checked_the store, ApiAuthentication { login: HumanLogin::TrustedProxy(TrustedProxyAuthentication { + allowed_hosts: Vec::new(), trusted_peers: BTreeSet::from([value("untrusted_peer") .parse() .expect("untrusted IP")]), diff --git a/crates/sqlbuild-orchestration/tests/api/test_proxy_hosts.rs b/crates/sqlbuild-orchestration/tests/api/test_proxy_hosts.rs new file mode 100644 index 0000000000..e7d928ce1e --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/api/test_proxy_hosts.rs @@ -0,0 +1,177 @@ +//! A trusted proxy peer is served only under its own host names, so a DNS-rebinding page is refused. + +use axum::body::Body; +use reqwest::StatusCode; +use serde_json::json; + +use crate::api::tests::proxy_provisioning_helpers::{ + USER_HEADER, proxy_login, rows, send_from_peer, +}; +use crate::api::tests::test_types::ProxyHostTestCase; +use crate::store::main::migrate_store::migrate_store; +use crate::store::models::Parameter; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +const BOOTSTRAP: (&str, &str) = ("GET", "/api/control/bootstrap"); +const RUN: (&str, &str) = ("POST", "/api/control/runs"); + +#[test] +fn given_a_trusted_proxy_peer_when_the_host_header_names_another_site_then_the_request_is_refused() +{ + let test_cases = [ + ProxyHostTestCase { + description: "a rebinding page reads under its own host name", + allowed_hosts: &[], + peer: "127.0.0.1", + request: BOOTSTRAP, + headers: &[("host", "evil.example:8000"), ("x-sqb-csrf", "1")], + username: "orders-rebound-reader", + expected_status: StatusCode::FORBIDDEN, + expected_provisioned: false, + }, + ProxyHostTestCase { + description: "a rebinding page writes with the CSRF header", + allowed_hosts: &[], + peer: "127.0.0.1", + request: RUN, + headers: &[("host", "evil.example:8000"), ("x-sqb-csrf", "1")], + username: "orders-rebound-writer", + expected_status: StatusCode::FORBIDDEN, + expected_provisioned: false, + }, + ProxyHostTestCase { + description: "a forged X-Forwarded-Host naming the origin", + allowed_hosts: &[], + peer: "127.0.0.1", + request: BOOTSTRAP, + headers: &[ + ("host", "evil.example:8000"), + ("x-forwarded-host", "control.example.com"), + ("x-sqb-csrf", "1"), + ], + username: "orders-forwarded-host", + expected_status: StatusCode::FORBIDDEN, + expected_provisioned: false, + }, + ProxyHostTestCase { + description: "no Host header", + allowed_hosts: &[], + peer: "127.0.0.1", + request: BOOTSTRAP, + headers: &[("x-sqb-csrf", "1")], + username: "orders-no-host", + expected_status: StatusCode::FORBIDDEN, + expected_provisioned: false, + }, + ProxyHostTestCase { + description: "a stock proxy that sends the backend's IPv4 loopback Host", + allowed_hosts: &[], + peer: "127.0.0.1", + request: BOOTSTRAP, + headers: &[("host", "127.0.0.1:8000"), ("x-sqb-csrf", "1")], + username: "orders-ipv4-host", + expected_status: StatusCode::OK, + expected_provisioned: true, + }, + ProxyHostTestCase { + description: "a stock proxy that sends the backend's IPv6 loopback Host", + allowed_hosts: &[], + peer: "::1", + request: BOOTSTRAP, + headers: &[("host", "[::1]:8000"), ("x-sqb-csrf", "1")], + username: "orders-ipv6-host", + expected_status: StatusCode::OK, + expected_provisioned: true, + }, + ProxyHostTestCase { + description: "a stock proxy that sends localhost", + allowed_hosts: &[], + peer: "127.0.0.1", + request: BOOTSTRAP, + headers: &[("host", "LocalHost:8000"), ("x-sqb-csrf", "1")], + username: "orders-localhost-host", + expected_status: StatusCode::OK, + expected_provisioned: true, + }, + ProxyHostTestCase { + description: "a Host-preserving proxy under the origin's host", + allowed_hosts: &[], + peer: "127.0.0.1", + request: BOOTSTRAP, + headers: &[("host", "control.example.com"), ("x-sqb-csrf", "1")], + username: "orders-origin-host", + expected_status: StatusCode::OK, + expected_provisioned: true, + }, + ProxyHostTestCase { + description: "a preserved public Host that allowed_hosts does not list", + allowed_hosts: &[], + peer: "127.0.0.1", + request: BOOTSTRAP, + headers: &[("host", "control-short:443"), ("x-sqb-csrf", "1")], + username: "orders-unlisted-host", + expected_status: StatusCode::FORBIDDEN, + expected_provisioned: false, + }, + ProxyHostTestCase { + description: "a preserved public Host that allowed_hosts lists", + allowed_hosts: &["Control-Short"], + peer: "127.0.0.1", + request: BOOTSTRAP, + headers: &[("host", "control-short:443"), ("x-sqb-csrf", "1")], + username: "orders-listed-host", + expected_status: StatusCode::OK, + expected_provisioned: true, + }, + ]; + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + for test_case in test_cases { + let (method, path) = test_case.request; + let request = axum::http::Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json") + .header(USER_HEADER, test_case.username); + let request = test_case + .headers + .iter() + .fold(request, |request, (name, value)| { + request.header(*name, *value) + }) + .body(Body::from("{}")) + .expect("request"); + + let response = send_from_peer( + store, + proxy_login(test_case.allowed_hosts), + (test_case.peer, request), + ) + .await; + + assert_eq!( + response.status(), + test_case.expected_status, + "{}", + test_case.description + ); + assert_eq!( + rows( + store, + "SELECT COUNT(*) AS people FROM sqb_principals WHERE name = $1", + vec![Parameter::Text(test_case.username.into())], + ) + .await, + json!([{"people": i64::from(test_case.expected_provisioned)}]), + "{}: provisioned", + test_case.description + ); + } + close_test_store(fixture).await; + }); +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs b/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs index 5f21236a84..d42e518c8d 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_proxy_provisioning.rs @@ -1,19 +1,14 @@ //! A proxy that rewrites `Host` over plain HTTP signs people in, provisioning newcomers as viewers. use axum::body::Body; -use axum::extract::ConnectInfo; use reqwest::{Client, StatusCode, header}; use serde_json::{Value, json}; -use tower::ServiceExt; -use crate::api::_helpers::authentication::configure::configure; -use crate::api::models::{ - ApiAuthentication, HumanLogin, TrustedProxyAuthentication, UnknownProxyUsers, -}; +use crate::api::models::{HumanLogin, TrustedProxyAuthentication, UnknownProxyUsers}; use crate::api::tests::helpers::stop_api; use crate::api::tests::proxy_provisioning_helpers::{ - LOGOUT_URL, NAME_HEADER, ORIGIN, PUBLIC_HOST, USER_HEADER, default_proxy_login, forwarded, - rows, settings, start, + LOGOUT_URL, NAME_HEADER, ORIGIN, PUBLIC_HOST, USER_HEADER, forwarded, proxy_login, rows, + send_from_peer, settings, start, }; use crate::api::tests::test_types::{ ProxyPeerTrustTestCase, ProxyPeersDefaultTestCase, ProxyProvisioningTestCase, @@ -301,7 +296,7 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo let test_cases = [ ProxyPeerTrustTestCase { description: "IPv4 loopback peer, the default proxy on the same host", - login: default_proxy_login(), + login: proxy_login(&[]), peer: "127.0.0.1", forwarding_headers: &[], username: "orders-ipv4-loopback", @@ -310,7 +305,7 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo }, ProxyPeerTrustTestCase { description: "IPv6 loopback peer, the default proxy on the same host", - login: default_proxy_login(), + login: proxy_login(&[]), peer: "::1", forwarding_headers: &[], username: "orders-ipv6-loopback", @@ -319,7 +314,7 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo }, ProxyPeerTrustTestCase { description: "IPv4-mapped loopback peer from a dual-stack listener", - login: default_proxy_login(), + login: proxy_login(&[]), peer: "::ffff:127.0.0.1", forwarding_headers: &[], username: "orders-mapped-loopback", @@ -328,7 +323,7 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo }, ProxyPeerTrustTestCase { description: "IPv4 non-loopback peer not in trusted_peers", - login: default_proxy_login(), + login: proxy_login(&[]), peer: "192.0.2.24", forwarding_headers: &[], username: "orders-ipv4-remote", @@ -337,7 +332,7 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo }, ProxyPeerTrustTestCase { description: "IPv6 non-loopback peer not in trusted_peers", - login: default_proxy_login(), + login: proxy_login(&[]), peer: "2001:db8::24", forwarding_headers: &[], username: "orders-ipv6-remote", @@ -346,7 +341,7 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo }, ProxyPeerTrustTestCase { description: "IPv4-mapped non-loopback peer from a dual-stack listener", - login: default_proxy_login(), + login: proxy_login(&[]), peer: "::ffff:192.0.2.24", forwarding_headers: &[], username: "orders-mapped-remote", @@ -355,7 +350,7 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo }, ProxyPeerTrustTestCase { description: "IPv4 non-loopback peer claiming a loopback client in forwarding headers", - login: default_proxy_login(), + login: proxy_login(&[]), peer: "192.0.2.24", forwarding_headers: &[ ("x-forwarded-for", "127.0.0.1"), @@ -368,7 +363,7 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo }, ProxyPeerTrustTestCase { description: "IPv6 non-loopback peer claiming a loopback client in forwarding headers", - login: default_proxy_login(), + login: proxy_login(&[]), peer: "2001:db8::24", forwarding_headers: &[ ("x-forwarded-for", "::1"), @@ -405,18 +400,6 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo let store = &fixture.store; migrate_store(store).await.expect("migrate"); for test_case in test_cases { - let (_, routes, _) = configure( - store, - ApiAuthentication { - login: test_case.login, - ..ApiAuthentication::default() - }, - "127.0.0.1:8080".parse().expect("listener"), - ) - .await - .expect("sign-in routes"); - let peer = std::net::SocketAddr::new(test_case.peer.parse().expect("peer IP"), 40_000); - let application = routes.with_state(store.clone()); let request = axum::http::Request::get("/api/control/bootstrap") .header(header::HOST, PUBLIC_HOST) .header("x-forwarded-host", PUBLIC_HOST) @@ -427,10 +410,9 @@ fn given_the_default_proxy_peers_when_an_identity_header_arrives_then_only_a_loo .fold(request, |request, (name, value)| { request.header(*name, *value) }); - let mut request = request.body(Body::empty()).expect("request"); - request.extensions_mut().insert(ConnectInfo(peer)); + let request = request.body(Body::empty()).expect("request"); - let response = application.oneshot(request).await.expect("response"); + let response = send_from_peer(store, test_case.login, (test_case.peer, request)).await; assert_eq!( response.status(), diff --git a/crates/sqlbuild-orchestration/tests/api/test_types.rs b/crates/sqlbuild-orchestration/tests/api/test_types.rs index f4b3eff94f..72c8c81ca1 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_types.rs @@ -189,6 +189,18 @@ pub(crate) struct ProxyPeerTrustTestCase { pub(crate) expected_provisioned: bool, } +/// One request from a trusted proxy peer, naming a person, under one `Host` and set of headers. +pub(crate) struct ProxyHostTestCase { + pub(crate) description: &'static str, + pub(crate) allowed_hosts: &'static [&'static str], + pub(crate) peer: &'static str, + pub(crate) request: (&'static str, &'static str), + pub(crate) headers: &'static [(&'static str, &'static str)], + pub(crate) username: &'static str, + pub(crate) expected_status: reqwest::StatusCode, + pub(crate) expected_provisioned: bool, +} + pub(crate) struct ProxyPeersDefaultTestCase { pub(crate) description: &'static str, pub(crate) configuration: serde_json::Value, diff --git a/fensu.toml b/fensu.toml index a087795f62..1f4711aff1 100644 --- a/fensu.toml +++ b/fensu.toml @@ -1929,8 +1929,8 @@ reason = "Locations, workers and remote publication share this client; it warns [[targets.rust.rule_exceptions]] rule = "FPRSH011" path = "crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs" -symbols = ["warn_plain_http_origin", "warn_untrusted_source", "warn_untrusted_overflow", "warn_taken_username"] -reason = "The server's operator reads trusted-proxy misconfiguration on stderr: a plain-HTTP origin at start-up, and once each the untrusted peers that send the username header and the usernames refused because another principal holds the name. Untrusted header values are never printed." +symbols = ["warn_plain_http_origin", "warn_untrusted_source", "warn_untrusted_overflow", "warn_taken_username", "warn_refused_host"] +reason = "The server's operator reads trusted-proxy misconfiguration on stderr: a plain-HTTP origin at start-up, and once each the untrusted peers that send the username header, the usernames refused because another principal holds the name, and the escaped Host values a trusted peer was refused under, so they can be added to allowed_hosts. Untrusted peers' header values are never printed." [[targets.rust.rule_exceptions]] rule = "FPRSS201" diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md index 63a9bf3ce9..c84cb45f05 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md @@ -68,7 +68,7 @@ executable = "/usr/local/bin/sqb" | `[server]` | `host` (default `127.0.0.1`), `port` (`8000`), `database_env` (`SQLBUILD_CONTROL_DATABASE_URL`), `password_origin`, `default_role` (`none`), `scheduler` (`true`) | | `[retention]` | `statistics_days`, `audit_days`, `snapshot_count`, `run_log_days`, `run_log_count`, `state_history_versions`; see [Set retention](#set-retention) | | `[oidc]` | `origin`, `issuer`, `client_id`, `identities`, and optionally `client_secret_env`, `certificate_authority`, `groups_claim` and `group_roles` | -| `[trusted_proxy]` | `origin`, and optionally `trusted_peers` (`127.0.0.1` and `::1`), `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | +| `[trusted_proxy]` | `origin`, and optionally `trusted_peers` (`127.0.0.1` and `::1`), `allowed_hosts`, `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | | `[[launchers.docker]]` | `location`, `target`, `server_url`, `max_workers`, `socket`, `location_container`, `executable`, and optional `run` and `pool_caps` tables; see [Limit worker containers](#limit-worker-containers) | | `[[launchers.local]]` | `location`, `target`, `server_url`, `max_workers`, absolute `project_dir` and `executable` paths, and an optional `pool_caps` table | @@ -121,15 +121,17 @@ proxy_logout_url = "https://sign-in.example.com/logout" | --- | --- | | `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | | `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6, so any process on the server's host can send the header and sign in as anyone. Setting `trusted_peers` narrows this to the addresses you list: a proxy on another host, listed by its own address, keeps local processes out. The server takes the peer from the connection, never from `X-Forwarded-For` or `Forwarded`. | +| `allowed_hosts` | Further host names the proxy sends in `Host`, needed only when it keeps the browser's host name, such as Apache with `ProxyPreserveHost On`. List every name people reach the server under, without a scheme or port. | | `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | | `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | | `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | | `proxy_logout_url` | Where the UI's **Sign out** link goes. Only the proxy can end its own sign-in, so without this key the UI shows no sign-out link. | | `[trusted_proxy.identities]` | Optional: binds a username to a principal you already created with `sqb admin create-principal`. | -The proxy must authenticate every request, then set every identity header you configured itself. -A header the proxy leaves alone passes through from the browser, so set the username header and -set or unset the display name and email headers on every request. With Apache on the same host, +Turn on the proxy's authentication for every location it forwards to the server, and have the proxy +set every identity header you configured itself. A header the proxy leaves alone passes through +from the browser, so set the username header and set or unset the display name and email headers +on every request. With Apache on the same host, forwarding port 80 to the server on port 8000: ```apache @@ -158,10 +160,13 @@ ProxyPassReverse "/" "http://127.0.0.1:8000/" doesn't remove people already provisioned. Disable a principal to remove their access. Removing someone at the proxy doesn't end their `sqb login` sessions: they last until they expire or the principal is disabled. -- **Host names and writes.** The proxy can serve the UI under any host name, such as a short name, - the full name or an IP address. A browser write is accepted when it carries the `X-SQB-CSRF` - header, which the UI always sends and which a page on another site cannot send, or when its - `Origin` header is exactly `origin`. The server allows no cross-origin requests. +- **Host names.** A request from a trusted peer must carry a `Host` of `127.0.0.1`, `localhost`, + `[::1]` or the host of `origin`, with any port, or a name in `allowed_hosts`; the server ignores + `X-Forwarded-Host` here. A proxy that sends the backend's address, as Apache does by default, + needs no `allowed_hosts`. Any other `Host` gets `403 Forbidden`, and the server logs it once. +- **Writes.** A browser write is accepted when it carries the `X-SQB-CSRF` header, which the UI + always sends and which a page on another site cannot send, or when its `Origin` header is exactly + `origin`. The server allows no cross-origin requests. - **Finding the proxy's address.** When a request carrying the username header comes from a peer that is not in `trusted_peers`, the server ignores the header and logs the peer once, without the header's value: diff --git a/website/src/content/docs/docs/cli/server.mdx b/website/src/content/docs/docs/cli/server.mdx index b825321347..9a52daffd4 100644 --- a/website/src/content/docs/docs/cli/server.mdx +++ b/website/src/content/docs/docs/cli/server.mdx @@ -48,7 +48,7 @@ executable = "/usr/local/bin/sqb" | `[server]` | `host` (default `127.0.0.1`), `port` (`8000`), `database_env` (`SQLBUILD_CONTROL_DATABASE_URL`), `password_origin`, `default_role` (`none`), `scheduler` (`true`) | | `[retention]` | `statistics_days`, `audit_days`, `snapshot_count`, `run_log_days`, `run_log_count`, `state_history_versions`; see [Set retention](#set-retention) | | `[oidc]` | `origin`, `issuer`, `client_id`, `identities`, and optionally `client_secret_env`, `certificate_authority`, `groups_claim` and `group_roles` | -| `[trusted_proxy]` | `origin`, and optionally `trusted_peers` (`127.0.0.1` and `::1`), `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | +| `[trusted_proxy]` | `origin`, and optionally `trusted_peers` (`127.0.0.1` and `::1`), `allowed_hosts`, `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | | `[[launchers.docker]]` | `location`, `target`, `server_url`, `max_workers`, `socket`, `location_container`, `executable`, and optional `run` and `pool_caps` tables; see [Limit worker containers](#limit-worker-containers) | | `[[launchers.local]]` | `location`, `target`, `server_url`, `max_workers`, absolute `project_dir` and `executable` paths, and an optional `pool_caps` table | @@ -101,15 +101,17 @@ proxy_logout_url = "https://sign-in.example.com/logout" | --- | --- | | `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | | `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6, so any process on the server's host can send the header and sign in as anyone. Setting `trusted_peers` narrows this to the addresses you list: a proxy on another host, listed by its own address, keeps local processes out. The server takes the peer from the connection, never from `X-Forwarded-For` or `Forwarded`. | +| `allowed_hosts` | Further host names the proxy sends in `Host`, needed only when it keeps the browser's host name, such as Apache with `ProxyPreserveHost On`. List every name people reach the server under, without a scheme or port. | | `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | | `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | | `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | | `proxy_logout_url` | Where the UI's **Sign out** link goes. Only the proxy can end its own sign-in, so without this key the UI shows no sign-out link. | | `[trusted_proxy.identities]` | Optional: binds a username to a principal you already created with `sqb admin create-principal`. | -The proxy must authenticate every request, then set every identity header you configured itself. -A header the proxy leaves alone passes through from the browser, so set the username header and -set or unset the display name and email headers on every request. With Apache on the same host, +Turn on the proxy's authentication for every location it forwards to the server, and have the proxy +set every identity header you configured itself. A header the proxy leaves alone passes through +from the browser, so set the username header and set or unset the display name and email headers +on every request. With Apache on the same host, forwarding port 80 to the server on port 8000: ```apache @@ -138,10 +140,13 @@ ProxyPassReverse "/" "http://127.0.0.1:8000/" doesn't remove people already provisioned. Disable a principal to remove their access. Removing someone at the proxy doesn't end their `sqb login` sessions: they last until they expire or the principal is disabled. -- **Host names and writes.** The proxy can serve the UI under any host name, such as a short name, - the full name or an IP address. A browser write is accepted when it carries the `X-SQB-CSRF` - header, which the UI always sends and which a page on another site cannot send, or when its - `Origin` header is exactly `origin`. The server allows no cross-origin requests. +- **Host names.** A request from a trusted peer must carry a `Host` of `127.0.0.1`, `localhost`, + `[::1]` or the host of `origin`, with any port, or a name in `allowed_hosts`; the server ignores + `X-Forwarded-Host` here. A proxy that sends the backend's address, as Apache does by default, + needs no `allowed_hosts`. Any other `Host` gets `403 Forbidden`, and the server logs it once. +- **Writes.** A browser write is accepted when it carries the `X-SQB-CSRF` header, which the UI + always sends and which a page on another site cannot send, or when its `Origin` header is exactly + `origin`. The server allows no cross-origin requests. - **Finding the proxy's address.** When a request carrying the username header comes from a peer that is not in `trusted_peers`, the server ignores the header and logs the peer once, without the header's value: From 7d1b5169504505f87025a9fb5d6cbcf6171c0a84 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:02:31 +0000 Subject: [PATCH 10/10] docs(server): a proxy on another host lists its backend address in allowed_hosts A stock proxy on another host forwards with its backend address as Host, which is not a loopback name, so it needs allowed_hosts too. Say so in the docs and in the refused-Host warning. --- crates/sqlbuild-cli/tests/native_commands/test_proxy.rs | 2 +- .../src/api/_helpers/authentication/proxy_warnings.rs | 3 ++- .../.agents/skills/sqlbuild/references/docs/cli/server.md | 7 ++++--- website/src/content/docs/docs/cli/server.mdx | 7 ++++--- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs index 1745301963..ed853fbb51 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs @@ -279,7 +279,7 @@ fn given_a_misconfigured_proxy_when_requests_arrive_then_startup_warns_and_each_ host: "evil.example:8000", expected_status: StatusCode::FORBIDDEN, expected_warnings: &[( - "warning: refused a request from trusted proxy peer 127.0.0.1 with Host 'evil.example:8000', which is not a loopback name, the [trusted_proxy] origin's host or in [trusted_proxy] allowed_hosts; if your proxy keeps the browser's host name (ProxyPreserveHost On), add it to allowed_hosts", + "warning: refused a request from trusted proxy peer 127.0.0.1 with Host 'evil.example:8000', which is not a loopback name, the [trusted_proxy] origin's host or in [trusted_proxy] allowed_hosts; if your proxy keeps the browser's host name (ProxyPreserveHost On) or forwards to this server by another name or address, add it to allowed_hosts", 1, )], }, diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs index 8d06c42b7c..d2a5d2f39b 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs @@ -40,6 +40,7 @@ pub(crate) fn warn_refused_host(host: Option<&str>, peer: IpAddr) { eprintln!( "warning: refused a request from trusted proxy peer {peer} with Host {host}, which is not \ a loopback name, the [trusted_proxy] origin's host or in [trusted_proxy] allowed_hosts; if \ - your proxy keeps the browser's host name (ProxyPreserveHost On), add it to allowed_hosts" + your proxy keeps the browser's host name (ProxyPreserveHost On) or forwards to this \ + server by another name or address, add it to allowed_hosts" ); } diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md index c84cb45f05..67054f7e52 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md @@ -121,7 +121,7 @@ proxy_logout_url = "https://sign-in.example.com/logout" | --- | --- | | `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | | `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6, so any process on the server's host can send the header and sign in as anyone. Setting `trusted_peers` narrows this to the addresses you list: a proxy on another host, listed by its own address, keeps local processes out. The server takes the peer from the connection, never from `X-Forwarded-For` or `Forwarded`. | -| `allowed_hosts` | Further host names the proxy sends in `Host`, needed only when it keeps the browser's host name, such as Apache with `ProxyPreserveHost On`. List every name people reach the server under, without a scheme or port. | +| `allowed_hosts` | Further host names the proxy sends in `Host`, without a scheme or port. A proxy that keeps the browser's host name, such as Apache with `ProxyPreserveHost On`, needs every name people reach the server under. A proxy on another host needs the name or address it forwards to, such as `10.0.0.2`. | | `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | | `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | | `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | @@ -162,8 +162,9 @@ ProxyPassReverse "/" "http://127.0.0.1:8000/" or the principal is disabled. - **Host names.** A request from a trusted peer must carry a `Host` of `127.0.0.1`, `localhost`, `[::1]` or the host of `origin`, with any port, or a name in `allowed_hosts`; the server ignores - `X-Forwarded-Host` here. A proxy that sends the backend's address, as Apache does by default, - needs no `allowed_hosts`. Any other `Host` gets `403 Forbidden`, and the server logs it once. + `X-Forwarded-Host` here. A proxy on the same host that forwards to `127.0.0.1`, `localhost` or + `[::1]`, as Apache does by default, needs no `allowed_hosts`. Any other `Host` gets + `403 Forbidden`, and the server logs it once. - **Writes.** A browser write is accepted when it carries the `X-SQB-CSRF` header, which the UI always sends and which a page on another site cannot send, or when its `Origin` header is exactly `origin`. The server allows no cross-origin requests. diff --git a/website/src/content/docs/docs/cli/server.mdx b/website/src/content/docs/docs/cli/server.mdx index 9a52daffd4..845cd2ec22 100644 --- a/website/src/content/docs/docs/cli/server.mdx +++ b/website/src/content/docs/docs/cli/server.mdx @@ -101,7 +101,7 @@ proxy_logout_url = "https://sign-in.example.com/logout" | --- | --- | | `origin` | The URL people open, such as `https://control.example.com`. `http://` works too: the server warns at start-up, and `https://` is recommended. | | `trusted_peers` | The proxy's IP addresses. Without this key the server trusts `127.0.0.1` and `::1`, for a proxy on the same host that connects to `localhost` over either IPv4 or IPv6, so any process on the server's host can send the header and sign in as anyone. Setting `trusted_peers` narrows this to the addresses you list: a proxy on another host, listed by its own address, keeps local processes out. The server takes the peer from the connection, never from `X-Forwarded-For` or `Forwarded`. | -| `allowed_hosts` | Further host names the proxy sends in `Host`, needed only when it keeps the browser's host name, such as Apache with `ProxyPreserveHost On`. List every name people reach the server under, without a scheme or port. | +| `allowed_hosts` | Further host names the proxy sends in `Host`, without a scheme or port. A proxy that keeps the browser's host name, such as Apache with `ProxyPreserveHost On`, needs every name people reach the server under. A proxy on another host needs the name or address it forwards to, such as `10.0.0.2`. | | `username_header` | The header naming the signed-in person, `X-SQB-User` by default. | | `display_name_header`, `email_header` | Optional headers whose values the UI shows. The server doesn't store them. | | `unknown_users` | `provision_viewer` (default) gives a person signing in for the first time an account with the `viewer` role; `reject` refuses them. | @@ -142,8 +142,9 @@ ProxyPassReverse "/" "http://127.0.0.1:8000/" or the principal is disabled. - **Host names.** A request from a trusted peer must carry a `Host` of `127.0.0.1`, `localhost`, `[::1]` or the host of `origin`, with any port, or a name in `allowed_hosts`; the server ignores - `X-Forwarded-Host` here. A proxy that sends the backend's address, as Apache does by default, - needs no `allowed_hosts`. Any other `Host` gets `403 Forbidden`, and the server logs it once. + `X-Forwarded-Host` here. A proxy on the same host that forwards to `127.0.0.1`, `localhost` or + `[::1]`, as Apache does by default, needs no `allowed_hosts`. Any other `Host` gets + `403 Forbidden`, and the server logs it once. - **Writes.** A browser write is accepted when it carries the `X-SQB-CSRF` header, which the UI always sends and which a page on another site cannot send, or when its `Origin` header is exactly `origin`. The server allows no cross-origin requests.