diff --git a/Cargo.lock b/Cargo.lock index 7aa213651..26a2759cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1691,6 +1691,7 @@ dependencies = [ "extenddb-engine", "extenddb-server", "extenddb-storage", + "extenddb-storage-sqlite", "futures", "libc", "rcgen", @@ -1698,11 +1699,13 @@ dependencies = [ "serde", "serde_json", "sqlx", + "tempfile", "time", "tokio", "toml", "tracing", "tracing-subscriber", + "zeroize", ] [[package]] @@ -1718,6 +1721,7 @@ dependencies = [ "extenddb-core", "futures", "hex", + "libc", "proptest", "serde_json", "sha2 0.10.9", @@ -1862,6 +1866,7 @@ dependencies = [ "tracing-subscriber", "unicode-properties", "uuid", + "zeroize", ] [[package]] diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index 6398e13ca..e9d2cf1d9 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -41,6 +41,9 @@ tracing-subscriber = { workspace = true } base64 = { workspace = true } rcgen = { workspace = true } rustls = { workspace = true } +# The connection string that `encryption-key reset` and `set-data-connection` +# read from standard input, wiped when it drops. +zeroize = { workspace = true } # Daemon mode (double-fork, PID files, SIGTERM) is POSIX-only; on Windows the # server runs with `serve --foreground` under an external supervisor. @@ -50,3 +53,6 @@ libc = { workspace = true } [dev-dependencies] async-trait = { workspace = true } +# The encryption-key commands' tests run on a SQLite file catalog. +extenddb-storage-sqlite = { path = "../storage-sqlite" } +tempfile = "3" diff --git a/crates/app/src/cmd_backup.rs b/crates/app/src/cmd_backup.rs index 7fe6c0311..e99e605e1 100644 --- a/crates/app/src/cmd_backup.rs +++ b/crates/app/src/cmd_backup.rs @@ -659,6 +659,7 @@ async fn open_catalog( options.beside_server = mode == Mode::Read; options.startup_recovery = false; options.command = Some(command); + options.key_source = crate::util::command_key_source(app_config)?; let mut storage_config = app_config.storage.clone(); storage_config.set_instance_id(&format!( "{}:backup-command", diff --git a/crates/app/src/cmd_catalog_check.rs b/crates/app/src/cmd_catalog_check.rs index 91744c1de..3693d2f20 100755 --- a/crates/app/src/cmd_catalog_check.rs +++ b/crates/app/src/cmd_catalog_check.rs @@ -77,6 +77,7 @@ pub async fn run(args: CatalogCheckArgs) -> anyhow::Result<()> { let Some((data_conn_str,)) = data_conn else { anyhow::bail!("No data database connection string in settings. Run `extenddb init`."); }; + let data_conn_str = data_connection_text(&catalog_pool, &app_config, data_conn_str).await?; let data_pool = PgPoolOptions::new() .max_connections(2) .connect(&data_conn_str) @@ -214,3 +215,48 @@ pub async fn run(args: CatalogCheckArgs) -> anyhow::Result<()> { Ok(()) } + +/// The data database connection string that the row `stored` holds: the +/// row as it is in a catalog without a key ring; with a ring, the row +/// decrypted under a DEK of the ring, which the KEK of `[auth.encryption] +/// key_file` opens (RFC-0000 section 12). A row that no DEK opens is +/// refused, plaintext included, as every reader but `switch` refuses it. +async fn data_connection_text( + catalog: &sqlx::PgPool, + app_config: &config::AppConfig, + stored: String, +) -> anyhow::Result> { + use extenddb_storage::key_ring::{KEY_RING_SETTING, open_ring}; + use extenddb_storage::secret_keys::CATALOG_ID_SETTING; + use extenddb_storage::server_components::KeySource; + + let setting = async |key: &str| -> anyhow::Result> { + let row: Option<(String,)> = sqlx::query_as("SELECT value FROM settings WHERE key = $1") + .bind(key) + .fetch_optional(catalog) + .await?; + Ok(row.map(|(value,)| value)) + }; + let Some(ring) = setting(KEY_RING_SETTING).await? else { + return Ok(zeroize::Zeroizing::new(stored)); + }; + let KeySource::Kek(kek) = extenddb_server::key_file::key_source(&app_config.auth.encryption) + .map_err(anyhow::Error::msg)? + else { + anyhow::bail!( + "The catalog has a key ring, so its data database connection string is encrypted. \ + Set [auth.encryption] key_file to the KEK file that the ring names" + ); + }; + let catalog_id = setting(CATALOG_ID_SETTING).await?; + let open = open_ring(&ring, catalog_id.as_deref(), &kek).map_err(|e| anyhow::anyhow!("{e}"))?; + open.deks + .iter() + .find_map(|dek| dek.decrypt_setting(&stored).ok()) + .ok_or_else(|| { + anyhow::anyhow!( + "No DEK of the key ring opens the data_database_connection_string row. Run \ + `extenddb encryption-key status`" + ) + }) +} diff --git a/crates/app/src/cmd_encryption_key.rs b/crates/app/src/cmd_encryption_key.rs new file mode 100644 index 000000000..d8223602b --- /dev/null +++ b/crates/app/src/cmd_encryption_key.rs @@ -0,0 +1,550 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `extenddb encryption-key`: the key commands of RFC-0000 section 8. +//! +//! `status`, `rewrap` and `set-data-connection` may run beside the server. +//! `switch`, `rotate` and `reset` run while every server is stopped: they take +//! the migration lock as `migrate --yes` does, wait up to `--lock-timeout` +//! for it, and exit 6 when it stays held. Without `--yes` a command prints +//! what it would do and writes nothing. +//! +//! The checks and the writes are the storage crate's +//! ([`extenddb_storage::key_commands`]). This module reads the configuration +//! and the KEK file (through the file rule), sets up the locked key store, +//! opens the stores, and prints what a command found or did. Nothing it +//! prints holds a secret, a key or a connection string. +//! +//! Exit status: 0 done, nothing to do, or a preview; 1 refused or failed; 6 +//! the lock was not free within `--lock-timeout`; 3, 4 or 5 a catalog whose +//! migrations are not current, with the code `migrate` gives it. On +//! PostgreSQL `status` does not check the migrations, and `rewrap` and +//! `set-data-connection` check those of the catalog database. + +use std::time::Duration; + +use clap::{Args, Subcommand}; +use extenddb_server::key_file::{COMMAND_SLOTS, KeyFile, init_key_store}; +use extenddb_storage::key_commands::{self, KekFile, KeyCommandError, KeyStores, RunFlags}; +use extenddb_storage::management_store::{ManagementStore, SettingsStore}; +use extenddb_storage::migrations::{CatalogMigrations, CatalogStatus, MigrationError, Target}; +use extenddb_storage::server_components::KeySource; +use zeroize::Zeroizing; + +use text::{outcome_text, status_text}; + +#[derive(Args)] +pub struct EncryptionKeyArgs { + #[command(subcommand)] + command: Command, +} + +/// The option every command takes. +#[derive(Args)] +struct Common { + /// Path to configuration file (default: extenddb.toml) + #[arg(short, long)] + config: Option, +} + +/// The options of a command that writes. +#[derive(Args)] +struct Write { + #[command(flatten)] + common: Common, + /// Write. Without it the command prints what it would do and writes + /// nothing + #[arg(long)] + yes: bool, +} + +/// The options of a command that runs while every server is stopped. +#[derive(Args)] +struct Offline { + #[command(flatten)] + write: Write, + /// Seconds to wait for a server or a migration to release the catalog + /// before exiting 6 (default 60, at most 86400) + #[arg(long, value_name = "SECONDS", value_parser = clap::value_parser!(u64).range(0..=86_400))] + lock_timeout: Option, +} + +/// The options of `switch` and `rotate` that section 8.5 and the common +/// rules give. +#[derive(Args)] +struct PassArgs { + /// Treat a catalog key that appeared after the switch finished as an old + /// key, and re-encrypt the stored secrets under it. Read the list that + /// `encryption-key status` prints first + #[arg(long)] + accept_catalog_key: bool, + /// Leave the stored secrets that no key opens as they are, and list them + #[arg(long)] + keep_unopenable: bool, +} + +#[derive(Subcommand)] +enum Command { + /// Print the key source, the KEK id, the DEK ids and the stored secrets + /// per key. Writes nothing + Status(Common), + /// Switch from the catalog key to a KEK file. Every server must be stopped + Switch { + #[command(flatten)] + offline: Offline, + /// The KEK file to switch to + #[arg(long, value_name = "PATH")] + key_file: String, + #[command(flatten)] + pass: PassArgs, + }, + /// Wrap the DEK under a new KEK. Rewrites the key ring only, beside a + /// running server + Rewrap { + #[command(flatten)] + write: Write, + /// The new KEK file + #[arg(long, value_name = "PATH")] + key_file: String, + }, + /// Replace the DEK and re-encrypt every stored secret under the new one. + /// Every server must be stopped + Rotate { + #[command(flatten)] + offline: Offline, + #[command(flatten)] + pass: PassArgs, + }, + /// Delete every access key and session and write a new key ring, for a + /// restored catalog whose KEK is lost. Every server must be stopped + Reset { + #[command(flatten)] + offline: Offline, + /// The new KEK file + #[arg(long, value_name = "PATH")] + key_file: String, + /// Required: every access key and every session is deleted + #[arg(long)] + discard_secrets: bool, + }, + /// PostgreSQL only: read a connection string from standard input and + /// write it as the data database connection string, encrypted under the + /// DEK + SetDataConnection(Write), +} + +/// Why a command stopped, with its exit status. +#[derive(Debug)] +struct Failure { + code: u8, + message: String, +} + +impl Failure { + fn new(message: impl std::fmt::Display) -> Self { + Self { + code: extenddb_storage::migrations::exit::ERROR, + message: message.to_string(), + } + } +} + +impl From for Failure { + fn from(e: MigrationError) -> Self { + Self { + code: e.exit_code(), + message: e.to_string(), + } + } +} + +impl From for Failure { + fn from(e: KeyCommandError) -> Self { + Self::new(e) + } +} + +impl From for Failure { + fn from(e: anyhow::Error) -> Self { + Self::new(format!("{e:#}")) + } +} + +/// Run `extenddb encryption-key`; returns the exit status. +pub async fn run(args: EncryptionKeyArgs) -> anyhow::Result { + match command(args.command).await { + Ok(()) => Ok(extenddb_storage::migrations::exit::OK), + Err(failure) => { + eprintln!("Error: {}", failure.message); + Ok(failure.code) + } + } +} + +/// The configuration a command reads, and the deployment it names. +struct Context { + config: extenddb_config::AppConfig, + target: Target, +} + +impl Context { + fn load(common: &Common) -> Result { + let (config, _) = crate::util::command_config(common.config.as_deref())?; + let target = Target::at(config.storage.connection_config()); + Ok(Self { config, target }) + } + + /// The KEK file the configuration names, for `rewrap`, `rotate` and + /// `set-data-connection`, which open the ring with it. + fn configured_kek(&self, command: &str) -> Result { + self.config + .auth + .encryption + .key_file_path() + .map(KeyFile) + .ok_or_else(|| { + Failure::new(format!( + "`encryption-key {command}` opens the key ring with the KEK in \ + [auth.encryption] key_file, which this configuration does not set" + )) + }) + } + + fn key_file_configured(&self) -> bool { + self.config.auth.encryption.key_file.is_some() + } + + /// Put the KEK of `kek`, read through the file rule, on the target that + /// the migration backend opens: on PostgreSQL it opens the data + /// connection string row of a catalog with a key ring (RFC-0000 section + /// 12). + fn use_kek(&mut self, kek: &KeyFile) -> Result<(), Failure> { + let kek = extenddb_server::key_file::read_key_file(&kek.0).map_err(Failure::new)?; + self.target.key_source = KeySource::Kek(kek); + Ok(()) + } + + /// Set up the locked key store before any key is read (RFC-0000 section + /// 7, the last rows). A command that reads a KEK file holds a KEK. + fn init_key_store(&self, kek_in_use: bool) -> Result<(), Failure> { + let protection = init_key_store( + kek_in_use, + self.config.auth.encryption.require_locked_memory, + COMMAND_SLOTS, + ) + .map_err(Failure::new)?; + tracing::info!("Locked key store: {protection}"); + Ok(()) + } +} + +async fn command(command: Command) -> Result<(), Failure> { + match command { + Command::Status(common) => { + let cx = Context::load(&common)?; + let kek = cx.config.auth.encryption.key_file_path().map(KeyFile); + cx.init_key_store(kek.is_some())?; + let stores = Stores::open(&cx.target, false).await?; + let report = + key_commands::status(stores.view(), kek.as_ref().map(|k| k as &dyn KekFile)) + .await?; + print!("{}", status_text(&report)); + Ok(()) + } + Command::Switch { + offline, + key_file, + pass, + } => { + let mut cx = Context::load(&offline.write.common)?; + cx.init_key_store(true)?; + let kek = KeyFile(key_file); + cx.use_kek(&kek)?; + // The one caller whose backend accepts the plaintext connection + // string row of an unfinished switch (section 12). + cx.target.plaintext_data_connection = true; + let flags = RunFlags { + yes: offline.write.yes, + keep_unopenable: pass.keep_unopenable, + accept_catalog_key: pass.accept_catalog_key, + key_file_configured: cx.key_file_configured(), + }; + let outcome = locked( + migrations()?, + &cx.target, + offline.lock_timeout, + None, + async |stores| key_commands::switch(stores, &kek, flags).await, + ) + .await?; + print!("{}", outcome_text("switch", &outcome)); + Ok(()) + } + Command::Rewrap { write, key_file } => { + let cx = Context::load(&write.common)?; + let current = cx.configured_kek("rewrap")?; + cx.init_key_store(true)?; + let stores = Stores::open(&cx.target, true).await?; + let new = KeyFile(key_file); + let outcome = key_commands::rewrap(stores.view(), ¤t, &new, write.yes).await?; + print!("{}", outcome_text("rewrap", &outcome)); + Ok(()) + } + Command::Rotate { offline, pass } => { + let mut cx = Context::load(&offline.write.common)?; + let kek = cx.configured_kek("rotate")?; + cx.init_key_store(true)?; + cx.use_kek(&kek)?; + let flags = RunFlags { + yes: offline.write.yes, + keep_unopenable: pass.keep_unopenable, + accept_catalog_key: pass.accept_catalog_key, + key_file_configured: true, + }; + let outcome = locked( + migrations()?, + &cx.target, + offline.lock_timeout, + None, + async |stores| key_commands::rotate(stores, &kek, flags).await, + ) + .await?; + print!("{}", outcome_text("rotate", &outcome)); + Ok(()) + } + Command::Reset { + offline, + key_file, + discard_secrets, + } => { + let mut cx = Context::load(&offline.write.common)?; + cx.init_key_store(true)?; + let kek = KeyFile(key_file); + cx.use_kek(&kek)?; + // On PostgreSQL the stores open with the connection string read + // here in place of the row, preview included (section 8.6). + let data_connection = if crate::util::is_postgres() { + Some(read_secret_input( + std::io::stdin().lock(), + std::io::IsTerminal::is_terminal(&std::io::stdin()), + )?) + } else { + None + }; + let flags = RunFlags { + yes: offline.write.yes, + key_file_configured: cx.key_file_configured(), + ..RunFlags::default() + }; + let connection = data_connection.as_deref().map(String::as_str); + // The status read and the stores reach the data database with + // this string in place of the row (RFC-0000 section 8.6, step 1). + cx.target.data_connection = connection.map(str::to_owned); + let outcome = locked( + migrations()?, + &cx.target, + offline.lock_timeout, + connection, + async |stores| { + key_commands::reset(stores, &kek, flags, discard_secrets, connection).await + }, + ) + .await?; + print!("{}", outcome_text("reset", &outcome)); + Ok(()) + } + Command::SetDataConnection(write) => set_data_connection(&write).await, + } +} + +/// `set-data-connection` (section 8.7). The connection string is read only +/// with `--yes`, and parsed before anything is written. +async fn set_data_connection(write: &Write) -> Result<(), Failure> { + if !crate::util::is_postgres() { + return Err(Failure::new(format!( + "`encryption-key set-data-connection` writes the PostgreSQL data database \ + connection string; this binary serves {}, whose catalog has no such row", + extenddb_storage::backend_name().unwrap_or("another backend") + ))); + } + let cx = Context::load(&write.common)?; + let kek = cx.configured_kek("set-data-connection")?; + cx.init_key_store(true)?; + if !write.yes { + println!( + "Nothing was written. With --yes this command reads a connection string from \ + standard input and writes the data_database_connection_string row, encrypted \ + under the DEK of the key ring." + ); + return Ok(()); + } + let connection = read_secret_input( + std::io::stdin().lock(), + std::io::IsTerminal::is_terminal(&std::io::stdin()), + )?; + extenddb_storage::operations::parse_connection_string(&connection).map_err(|_| { + Failure::new("standard input does not parse as a PostgreSQL connection string") + })?; + // The store reads the ring with `SELECT ... FOR SHARE` and writes the + // row in one transaction, so a ring write of `rotate` waits for it. + let stores = Stores::open(&cx.target, true).await?; + let key = kek.read().map_err(Failure::new)?; + stores + .settings + .set_data_connection(&key, &connection) + .await + .map_err(|e| Failure::new(e.message()))?; + println!( + "The data_database_connection_string row was written, encrypted under the DEK of the \ + key ring. A running server reads it at its next start." + ); + Ok(()) +} + +/// Run `f` over the catalog's stores, which the migration backend opens +/// under the migration lock that this process holds, as `migrate --yes` +/// does, and free the lock after. The catalog's migrations must be current. +async fn locked( + migrations: &dyn CatalogMigrations, + target: &Target, + lock_timeout: Option, + data_connection: Option<&str>, + f: impl AsyncFnOnce(KeyStores<'_>) -> Result, +) -> Result { + let timeout = + Duration::from_secs(lock_timeout.unwrap_or(crate::cmd_migrate::DEFAULT_LOCK_TIMEOUT_SECS)); + println!( + "--- Taking the migration lock (waiting up to {} s for a server or another migration)...", + timeout.as_secs() + ); + let lock = migrations.lock(target, timeout).await?; + let result = async { + current(migrations.status_under_lock(&lock, target).await?)?; + let stores = migrations.locked_stores(&lock, data_connection).await?; + Ok::( + f(KeyStores { + management: stores.management(), + settings: stores.settings(), + }) + .await?, + ) + } + .await; + migrations.release(lock).await; + result +} + +/// The installed backend's catalog migrations. +fn migrations() -> Result<&'static dyn CatalogMigrations, Failure> { + extenddb_storage::migrations::installed() + .ok_or_else(|| Failure::new("no storage backend is installed")) +} + +/// Refuse a catalog whose migrations are not current: the commands read and +/// write the rows of this binary's catalog. +fn current(status: CatalogStatus) -> Result<(), Failure> { + match status { + CatalogStatus::Current { .. } | CatalogStatus::AheadCompatible { .. } => Ok(()), + status => Err(Failure { + code: status.exit_code(), + message: format!( + "{status}. The encryption-key commands run on a catalog whose migrations are \ + current: run `extenddb migrate` first" + ), + }), + } +} + +/// The catalog's management and settings stores, holding no key. +struct Stores { + management: Box, + settings: Box, +} + +impl Stores { + /// The stores of `status`, `rewrap` and `set-data-connection`, which run + /// beside a server. `writes` is false for `status`. + /// + /// On every backend but PostgreSQL the catalog status is read first, + /// without the lock, and a catalog whose migrations are not current is + /// refused: opening the stores of a path that holds no catalog would + /// create an empty database there. On PostgreSQL an open creates nothing, + /// and the full status read opens the `data_database_connection_string` + /// row, which a catalog with a key ring keeps encrypted (RFC-0000 section + /// 12). There `rewrap` and `set-data-connection`, which write rows of the + /// catalog database, read the status of the catalog database alone, + /// which opens no such row. `status` writes nothing and reads no status, + /// so it can report a ring or a row that does not open. + async fn open(target: &Target, writes: bool) -> Result { + if writes { + current(migrations()?.catalog_store_status(target).await?)?; + } else if !crate::util::is_postgres() { + current(migrations()?.status(target).await?)?; + } + let location = target.location.as_str(); + let management = + extenddb_storage::management_store_factory::create_management_store(location) + .await + .map_err(|e| Failure::new(format!("cannot open the catalog: {e}")))?; + let settings = extenddb_storage::settings_store::create_settings_store(location) + .await + .map_err(|e| Failure::new(format!("cannot open the catalog: {e}")))?; + Ok(Self { + management, + settings, + }) + } + + fn view(&self) -> KeyStores<'_> { + KeyStores { + management: &*self.management, + settings: &*self.settings, + } + } +} + +/// Standard input as section 8.7 reads it for `reset` and +/// `set-data-connection`: to the end, with one trailing newline stripped. +/// Refused when it is a terminal, so the command never waits with no +/// prompt, when it is empty, and past 8 KiB. The text is wiped when it drops. +fn read_secret_input( + mut input: impl std::io::Read, + is_terminal: bool, +) -> Result, Failure> { + const LIMIT: usize = 8192; + if is_terminal { + return Err(Failure::new( + "standard input is a terminal; give the connection string on standard input, for \ + example `< conn.txt` from a file written under `umask 077`", + )); + } + let mut buffer = Zeroizing::new([0u8; LIMIT + 1]); + let filled = extenddb_server::key_file::read_bounded(&mut input, &mut buffer[..]) + .map_err(|e| Failure::new(format!("cannot read standard input: {e}")))?; + if filled > LIMIT { + return Err(Failure::new(format!( + "standard input holds more than {LIMIT} bytes; give one connection string" + ))); + } + let bytes = &buffer[..filled]; + let bytes = bytes.strip_suffix(b"\n").unwrap_or(bytes); + if bytes.is_empty() { + return Err(Failure::new( + "standard input is empty; give the connection string on standard input", + )); + } + let text = + std::str::from_utf8(bytes).map_err(|_| Failure::new("standard input is not UTF-8 text"))?; + Ok(Zeroizing::new(text.to_owned())) +} + +#[path = "cmd_encryption_key_text.rs"] +mod text; + +#[cfg(test)] +#[path = "cmd_encryption_key_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "cmd_encryption_key_sqlite_tests.rs"] +mod sqlite_tests; diff --git a/crates/app/src/cmd_encryption_key_sqlite_tests.rs b/crates/app/src/cmd_encryption_key_sqlite_tests.rs new file mode 100644 index 000000000..aa1ac8c61 --- /dev/null +++ b/crates/app/src/cmd_encryption_key_sqlite_tests.rs @@ -0,0 +1,444 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The encryption-key commands end to end on a SQLite file catalog: the +//! migration lock, the stores the commands open, the storage crate's steps, +//! and what a server started afterwards opens. +//! +//! The KEK files here are read without the file rule, which the key file +//! module tests on its own: the rule refuses every path under a directory +//! that another user owns, and a test host's temp directory can sit under +//! one. Each test skips with a printed reason while the SQLite backend lacks +//! the stores of a held lock or the pass methods (`read_secret_page` and the +//! rest). + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use extenddb_storage::key_commands::{self, KekFile, KeyStores, Outcome, RunFlags}; +use extenddb_storage::key_ring::{kek_id, parse_kek_file}; +use extenddb_storage::management_store::OpError; +use extenddb_storage::migrations::MigrationError; +use extenddb_storage::secret_keys::SecretTable; +use extenddb_storage::server_components::{BackendError, KeySource, ServerComponentsOptions}; +use zeroize::Zeroizing; + +use super::{Failure, Stores, locked, outcome_text, status_text}; + +const ACCOUNT: &str = "111122223333"; +const USER: &str = "alice"; +const ACCESS_KEY_ID: &str = "AKIAEXTENDDBKEYTEST1"; +const SECRET: &str = "extenddbKeyCommandsEndToEndSecret0000001"; + +/// A KEK file read without the file rule. `fail_after` makes every read +/// after that many fail, as a file that went away during a run. +struct TestKek { + path: String, + reads: AtomicUsize, + fail_after: usize, +} + +impl TestKek { + fn new(path: &Path) -> Self { + Self::failing_after(path, usize::MAX) + } + + fn failing_after(path: &Path, fail_after: usize) -> Self { + Self { + path: path.to_str().expect("utf-8 path").to_owned(), + reads: AtomicUsize::new(0), + fail_after, + } + } + + fn key(&self) -> Zeroizing<[u8; 32]> { + Zeroizing::new(**parse_kek_file(&std::fs::read(&self.path).expect("read")).expect("a KEK")) + } +} + +impl KekFile for TestKek { + fn path(&self) -> &str { + &self.path + } + + fn read(&self) -> Result, String> { + if self.reads.fetch_add(1, Ordering::SeqCst) >= self.fail_after { + return Err(format!("KEK file {} cannot be resolved: gone", self.path)); + } + Ok(self.key()) + } +} + +/// One SQLite catalog in a temp directory, made by `init`'s steps, with one +/// access key under the catalog key, and three KEK files. +struct Deployment { + _dir: tempfile::TempDir, + config: extenddb_config::AppConfig, + keks: [PathBuf; 3], +} + +impl Deployment { + /// `None` when the SQLite store has no pass methods yet. + async fn new() -> Option { + let _ = extenddb_storage::set_backend(extenddb_storage_sqlite::backend()); + let dir = tempfile::tempdir().expect("tempdir"); + let config_path = dir.path().join("extenddb.toml"); + std::fs::write( + &config_path, + format!( + "[storage.sqlite]\npath = {:?}\n\n[auth.encryption]\nrequire_locked_memory = \ + false\n", + dir.path().join("catalog.sqlite").display().to_string() + ), + ) + .expect("config"); + let config_path = config_path.to_str().expect("utf-8").to_owned(); + let config = extenddb_config::load(&config_path).expect("load"); + + let bootstrapper = extenddb_storage::bootstrapper::create_bootstrapper(&config_path, &[]) + .await + .expect("bootstrapper"); + bootstrapper.create_catalog_db().await.expect("catalog db"); + bootstrapper.create_data_db().await.expect("data db"); + let migrations = extenddb_storage::migrations::installed().expect("installed"); + crate::cmd_init::init_on_runner(bootstrapper.as_ref(), migrations, "test", &mut |_| {}) + .await + .expect("init"); + + let keks = [1u8, 2, 3].map(|n| { + let path = dir.path().join(format!("kek-{n}")); + std::fs::write(&path, format!("{}\n", base64_of([n; 32]))).expect("kek"); + path + }); + let deployment = Self { + _dir: dir, + config, + keks, + }; + let components = deployment + .open(KeySource::CatalogKey) + .await + .expect("catalog key"); + let store = components.catalog_store.clone(); + store + .create_account(ACCOUNT, "test") + .await + .expect("account"); + store.create_user(ACCOUNT, USER, None).await.expect("user"); + store + .import_access_key(ACCOUNT, USER, ACCESS_KEY_ID, SECRET) + .await + .expect("access key"); + close(components).await; + + // The commands need the stores of a held lock and the pass methods. + let migrations = extenddb_storage::migrations::installed().expect("installed"); + let lock = migrations + .lock(&deployment.target(), std::time::Duration::from_secs(5)) + .await + .expect("lock"); + let missing = match migrations.locked_stores(&lock, None).await { + Err(MigrationError::Refused(m)) => Some(m), + Err(e) => panic!("locked_stores: {e:?}"), + Ok(stores) => match stores + .management() + .read_secret_page(SecretTable::AccessKeys, None, 1) + .await + { + Err(OpError::Internal(m)) + if m.contains("is not supported by this storage backend") => + { + Some(m) + } + Err(e) => panic!("read_secret_page: {e:?}"), + Ok(_) => None, + }, + }; + migrations.release(lock).await; + match missing { + Some(m) => { + eprintln!("skipped: the SQLite backend of this build lacks a method: {m}"); + None + } + None => Some(deployment), + } + } + + fn target(&self) -> extenddb_storage::migrations::Target { + extenddb_storage::migrations::Target::at(self.config.storage.connection_config()) + } + + fn kek(&self, n: usize) -> TestKek { + TestKek::new(&self.keks[n]) + } + + /// The server's components with `key_source`, as `serve` builds them. + async fn open( + &self, + key_source: KeySource, + ) -> Result { + let mut options = ServerComponentsOptions::default(); + options.release = "test"; + options.key_source = key_source; + extenddb_storage::create_server_components( + self.config.storage.as_trait(), + "us-east-1", + options, + ) + .await + } + + /// The secret a server started with `key_source` reads for the access + /// key, or the refusal of its start. + async fn served_secret(&self, key_source: KeySource) -> Result, String> { + let components = self.open(key_source).await.map_err(|e| e.to_string())?; + let found = components + .credential_store + .lookup_credential(ACCESS_KEY_ID) + .await + .map_err(|e| format!("{e:?}")); + close(components).await; + Ok(found?.map(|c| c.secret_key.clone())) + } + + /// Run a locked command, as `switch`, `rotate` and `reset` do. + async fn locked( + &self, + f: impl AsyncFnOnce(KeyStores<'_>) -> Result, + ) -> Result { + let migrations = extenddb_storage::migrations::installed().expect("installed"); + locked(migrations, &self.target(), Some(5), None, f).await + } +} + +fn base64_of(bytes: [u8; 32]) -> String { + use base64::Engine as _; + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +async fn close(components: extenddb_storage::server_components::ServerComponents) { + if let Some(registration) = components + .runtime_hooks + .as_ref() + .and_then(|hooks| hooks.serving_registrar()) + { + registration.release().await; + } +} + +fn flags(yes: bool) -> RunFlags { + RunFlags { + yes, + ..RunFlags::default() + } +} + +fn kek_source(kek: &TestKek) -> KeySource { + KeySource::Kek(kek.key().into()) +} + +/// `switch`: the preview writes nothing, `--yes` moves the secret under a DEK +/// that the KEK wraps and deletes the catalog key, the server then opens the +/// secret with the KEK only, and a second run has nothing to do. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn switch_moves_every_secret_to_a_dek_under_the_kek() { + let Some(d) = Deployment::new().await else { + return; + }; + let kek = d.kek(0); + let preview = d + .locked(async |s| key_commands::switch(s, &kek, flags(false)).await) + .await + .expect("preview"); + assert!(matches!(preview, Outcome::Preview(_)), "{preview:?}"); + assert_eq!( + d.served_secret(KeySource::CatalogKey).await, + Ok(Some(SECRET.to_owned())) + ); + + let done = d + .locked(async |s| key_commands::switch(s, &kek, flags(true)).await) + .await + .expect("switch"); + let text = outcome_text("switch", &done); + assert!( + text.contains(&format!("KEK id: {}", kek_id(&kek.key()))), + "{text}" + ); + assert!( + text.contains("The encryption_key row was deleted."), + "{text}" + ); + assert!(!text.contains(SECRET), "{text}"); + + assert_eq!( + d.served_secret(kek_source(&kek)).await, + Ok(Some(SECRET.to_owned())) + ); + let refused = d.served_secret(KeySource::CatalogKey).await; + assert!( + refused.is_err(), + "a server without key_file starts after the switch" + ); + + let again = d + .locked(async |s| key_commands::switch(s, &kek, flags(true)).await) + .await + .expect("again"); + assert!( + matches!(again, Outcome::NothingToDo { dek_id: 1, .. }), + "{again:?}" + ); +} + +/// A switch that stops when the KEK file goes away before the catalog key +/// is deleted leaves a ring that the server refuses; the same command run +/// again resumes and finishes. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_stopped_switch_resumes() { + let Some(d) = Deployment::new().await else { + return; + }; + let stops = TestKek::failing_after(&d.keks[0], 1); + let stopped = d + .locked(async |s| key_commands::switch(s, &stops, flags(true)).await) + .await; + assert!(stopped.is_err(), "{stopped:?}"); + let kek = d.kek(0); + let refused = d.served_secret(kek_source(&kek)).await; + assert!( + refused.is_err(), + "a server with key_file starts on the ring of a stopped switch" + ); + + let done = d + .locked(async |s| key_commands::switch(s, &kek, flags(true)).await) + .await + .expect("resume"); + assert!(matches!(done, Outcome::Done(_)), "{done:?}"); + assert_eq!( + d.served_secret(kek_source(&kek)).await, + Ok(Some(SECRET.to_owned())) + ); +} + +/// `rewrap` changes the KEK and no stored secret; `rotate` replaces the DEK; +/// `status` reports the ring under the configured KEK; `reset` with a new +/// KEK deletes the access key and writes a ring that the new KEK opens. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn rewrap_rotate_status_and_reset() { + let Some(d) = Deployment::new().await else { + return; + }; + let (first, second, third) = (d.kek(0), d.kek(1), d.kek(2)); + d.locked(async |s| key_commands::switch(s, &first, flags(true)).await) + .await + .expect("switch"); + + let stores = Stores::open(&d.target(), true).await.expect("stores"); + let rewrapped = key_commands::rewrap(stores.view(), &first, &second, true) + .await + .expect("rewrap"); + assert!(matches!(rewrapped, Outcome::Done(_)), "{rewrapped:?}"); + let report = key_commands::status(stores.view(), Some(&second as &dyn KekFile)) + .await + .expect("status"); + let text = status_text(&report); + assert!( + text.contains("Authenticated under the configured KEK."), + "{text}" + ); + assert!( + text.contains("Catalog key (encryption_key row): none"), + "{text}" + ); + drop(stores); + let mismatch = d.served_secret(kek_source(&first)).await; + assert!( + mismatch.is_err(), + "a server with the first KEK starts after the rewrap" + ); + assert_eq!( + d.served_secret(kek_source(&second)).await, + Ok(Some(SECRET.to_owned())) + ); + + let rotated = d + .locked(async |s| key_commands::rotate(s, &second, flags(true)).await) + .await + .expect("rotate"); + assert!( + matches!(&rotated, Outcome::Done(s) if s.dek_id == 2), + "{rotated:?}" + ); + assert_eq!( + d.served_secret(kek_source(&second)).await, + Ok(Some(SECRET.to_owned())) + ); + + let reset = d + .locked(async |s| key_commands::reset(s, &third, flags(true), true, None).await) + .await + .expect("reset"); + let text = outcome_text("reset", &reset); + assert!(text.contains(ACCESS_KEY_ID), "{text}"); + assert!(text.contains("DEK id: 3"), "{text}"); + assert_eq!(d.served_secret(kek_source(&third)).await, Ok(None)); +} + +/// `set-data-connection` is refused on SQLite before it reads anything. +#[tokio::test] +async fn set_data_connection_is_refused_on_sqlite() { + let _ = extenddb_storage::set_backend(extenddb_storage_sqlite::backend()); + let write = super::Write { + common: super::Common { config: None }, + yes: true, + }; + let failure = super::set_data_connection(&write) + .await + .expect_err("refused"); + assert!( + failure + .message + .contains("this binary serves sqlite, whose catalog has no such row"), + "{}", + failure.message + ); + assert_eq!(failure.code, 1); +} + +/// `status` on a configuration whose SQLite path holds no file refuses with +/// the text of a catalog whose migrations are not current, and creates no +/// file there. +#[tokio::test] +async fn status_on_a_path_with_no_catalog_refuses_and_creates_no_file() { + let _ = extenddb_storage::set_backend(extenddb_storage_sqlite::backend()); + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("missing.sqlite"); + let config = dir.path().join("extenddb.toml"); + std::fs::write( + &config, + format!( + "[storage.sqlite]\npath = {:?}\n\n[auth.encryption]\nrequire_locked_memory = false\n", + path.display().to_string() + ), + ) + .expect("config"); + let common = super::Common { + config: Some(config.to_str().expect("utf-8").to_owned()), + }; + let failure = super::command(super::Command::Status(common)) + .await + .expect_err("refused"); + assert_eq!( + failure.message, + "the catalog is not initialized. The encryption-key commands run on a catalog whose \ + migrations are current: run `extenddb migrate` first" + ); + assert_eq!(failure.code, 1); + let left: Vec<_> = std::fs::read_dir(dir.path()) + .expect("dir") + .map(|entry| entry.expect("entry").file_name()) + .collect(); + assert_eq!(left, vec![std::ffi::OsString::from("extenddb.toml")]); +} diff --git a/crates/app/src/cmd_encryption_key_tests.rs b/crates/app/src/cmd_encryption_key_tests.rs new file mode 100644 index 000000000..fe3424f2b --- /dev/null +++ b/crates/app/src/cmd_encryption_key_tests.rs @@ -0,0 +1,446 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Tests of `extenddb encryption-key`: the command line, the standard input +//! rules, the lock, and what the commands print. + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use async_trait::async_trait; +use clap::Parser; +use extenddb_storage::key_commands::{NO_REVOCATION_NOTICE, Outcome, StatusReport, Summary}; +use extenddb_storage::key_pass::{DataConnection, Opener, SecretListing, Survey, TableCounts}; +use extenddb_storage::key_ring::{KekRef, KekSource, KeyId, KeyRing, WrappedDek}; +use extenddb_storage::migrations::{ + HeldLock, LedgerRow, Listed, MigrationId, Pending, RunKind, RunReport, StoreKind, +}; +use extenddb_storage::secret_keys::SecretTable; + +use super::*; + +#[derive(Parser)] +struct Cli { + #[command(flatten)] + args: EncryptionKeyArgs, +} + +/// Each command's options: the lock options only on the commands that take +/// the lock, `--yes` on every command that writes, and the flags that the +/// RFC gives a command only on that command. +#[test] +fn each_command_takes_its_own_options() { + let cases: &[(&[&str], bool)] = &[ + (&["status"], true), + (&["status", "--config", "/etc/extenddb/extenddb.toml"], true), + (&["status", "--yes"], false), + (&["switch", "--key-file", "/run/kek"], true), + ( + &[ + "switch", + "--key-file", + "/run/kek", + "--yes", + "--lock-timeout", + "86400", + "--accept-catalog-key", + "--keep-unopenable", + ], + true, + ), + (&["switch"], false), + ( + &[ + "switch", + "--key-file", + "/run/kek", + "--lock-timeout", + "86401", + ], + false, + ), + (&["rewrap", "--key-file", "/run/new", "--yes"], true), + ( + &["rewrap", "--key-file", "/run/new", "--lock-timeout", "5"], + false, + ), + ( + &["rewrap", "--key-file", "/run/new", "--keep-unopenable"], + false, + ), + ( + &[ + "rotate", + "--yes", + "--accept-catalog-key", + "--keep-unopenable", + ], + true, + ), + (&["rotate", "--key-file", "/run/kek"], false), + ( + &[ + "reset", + "--key-file", + "/run/new", + "--discard-secrets", + "--yes", + ], + true, + ), + ( + &["reset", "--key-file", "/run/new", "--keep-unopenable"], + false, + ), + (&["set-data-connection", "--yes"], true), + (&["set-data-connection", "--lock-timeout", "5"], false), + ]; + for (argv, parses) in cases { + let line = std::iter::once("encryption-key").chain(argv.iter().copied()); + let result = Cli::try_parse_from(line); + assert_eq!(result.is_ok(), *parses, "{argv:?}: {:?}", result.err()); + } +} + +/// Standard input as `reset` and `set-data-connection` read it: one +/// trailing newline stripped, a terminal, empty input and more than 8 KiB +/// refused. No refusal repeats the input. +#[test] +fn standard_input_follows_the_rules_of_section_8_7() { + const CONN: &str = "postgresql://extenddb:apppassword@db.internal:5432/extenddb"; + let long = "x".repeat(8193); + /// What the case is, the input, whether it is a terminal, and the text + /// or a part of the refusal. + type Case<'a> = (&'a str, &'a [u8], bool, Result<&'a str, &'a str>); + let cases: Vec> = vec![ + ( + "one newline", + b"postgresql://extenddb:apppassword@db.internal:5432/extenddb\n", + false, + Ok(CONN), + ), + ("no newline", CONN.as_bytes(), false, Ok(CONN)), + ("two newlines", b"a\n\n", false, Ok("a\n")), + ( + "a terminal", + CONN.as_bytes(), + true, + Err("standard input is a terminal"), + ), + ("empty", b"", false, Err("standard input is empty")), + ( + "a newline only", + b"\n", + false, + Err("standard input is empty"), + ), + ( + "more than 8 KiB", + long.as_bytes(), + false, + Err("more than 8192 bytes"), + ), + ( + "not UTF-8", + b"\xff\xfeapppassword", + false, + Err("not UTF-8 text"), + ), + ]; + for (what, input, terminal, expected) in cases { + match (read_secret_input(input, terminal), expected) { + (Ok(text), Ok(want)) => assert_eq!(text.as_str(), want, "{what}"), + (Err(failure), Err(part)) => { + assert!( + failure.message.contains(part), + "{what}: {}", + failure.message + ); + assert!(!failure.message.contains("apppassword"), "{what}"); + assert_eq!(failure.code, 1, "{what}"); + } + (got, _) => panic!("{what}: {:?}", got.map(|t| t.len())), + } + } +} + +/// A fake catalog whose lock and status the test chooses, recording the +/// calls in order. +struct FakeMigrations { + lock: Result<(), MigrationError>, + status: CatalogStatus, + calls: Arc>>, +} + +impl FakeMigrations { + fn call(&self, name: &'static str) { + self.calls.lock().unwrap().push(name); + } +} + +#[async_trait] +impl CatalogMigrations for FakeMigrations { + fn listed(&self, _id: MigrationId) -> Listed { + Listed::NotApplicable("fake") + } + fn backup_advice(&self, target: &Target) -> String { + format!("back up {}", target.location) + } + async fn status(&self, _target: &Target) -> Result { + self.call("status"); + Ok(self.status.clone()) + } + async fn catalog_ledger(&self, _: &Target) -> Result, MigrationError> { + Ok(Vec::new()) + } + async fn lock(&self, target: &Target, _: Duration) -> Result { + self.call("lock"); + self.lock + .clone() + .map(|()| HeldLock::new(target.location.as_str(), ())) + } + async fn run(&self, _: &HeldLock, _: &str, _: RunKind) -> Result { + unreachable!("the key commands run no migration") + } + async fn forget(&self, _lock: &HeldLock, _id: u32) -> Result<(), MigrationError> { + unreachable!("the key commands forget no migration") + } + async fn release(&self, lock: HeldLock) { + self.call("release"); + drop(lock); + } +} + +/// The lock is taken and freed as `migrate --yes` does: a lock held past +/// `--lock-timeout` exits 6 with nothing run; a catalog whose migrations are +/// not current exits with `migrate`'s code for it, and the lock is freed. +#[tokio::test] +async fn the_lock_exits_6_when_held_and_a_catalog_behind_is_refused() { + let behind = CatalogStatus::Behind { + version: Some(8), + pending: vec![Pending { + id: 9, + name: "warm_throughput", + store: StoreKind::Catalog, + store_name: "extenddb.sqlite".to_owned(), + kind: extenddb_storage::migrations::Kind::Additive, + }], + }; + let cases = [ + ( + Err(MigrationError::Locked("held by pid 7".to_owned())), + CatalogStatus::Current { version: 9 }, + 6, + vec!["lock"], + ), + (Ok(()), behind, 3, vec!["lock", "status", "release"]), + ]; + for (lock, status, code, calls) in cases { + let fake = FakeMigrations { + lock, + status, + calls: Arc::default(), + }; + let target = Target::at("/var/lib/extenddb/extenddb.sqlite"); + let failure = locked(&fake, &target, Some(1), None, async |_stores| { + Ok::<(), KeyCommandError>(()) + }) + .await + .expect_err("refused"); + assert_eq!(failure.code, code, "{}", failure.message); + assert_eq!(*fake.calls.lock().unwrap(), calls, "{}", failure.message); + } +} + +fn key_id(hex: &str) -> KeyId { + KeyId::parse(hex).expect("a key id") +} + +fn listing(access_key_id: &str, opener: Opener) -> SecretListing { + SecretListing { + table: SecretTable::AccessKeys, + access_key_id: access_key_id.to_owned(), + account_id: "123456789012".to_owned(), + principal_name: "alice".to_owned(), + created_at: Some(time::OffsetDateTime::from_unix_timestamp(1_794_823_200).expect("time")), + opener, + } +} + +/// The summary prints the KEK id, the DEK id, the counts per table under the +/// command's key names, the stored secrets that no key opens, the `key_file` +/// line and the notice, which for `reset` says that every access key and +/// session was deleted. +#[test] +fn the_summary_names_the_keys_and_ends_with_the_notice() { + let counts = TableCounts { + target: 1, + old: vec![0], + unopenable: 1, + rewritten: 2, + }; + let summary = Summary { + kek_id: key_id("3f9a0c51e2d47b86"), + dek_id: 1, + tables: [ + (SecretTable::AccessKeys, counts), + (SecretTable::IamSessions, TableCounts::default()), + ], + data_connection_rewritten: None, + unopenable: vec![listing("AKIAEXAMPLE000000001", Opener::None)], + deleted_access_key_ids: Vec::new(), + deleted_catalog_key: true, + key_file: "/etc/extenddb/kek".to_owned(), + key_names: vec!["DEK 1".to_owned(), "the catalog key".to_owned()], + }; + let text = outcome_text("switch", &Outcome::Done(summary.clone())); + for line in [ + "=== extenddb encryption-key switch complete ===", + "KEK id: 3f9a0c51e2d47b86", + "DEK id: 1", + "access_keys: 1 under DEK 1, 0 under the catalog key, 1 that no key opens, 2 \ + re-encrypted", + "iam_sessions: 0 under DEK 1, 0 that no key opens", + "The encryption_key row was deleted.", + "access_keys AKIAEXAMPLE000000001: account 123456789012, owner alice, created \ + 2026-11-16T10:00:00Z, under no key", + "key_file = \"/etc/extenddb/kek\"", + NO_REVOCATION_NOTICE, + ] { + assert!(text.contains(line), "{line}\n{text}"); + } + assert!(!text.contains("data_database_connection_string"), "{text}"); + + let text = outcome_text("reset", &Outcome::Done(summary.clone())); + assert!( + text.ends_with(&format!("{}\n", key_commands::reset_notice())), + "{text}" + ); + assert!(text.contains("The KEK of a catalog copy is lost"), "{text}"); + assert!(!text.contains(NO_REVOCATION_NOTICE), "{text}"); + + // A daemon `serve` runs from `/`, so a relative path is printed absolute. + let relative = Summary { + key_file: "kek".to_owned(), + ..summary + }; + let absolute = std::env::current_dir().expect("cwd").join("kek"); + assert_eq!( + relative.key_file_line(), + format!("key_file = {:?}", absolute.display().to_string()) + ); + + let text = outcome_text( + "rotate", + &Outcome::NothingToDo { + kek_id: key_id("3f9a0c51e2d47b86"), + dek_id: 2, + }, + ); + assert_eq!( + text, + "Nothing to do: the key ring is already in the target state (KEK id \ + 3f9a0c51e2d47b86, DEK id 2).\n" + ); +} + +/// `status` prints the ring's fields, and says whether they are +/// authenticated: no KEK given, another KEK, a DEK that fails to unwrap, or +/// the configured KEK. +#[test] +fn status_says_whether_the_ring_is_authenticated() { + let ring = KeyRing { + version: 1, + kek: KekRef { + source: KekSource::File, + id: key_id("3f9a0c51e2d47b86"), + }, + keys: vec![ + WrappedDek { + id: 2, + wrapped: "c2VhbGVk".to_owned(), + }, + WrappedDek { + id: 1, + wrapped: "c2VhbGVk".to_owned(), + }, + ], + switch_from_catalog_key: false, + retiring_catalog_key_id: None, + }; + let cases = [ + (None, vec![], "Not authenticated: no KEK file was given"), + ( + Some(key_id("00000000000000aa")), + vec![], + "Not authenticated: the configured KEK has id 00000000000000aa, and the ring names \ + KEK id 3f9a0c51e2d47b86.", + ), + ( + Some(key_id("3f9a0c51e2d47b86")), + vec![1], + "Not authenticated: DEK ids 1 fail to unwrap under the configured KEK", + ), + ( + Some(key_id("3f9a0c51e2d47b86")), + vec![], + "Authenticated under the configured KEK.", + ), + ]; + for (given_kek_id, failed_dek_ids, expected) in cases { + let report = StatusReport { + catalog_key_present: false, + ring: Some(key_commands::RingStatus { + ring: ring.clone(), + given_kek_id, + failed_dek_ids, + }), + survey: None, + }; + let text = status_text(&report); + assert!( + text.contains( + "Key ring (encryption_key_ring row): KEK source file, KEK id 3f9a0c51e2d47b86, \ + DEK ids 1, 2, switch_from_catalog_key false, retiring_catalog_key_id none" + ), + "{text}" + ); + assert!(text.contains(expected), "{expected}\n{text}"); + assert!( + text.contains("Catalog key (encryption_key row): none"), + "{text}" + ); + } + + let survey = Survey { + tables: [ + ( + SecretTable::AccessKeys, + TableCounts { + target: 2, + old: vec![], + unopenable: 1, + rewritten: 0, + }, + ), + (SecretTable::IamSessions, TableCounts::default()), + ], + not_target: vec![listing("AKIAEXAMPLE000000002", Opener::None)], + data_connection: DataConnection::Absent, + key_names: vec!["the catalog key".to_owned()], + }; + let text = status_text(&StatusReport { + catalog_key_present: true, + ring: None, + survey: Some(survey), + }); + for line in [ + "Catalog key (encryption_key row): present", + "Key ring (encryption_key_ring row): none", + "access_keys: 2 under the catalog key, 1 that no key opens", + "Stored secrets under a key other than the catalog key:", + "access_keys AKIAEXAMPLE000000002: account 123456789012, owner alice", + ] { + assert!(text.contains(line), "{line}\n{text}"); + } +} diff --git a/crates/app/src/cmd_encryption_key_text.rs b/crates/app/src/cmd_encryption_key_text.rs new file mode 100644 index 000000000..ef4af30ae --- /dev/null +++ b/crates/app/src/cmd_encryption_key_text.rs @@ -0,0 +1,199 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use extenddb_storage::key_commands::{self, NO_REVOCATION_NOTICE, Outcome, StatusReport, Summary}; +use extenddb_storage::key_pass::{Opener, SecretListing, Survey, TableCounts}; +use extenddb_storage::secret_keys::SecretTable; + +/// The name of the key that `opener` stands for, from the names of the run's +/// keys: `[0]` the target, `[i + 1]` `Opener::Old(i)`, for example "the +/// catalog key" or "DEK 2". +fn key_name(names: &[String], opener: Opener) -> &str { + let at = match opener { + Opener::Target => 0, + Opener::Old(i) => i + 1, + Opener::None => return "no key", + }; + names.get(at).map_or("an unnamed key", String::as_str) +} + +/// One line per table: the stored secrets under each key, those that no key +/// opens, and, after a pass, how many it re-encrypted. +fn counts_lines(tables: &[(SecretTable, TableCounts); 2], names: &[String]) -> String { + let mut out = String::new(); + for (table, counts) in tables { + let mut parts = vec![format!( + "{} under {}", + counts.target, + key_name(names, Opener::Target) + )]; + for (i, n) in counts.old.iter().enumerate() { + parts.push(format!("{n} under {}", key_name(names, Opener::Old(i)))); + } + parts.push(format!("{} that no key opens", counts.unopenable)); + if counts.rewritten > 0 { + parts.push(format!("{} re-encrypted", counts.rewritten)); + } + out.push_str(&format!(" {}: {}\n", table.name(), parts.join(", "))); + } + out +} + +/// One line per stored secret: its access key ID, owner, creation time and +/// key. Never the secret, and never the row's primary key. +fn listing_lines(listing: &[SecretListing], names: &[String]) -> String { + listing + .iter() + .map(|s| { + let created = s.created_at.map_or_else( + || "unknown".to_owned(), + |t| { + t.format(&time::format_description::well_known::Rfc3339) + .unwrap_or_else(|_| t.to_string()) + }, + ); + format!( + " {} {}: account {}, owner {}, created {created}, under {}\n", + s.table.name(), + s.access_key_id, + s.account_id, + s.principal_name, + key_name(names, s.opener) + ) + }) + .collect() +} + +fn survey_text(survey: &Survey) -> String { + let names = &survey.key_names; + let mut out = format!("Stored secrets:\n{}", counts_lines(&survey.tables, names)); + if !survey.not_target.is_empty() { + out.push_str(&format!( + "Stored secrets under a key other than {}:\n{}", + key_name(names, Opener::Target), + listing_lines(&survey.not_target, names) + )); + } + out +} + +/// What `command` prints for `outcome`. +pub(super) fn outcome_text(command: &str, outcome: &Outcome) -> String { + match outcome { + Outcome::NothingToDo { kek_id, dek_id } => format!( + "Nothing to do: the key ring is already in the target state (KEK id {kek_id}, DEK \ + id {dek_id}).\n" + ), + Outcome::Preview(preview) => { + let mut out = format!("Nothing was written. `encryption-key {command} --yes` would:\n"); + for step in &preview.steps { + out.push_str(&format!(" {step}\n")); + } + if let Some(survey) = &preview.survey { + out.push_str(&survey_text(survey)); + } + out + } + Outcome::Done(summary) => summary_text(command, summary), + } +} + +/// The summary of section 8, common rules: the KEK id, the DEK id, the +/// counts per table, the connection string row, the stored secrets that no +/// key opens, the `key_file` line and the notice. +fn summary_text(command: &str, summary: &Summary) -> String { + let names = &summary.key_names; + let mut out = format!( + "=== extenddb encryption-key {command} complete ===\nKEK id: {}\nDEK id: {}\n{}", + summary.kek_id, + summary.dek_id, + counts_lines(&summary.tables, names) + ); + if let Some(rewritten) = summary.data_connection_rewritten { + out.push_str(if rewritten { + "The data_database_connection_string row was rewritten.\n" + } else { + "The data_database_connection_string row was not rewritten.\n" + }); + } + if summary.deleted_catalog_key { + out.push_str("The encryption_key row was deleted.\n"); + } + if !summary.deleted_access_key_ids.is_empty() { + out.push_str(&format!( + "Deleted access keys: {}\n", + summary.deleted_access_key_ids.join(", ") + )); + } + if !summary.unopenable.is_empty() { + out.push_str(&format!( + "Stored secrets that no key opens, kept as they are:\n{}", + listing_lines(&summary.unopenable, names) + )); + } + let notice = if command == "reset" { + key_commands::reset_notice() + } else { + NO_REVOCATION_NOTICE.to_owned() + }; + out.push_str(&format!( + "Set this line in the [auth.encryption] section of the configuration:\n {}\n{notice}\n", + summary.key_file_line(), + )); + out +} + +/// What `status` prints. +pub(super) fn status_text(report: &StatusReport) -> String { + let mut out = format!( + "Catalog key (encryption_key row): {}\n", + if report.catalog_key_present { + "present" + } else { + "none" + } + ); + match &report.ring { + None => out.push_str("Key ring (encryption_key_ring row): none\n"), + Some(status) => { + let ring = &status.ring; + let ids: Vec = ring.dek_ids().iter().map(u64::to_string).collect(); + out.push_str(&format!( + "Key ring (encryption_key_ring row): KEK source {}, KEK id {}, DEK ids {}, \ + switch_from_catalog_key {}, retiring_catalog_key_id {}\n", + ring.kek.source.name(), + ring.kek.id, + ids.join(", "), + ring.switch_from_catalog_key, + ring.retiring_catalog_key_id + .as_ref() + .map_or_else(|| "none".to_owned(), ToString::to_string) + )); + out.push_str(&match &status.given_kek_id { + None => " Not authenticated: no KEK file was given ([auth.encryption] key_file \ + is not set).\n" + .to_owned(), + Some(given) if *given != ring.kek.id => format!( + " Not authenticated: the configured KEK has id {given}, and the ring names \ + KEK id {}.\n", + ring.kek.id + ), + Some(_) if !status.failed_dek_ids.is_empty() => { + let failed: Vec = + status.failed_dek_ids.iter().map(u64::to_string).collect(); + format!( + " Not authenticated: DEK ids {} fail to unwrap under the configured \ + KEK; the ring has damage or a changed field.\n", + failed.join(", ") + ) + } + Some(_) => " Authenticated under the configured KEK.\n".to_owned(), + }); + } + } + match &report.survey { + Some(survey) => out.push_str(&survey_text(survey)), + None => out.push_str("Stored secrets: not read, because no key opens them here.\n"), + } + out +} diff --git a/crates/app/src/cmd_init.rs b/crates/app/src/cmd_init.rs index f2a62bf6b..441d58f3c 100755 --- a/crates/app/src/cmd_init.rs +++ b/crates/app/src/cmd_init.rs @@ -339,7 +339,7 @@ pub async fn run(args: InitArgs, release: &str) -> anyhow::Result { /// backend reads no flag itself. `say` prints this function's own lines: /// the one before the migrations, their notes, and the one that says a /// stopped `init` is being finished, before its rows. -async fn init_on_runner( +pub(crate) async fn init_on_runner( bootstrapper: &dyn extenddb_storage::bootstrapper::Bootstrapper, migrations: &dyn extenddb_storage::migrations::CatalogMigrations, release: &str, diff --git a/crates/app/src/cmd_migrate_runner.rs b/crates/app/src/cmd_migrate_runner.rs index 7bd203137..ac70c2c20 100644 --- a/crates/app/src/cmd_migrate_runner.rs +++ b/crates/app/src/cmd_migrate_runner.rs @@ -57,6 +57,8 @@ pub(crate) async fn run( std::env::var_os("EXTENDDB_CASSANDRA_PASSWORD"), )?, data_connection: None, + key_source: crate::util::status_key_source(&app_config)?, + ..Target::default() }; // The backup clause names the data store the catalog records when the // command names none. diff --git a/crates/app/src/cmd_verify.rs b/crates/app/src/cmd_verify.rs index 944c58164..e29f76fb7 100755 --- a/crates/app/src/cmd_verify.rs +++ b/crates/app/src/cmd_verify.rs @@ -63,7 +63,7 @@ pub async fn run(args: VerifyArgs, release: &str) -> anyhow::Result { // exist is reported, not created. let migrations = extenddb_storage::migrations::installed() .ok_or_else(|| anyhow::anyhow!("no storage backend is installed"))?; - let status_code = check_migrations( + let (status_code, key_source) = check_migrations( migrations, config_file.as_deref(), &app_config, @@ -100,7 +100,7 @@ pub async fn run(args: VerifyArgs, release: &str) -> anyhow::Result { .await .map_err(|e| anyhow::anyhow!("Failed to create diagnostics store: {e}"))?; - match diag_store.test_data_database_connection().await { + match diag_store.test_data_database_connection(&key_source).await { Ok(db_name) => println!(" OK: Connected to data database '{db_name}'."), Err(e) => { println!(" FAIL: {e}"); @@ -172,20 +172,34 @@ fn ledger_note_lines(rows: &[extenddb_storage::migrations::LedgerRow], all: bool /// Print the catalog status, what its pending migrations change, and the /// notes the ledger records (each migration's first [`NOTES_SHOWN`], or -/// every note with `all_notes`), and return the status's exit code. +/// every note with `all_notes`), and return the status's exit code with the +/// key the status read used, which the data database check uses too. async fn check_migrations( migrations: &dyn extenddb_storage::migrations::CatalogMigrations, config_file: Option<&str>, app_config: &config::AppConfig, release: &str, all_notes: bool, -) -> u8 { +) -> (u8, extenddb_storage::server_components::KeySource) { use extenddb_storage::migrations::advice::{self, AdviceFor}; use extenddb_storage::migrations::{CatalogStatus, Target}; println!("--- Checking catalog migrations..."); let location = app_config.storage.connection_config(); - let target = Target::at(location); + let key_source = match crate::util::status_key_source(app_config) { + Ok(key_source) => key_source, + Err(e) => { + println!(" FAIL: {e:#}"); + return ( + extenddb_storage::migrations::exit::ERROR, + extenddb_storage::server_components::KeySource::None, + ); + } + }; + let target = Target { + key_source, + ..Target::at(location) + }; // The backup clause names the data store the catalog records. let named = Target { data_store: migrations.data_store_name(&target).await, @@ -203,7 +217,7 @@ async fn check_migrations( Ok(status) => status, Err(e) => { println!(" FAIL: {}", advice::error_message(&e, &advice)); - return e.exit_code(); + return (e.exit_code(), target.key_source); } }; match &status { @@ -238,7 +252,7 @@ async fn check_migrations( println!("{line}"); } } - status.exit_code() + (status.exit_code(), target.key_source) } #[cfg(test)] diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index c7667c423..3e9a781ab 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -5,7 +5,7 @@ //! //! Owns the command-line interface (`serve`, `init`, `destroy`, `backup`, //! `verify`, `migrate`, `status`, `stop`, `settings`, `manage`, -//! `catalog-check`, `healthcheck`) and the +//! `catalog-check`, `encryption-key`, `healthcheck`) and the //! subcommand dispatch. It is backend-agnostic: a backend's thin `main` //! installs its backend with //! [`set_backend`](extenddb_storage::set_backend) and then calls [`run`]: @@ -25,6 +25,7 @@ mod cmd_backup; mod cmd_catalog_check; mod cmd_destroy; +mod cmd_encryption_key; mod cmd_healthcheck; mod cmd_init; mod cmd_manage; @@ -88,6 +89,10 @@ enum Command { Manage(cmd_manage::ManageArgs), /// Check catalog and data database integrity CatalogCheck(cmd_catalog_check::CatalogCheckArgs), + /// Show or change the key that encrypts stored secrets: status, switch, rewrap, rotate, + /// reset, set-data-connection (exit 0 done or previewed, 1 refused, 3 to 5 the catalog's + /// migrations are not current, 6 the catalog stayed locked) + EncryptionKey(cmd_encryption_key::EncryptionKeyArgs), /// Probe the local /health endpoint over HTTPS (exit 0 healthy, 1 not) Healthcheck(cmd_healthcheck::HealthcheckArgs), /// Print version, catalog version, git commit, and build timestamp @@ -160,6 +165,13 @@ pub fn run(build: BuildInfo) -> anyhow::Result<()> { Command::Settings(args) => run_interactive(cmd_settings::run(args)), Command::Manage(args) => run_interactive(cmd_manage::run(args)), Command::CatalogCheck(args) => run_interactive(cmd_catalog_check::run(args)), + Command::EncryptionKey(args) => { + let code = run_interactive(cmd_encryption_key::run(args))?; + if code != 0 { + std::process::exit(i32::from(code)); + } + Ok(()) + } Command::Healthcheck(args) => match cmd_healthcheck::run(&args) { Ok(()) => Ok(()), Err(e) => { diff --git a/crates/app/src/util.rs b/crates/app/src/util.rs index 4358e5750..2a873883a 100755 --- a/crates/app/src/util.rs +++ b/crates/app/src/util.rs @@ -43,6 +43,44 @@ pub(crate) fn command_config( ) } +/// Whether this binary serves PostgreSQL, the one backend whose catalog +/// holds the data database connection string (RFC-0000 section 12). +pub(crate) fn is_postgres() -> bool { + extenddb_storage::backend_name() == Some("postgres") +} + +/// The key that `migrate` and `verify` put on their target: on PostgreSQL +/// with `[auth.encryption] key_file` set, the KEK read through the file +/// rule, with which the migration backend opens the data connection string +/// row of a catalog with a key ring (RFC-0000 section 12); else the catalog +/// key, which no other backend's migrations read. +pub(crate) fn status_key_source( + config: &extenddb_config::AppConfig, +) -> anyhow::Result { + if !is_postgres() { + return Ok(extenddb_storage::server_components::KeySource::CatalogKey); + } + command_key_source(config) +} + +/// The key a command puts on its target or its factory options (RFC-0000 +/// section 7): with `[auth.encryption] key_file` set, the locked key store +/// is set up first, as `serve` and the `encryption-key` commands set it up, +/// so the DEK that the KEK unwraps lives in locked memory; then the KEK +/// read through the file rule. Without `key_file`, the catalog key. +pub(crate) fn command_key_source( + config: &extenddb_config::AppConfig, +) -> anyhow::Result { + use extenddb_server::key_file::{COMMAND_SLOTS, init_key_store, key_source}; + let encryption = &config.auth.encryption; + if encryption.key_file.is_some() { + let protection = init_key_store(true, encryption.require_locked_memory, COMMAND_SLOTS) + .map_err(anyhow::Error::msg)?; + tracing::info!("Locked key store: {protection}"); + } + key_source(encryption).map_err(anyhow::Error::msg) +} + /// Print each step a run applied, as ` ` /// (without ` ` when `noun` is empty), naming the store only when the /// run touched more than one, and each step's notes below it. A step of a diff --git a/crates/auth/Cargo.toml b/crates/auth/Cargo.toml index b936b9e52..b27969134 100755 --- a/crates/auth/Cargo.toml +++ b/crates/auth/Cargo.toml @@ -18,6 +18,7 @@ futures = { workspace = true } thiserror = { workspace = true } axum = { workspace = true } aws-lc-rs = { workspace = true } +libc = { workspace = true } sha2 = "0.10" hex = "0.4" serde_json = { workspace = true } diff --git a/crates/auth/src/credential_cache.rs b/crates/auth/src/credential_cache.rs index 1ea430b1d..412228353 100644 --- a/crates/auth/src/credential_cache.rs +++ b/crates/auth/src/credential_cache.rs @@ -1,15 +1,21 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! `CachedCredentialStore` — wraps any [`CredentialStore`] with a stale-while- -//! revalidate cache. +//! `CachedCredentialStore`: the signing-key cache over any [`CredentialStore`] +//! (RFC-0000, section 6.1), with stale-while-revalidate semantics. //! -//! Each `lookup_credential(access_key_id)` call first consults the in-memory -//! cache. Fresh entries (younger than `soft_ttl`) are returned immediately. +//! The cache entry of an access key holds the principal fields, the session +//! flag, `expires_at`, the SHA-256 of the session token, and the `SigV4` +//! signing key for each scope date in use, in a slot of the locked key store +//! ([`crate::secmem`]). It holds no plaintext secret and no plaintext token. +//! +//! `lookup(access_key_id, scope_date)` first consults the in-memory cache. +//! Fresh entries (younger than `soft_ttl`) are returned immediately. //! Stale-but-usable entries (between `soft_ttl` and `ttl`) are returned //! immediately while a background task refreshes them. Misses block on the -//! upstream store. Negative results (`Ok(None)`) are cached for the shorter -//! `negative_ttl`. Errors are never cached. +//! upstream store: one decrypt, and one derive per scope date valid now. +//! Negative results (`Ok(None)`) are cached for the shorter `negative_ttl`. +//! Errors are never cached. //! //! Write-through invalidation is exposed via [`CachedCredentialStore::invalidate`]: //! the management API calls it whenever an access key is created, deleted, or @@ -18,39 +24,60 @@ //! //! See `docs/design/12-auth-authz-cache.md` for the full design. +mod entry; + use std::sync::Arc; use extenddb_cache::{Loader, SwrCache, SwrCacheConfig}; use extenddb_core::error::DynamoDbError; use futures::FutureExt; use futures::future::BoxFuture; +use time::OffsetDateTime; + +use entry::{BufferPool, Destination, Key, ScopeDate, valid_dates}; +pub use entry::{CachedCredential, ResolvedCredential}; +use crate::secmem::{KeySlot, StoreFull}; +use crate::sigv4::signing_key::derive_signing_key_into; +use crate::sigv4::verify::SCOPE_DATE_COMPLAINT; use crate::{CredentialStore, StoredCredential}; -/// A `CredentialStore` that wraps another store and caches results. +/// The one service a signing key is derived for (`verify.rs` refuses any +/// other scope service). +const SERVICE: &str = "dynamodb"; + +/// The message of the `InternalServerError` the raw stores answer with. +const AUTH_INTERNAL_ERROR: &str = "Internal error during authentication"; + +/// The signing-key cache over a raw [`CredentialStore`]. /// -/// The cache uses stale-while-revalidate semantics — see the module-level +/// The cache uses stale-while-revalidate semantics: see the module-level /// docs and `docs/design/12-auth-authz-cache.md`. /// /// Cloning is cheap; clones share the underlying cache and inner store. #[derive(Clone)] pub struct CachedCredentialStore { - cache: SwrCache, + cache: SwrCache, DynamoDbError>, + inner: Arc, + region: Arc, + buffers: Arc, } impl CachedCredentialStore { - /// Wrap `inner` with a cache configured by `config`. + /// Wrap `inner` with a cache configured by `config`, deriving signing + /// keys for `region` (the server's region), with `workers` temporary + /// buffers (one per runtime worker thread). /// /// The `inner` store is moved into an `Arc` so the cache's loader closure /// can outlive the constructor call. The wrapper itself is `Clone` and /// safe to share across tasks. #[must_use] - pub fn new(inner: T, config: SwrCacheConfig) -> Self + pub fn new(inner: T, config: SwrCacheConfig, region: &str, workers: usize) -> Self where T: CredentialStore + 'static, { let inner: Arc = Arc::new(inner); - Self::with_arc(inner, config) + Self::with_arc(inner, config, region, workers) } /// Wrap an already-`Arc`-wrapped `CredentialStore`. @@ -58,41 +85,204 @@ impl CachedCredentialStore { /// Use this when the caller already holds an `Arc` /// (e.g. when sharing the same backing store across multiple wrappers). #[must_use] - pub fn with_arc(inner: Arc, config: SwrCacheConfig) -> Self { + pub fn with_arc( + inner: Arc, + config: SwrCacheConfig, + region: &str, + workers: usize, + ) -> Self { + let region: Arc = Arc::from(region); Self { - cache: SwrCache::new(Self::build_loader(inner), config), + cache: SwrCache::new(Self::build_loader(&inner, ®ion), config), + inner, + region, + buffers: BufferPool::new(workers), } } /// Construct a pass-through wrapper that bypasses the cache on every /// lookup. Used when `auth.cache.enabled = false`. #[must_use] - pub fn pass_through(inner: T, config: SwrCacheConfig) -> Self + pub fn pass_through(inner: T, config: SwrCacheConfig, region: &str, workers: usize) -> Self where T: CredentialStore + 'static, { let inner: Arc = Arc::new(inner); - Self::pass_through_arc(inner, config) + Self::pass_through_arc(inner, config, region, workers) } /// Like [`Self::pass_through`] but accepts an `Arc`. #[must_use] - pub fn pass_through_arc(inner: Arc, config: SwrCacheConfig) -> Self { + pub fn pass_through_arc( + inner: Arc, + config: SwrCacheConfig, + region: &str, + workers: usize, + ) -> Self { + let region: Arc = Arc::from(region); Self { - cache: SwrCache::pass_through(Self::build_loader(inner), config), + cache: SwrCache::pass_through(Self::build_loader(&inner, ®ion), config), + inner, + region, + buffers: BufferPool::new(workers), } } + /// The region signing keys are derived for. + #[must_use] + pub fn region(&self) -> &str { + &self.region + } + fn build_loader( - inner: Arc, - ) -> Loader { + inner: &Arc, + region: &Arc, + ) -> Loader, DynamoDbError> { + let inner = Arc::clone(inner); + let region = Arc::clone(region); Arc::new(move |access_key_id: String| - -> BoxFuture<'static, Result, DynamoDbError>> { + -> BoxFuture<'static, Result>, DynamoDbError>> { let inner = inner.clone(); - async move { inner.lookup_credential(&access_key_id).await }.boxed() + let region = region.clone(); + async move { load(&*inner, ®ion, &access_key_id).await }.boxed() }) } + /// The entry of `access_key_id` with its signing key for `scope_date` + /// (`YYYYMMDD`, checked against `X-Amz-Date` by `check_scope`). + /// + /// A hit derives nothing. A miss is one decrypt through the inner store + /// and one derive per scope date valid now. A hit whose entry has no key + /// for `scope_date` (a new date) is one decrypt and one derive, into the + /// slot of a stale date when both are taken. When that read names another + /// identity than the entry, the entry is dropped and the read answers. + /// When the key store has no free slot the key is derived into a + /// temporary buffer and not cached, with a warning at most once a + /// minute. The slot or buffer is taken after the decrypt, so none is + /// held across the inner store's await. + /// + /// # Errors + /// + /// `ExpiredTokenException` for a session past `expires_at`, + /// `InvalidSignatureException` for a `scope_date` that is not eight + /// bytes, `InternalServerError` when the key store has no free slot and + /// no temporary buffer is free, and the inner store's errors. + pub async fn lookup( + &self, + access_key_id: &str, + scope_date: &str, + ) -> Result, DynamoDbError> { + let Some(date) = ScopeDate::parse(scope_date) else { + return Err(DynamoDbError::InvalidSignatureException( + SCOPE_DATE_COMPLAINT.to_owned(), + )); + }; + let Some(entry) = self.cache.get(access_key_id.to_owned()).await? else { + return Ok(None); + }; + // CB-12 (cache-hit path): the storage layer enforces session expiry on + // load, but a cached session credential survives until `ttl_seconds` + // even if its `expires_at` has passed. Re-validate on every hit so + // the cache cannot extend a session past its issued lifetime. + // Mirror the storage-layer error so the cache is transparent to the + // auth provider. + let now = OffsetDateTime::now_utc(); + if entry.is_session + && let Some(expires_at) = entry.expires_at + && expires_at < now + { + // Drop the stale entry so the next lookup goes straight to the + // storage layer (which will raise ExpiredTokenException itself, + // or return the post-rotation credential if one exists). + self.cache.invalidate(&access_key_id.to_owned()).await; + return Err(DynamoDbError::ExpiredTokenException( + "The security token included in the request is expired".to_owned(), + )); + } + if let Some(slot) = entry.key(date) { + return Ok(Some(ResolvedCredential { + entry, + key: Key::Slot(slot), + })); + } + // A new scope date, or a key the loader could not place: one decrypt + // and one derive. The secret is read first and the slot or buffer is + // taken after the read, so none is held across the inner store's + // await: other requests on this worker thread run during that await. + let Some(secret) = Secret::read(&*self.inner, access_key_id).await? else { + self.cache.invalidate(&access_key_id.to_owned()).await; + return Ok(None); + }; + // The key comes from this read, so the identity does too. When the + // read names another identity than the entry (the access key ID was + // deleted and imported for another principal, or changed, through + // another server), the entry is dropped and this read answers. + let read = secret.fields(); + let entry = if read.same_identity(&entry) { + entry + } else { + self.cache.invalidate(&access_key_id.to_owned()).await; + Arc::new(read) + }; + let mut destination = self.destination()?; + secret.derive_into( + date, + &self.region, + match &mut destination { + Destination::Slot(slot) => slot.expose_mut(), + Destination::Buffer(lease) => lease.expose_mut(), + }, + ); + drop(secret); + let key = match destination { + Destination::Slot(slot) => { + let slot = Arc::new(slot); + entry.insert_key(date, Arc::clone(&slot), now); + Key::Slot(slot) + } + Destination::Buffer(lease) => Key::Buffer(lease), + }; + Ok(Some(ResolvedCredential { entry, key })) + } + + /// Where the next derived key goes: a slot of the key store, or, when + /// the store has no free slot, a temporary buffer that serves this + /// request only. + /// + /// # Errors + /// + /// `InternalServerError` when no buffer is free either: the key is never + /// derived into unlocked memory. + fn destination(&self) -> Result { + match KeySlot::new() { + Ok(slot) => Ok(Destination::Slot(slot)), + Err(StoreFull) => { + let Some(lease) = self.buffers.lease() else { + if self.buffers.exhausted_warning.due() { + tracing::warn!( + cache = self.cache.name(), + "the locked key store has no free slot and every temporary buffer \ + is in use; the request fails rather than derive a signing key into \ + unlocked memory" + ); + } + return Err(DynamoDbError::InternalServerError( + AUTH_INTERNAL_ERROR.to_owned(), + )); + }; + if self.buffers.full_warning.due() { + tracing::warn!( + cache = self.cache.name(), + live_entries = self.cache.entry_count(), + "the locked key store has no free slot; signing keys are derived into \ + a temporary buffer and not cached until eviction frees slots" + ); + } + Ok(Destination::Buffer(lease)) + } + } + } + /// Drop the cached entry for `access_key_id`. The next lookup will /// re-fetch from the inner store. Used by management endpoints (e.g. /// `CreateAccessKey`, `DeleteAccessKey`, `UpdateAccessKey` status change) @@ -165,326 +355,66 @@ impl CachedCredentialStore { } } -#[async_trait::async_trait] -impl CredentialStore for CachedCredentialStore { - async fn lookup_credential( - &self, - access_key_id: &str, - ) -> Result, DynamoDbError> { - let result = self.cache.get(access_key_id.to_owned()).await?; - // CB-12 (cache-hit path): the storage layer enforces session expiry on - // load, but a cached session credential survives until `ttl_seconds` - // even if its `expires_at` has passed. Re-validate on every hit so - // the cache cannot extend a session past its issued lifetime. - // Mirror the storage-layer error so the cache is transparent to the - // auth provider. - if let Some(ref cred) = result - && cred.is_session - && let Some(expires_at) = cred.expires_at - && expires_at < time::OffsetDateTime::now_utc() - { - // Drop the stale entry so the next lookup goes - // straight to the storage layer (which will raise - // ExpiredTokenException itself, or return the - // post-rotation credential if one exists). - self.cache.invalidate(&access_key_id.to_owned()).await; - return Err(DynamoDbError::ExpiredTokenException( - "The security token included in the request is expired".to_owned(), - )); - } - Ok(result) +/// The loader of a miss: one read, then a slot for each scope date valid +/// now, each filled by [`Secret::derive_into`]. The slots are taken after +/// the read, so a miss holds none across the inner store's await. +async fn load( + inner: &dyn CredentialStore, + region: &str, + access_key_id: &str, +) -> Result>, DynamoDbError> { + let Some(secret) = Secret::read(inner, access_key_id).await? else { + return Ok(None); + }; + let now = OffsetDateTime::now_utc(); + let (today, adjacent) = valid_dates(now); + let entry = secret.fields(); + for date in std::iter::once(today).chain(adjacent) { + // A full store leaves the entry without keys; `lookup` then derives + // into a temporary buffer for each request until eviction frees slots. + let Ok(mut slot) = KeySlot::new() else { + break; + }; + secret.derive_into(date, region, slot.expose_mut()); + entry.insert_key(date, Arc::new(slot), now); } + Ok(Some(Arc::new(entry))) } -#[cfg(test)] -mod tests { - use std::sync::Mutex; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::time::Duration; - - use super::*; - - /// In-process credential store backed by a Mutex-protected map. Counts - /// `lookup_credential` invocations so tests can assert cache behavior. - struct CountingCredStore { - creds: Mutex>, - calls: AtomicUsize, - } - - impl CountingCredStore { - fn new() -> Self { - Self { - creds: Mutex::new(std::collections::HashMap::new()), - calls: AtomicUsize::new(0), - } - } - - fn insert(&self, key: &str, cred: StoredCredential) { - self.creds.lock().unwrap().insert(key.to_owned(), cred); - } - - fn remove(&self, key: &str) { - self.creds.lock().unwrap().remove(key); - } - - fn calls(&self) -> usize { - self.calls.load(Ordering::SeqCst) - } - } - - #[async_trait::async_trait] - impl CredentialStore for CountingCredStore { - async fn lookup_credential( - &self, - access_key_id: &str, - ) -> Result, DynamoDbError> { - self.calls.fetch_add(1, Ordering::SeqCst); - Ok(self.creds.lock().unwrap().get(access_key_id).cloned()) - } - } - - fn make_cred(secret: &str, principal: &str) -> StoredCredential { - StoredCredential { - secret_key: secret.to_owned(), - account_id: "123456789012".to_owned(), - principal_name: principal.to_owned(), - session_name: None, - is_session: false, - session_token: None, - is_active: true, - expires_at: None, - } - } - - fn fast_config() -> SwrCacheConfig { - SwrCacheConfig { - ttl: Duration::from_millis(200), - soft_ttl: Duration::from_millis(50), - negative_ttl: Duration::from_millis(50), - max_entries: 100, - name: "test-cred", - } - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn invalidate_principal_drops_all_keys_for_user() { - let inner = Arc::new(CountingCredStore::new()); - inner.insert("AKIAALICE1", make_cred("s1", "alice")); - inner.insert("AKIAALICE2", make_cred("s2", "alice")); - inner.insert("AKIABOB", make_cred("s3", "bob")); - let store = CachedCredentialStore::with_arc(inner.clone(), fast_config()); - - // Prime all three. - let _ = store.lookup_credential("AKIAALICE1").await.unwrap(); - let _ = store.lookup_credential("AKIAALICE2").await.unwrap(); - let _ = store.lookup_credential("AKIABOB").await.unwrap(); - assert_eq!(inner.calls(), 3); - - store.invalidate_principal("123456789012", "alice").unwrap(); - store.cache.run_pending_tasks().await; - - // Re-fetch each. - let _ = store.lookup_credential("AKIAALICE1").await.unwrap(); - let _ = store.lookup_credential("AKIAALICE2").await.unwrap(); - let _ = store.lookup_credential("AKIABOB").await.unwrap(); - assert_eq!( - inner.calls(), - 5, - "alice's two keys re-fetched (2); bob still cached (0). Initial=3, total=5." - ); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn invalidate_account_drops_all_creds_for_account() { - let inner = Arc::new(CountingCredStore::new()); - let mut a1 = make_cred("s1", "alice"); - a1.account_id = "a1".to_owned(); - let mut a2 = make_cred("s2", "alice"); - a2.account_id = "a2".to_owned(); - inner.insert("AKIAA1", a1); - inner.insert("AKIAA2", a2); - let store = CachedCredentialStore::with_arc(inner.clone(), fast_config()); - - let _ = store.lookup_credential("AKIAA1").await.unwrap(); - let _ = store.lookup_credential("AKIAA2").await.unwrap(); - assert_eq!(inner.calls(), 2); - - store.invalidate_account("a1").unwrap(); - store.cache.run_pending_tasks().await; - - let _ = store.lookup_credential("AKIAA1").await.unwrap(); - let _ = store.lookup_credential("AKIAA2").await.unwrap(); - assert_eq!( - inner.calls(), - 3, - "AKIAA1 (account a1) re-fetched; AKIAA2 (account a2) still cached" - ); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn pass_through_skips_cache_on_every_lookup() { - let inner = Arc::new(CountingCredStore::new()); - inner.insert("AKIATEST", make_cred("s", "alice")); - let store = CachedCredentialStore::pass_through_arc(inner.clone(), fast_config()); - - for _ in 0..5 { - let r = store.lookup_credential("AKIATEST").await.unwrap().unwrap(); - assert_eq!(r.principal_name, "alice"); - } - assert_eq!( - inner.calls(), - 5, - "pass-through must invoke inner store on every call" - ); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn second_lookup_hits_cache() { - let inner = Arc::new(CountingCredStore::new()); - inner.insert("AKIATEST", make_cred("s", "alice")); - let store = CachedCredentialStore::with_arc(inner.clone(), fast_config()); - - let r1 = store.lookup_credential("AKIATEST").await.unwrap().unwrap(); - let r2 = store.lookup_credential("AKIATEST").await.unwrap().unwrap(); - - assert_eq!(r1.principal_name, "alice"); - assert_eq!(r2.principal_name, "alice"); - assert_eq!(inner.calls(), 1, "second lookup must hit cache"); +/// The stored credential of one access key, read through the inner store. +/// The one place that sees the secret: it derives signing keys and gives the +/// credential's fields, and dropping it wipes the secret and the token +/// (`StoredCredential` is `ZeroizeOnDrop`). A later key process (RFC-0000, +/// section 6.3) replaces it with a call that returns the signing keys. +struct Secret(StoredCredential); + +impl Secret { + /// Decrypt the stored secret of `access_key_id` through `inner`. `None` + /// when the key does not exist. Callers take their slot or temporary + /// buffer after this returns, never before. + async fn read( + inner: &dyn CredentialStore, + access_key_id: &str, + ) -> Result, DynamoDbError> { + Ok(inner.lookup_credential(access_key_id).await?.map(Self)) } - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn invalidate_forces_refetch() { - let inner = Arc::new(CountingCredStore::new()); - inner.insert("AKIATEST", make_cred("s", "alice")); - let store = CachedCredentialStore::with_arc(inner.clone(), fast_config()); - - let _ = store.lookup_credential("AKIATEST").await.unwrap(); - store.invalidate("AKIATEST").await; - let _ = store.lookup_credential("AKIATEST").await.unwrap(); - - assert_eq!( - inner.calls(), - 2, - "invalidation must force a re-fetch from the inner store" + /// Derive the signing key of `date` into `out`. + fn derive_into(&self, date: ScopeDate, region: &str, out: &mut [u8; 32]) { + derive_signing_key_into( + self.0.secret_key.as_bytes(), + date.as_str(), + region, + SERVICE, + out, ); } - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn negative_lookup_is_cached_then_picks_up_new_key_after_negative_ttl() { - let inner = Arc::new(CountingCredStore::new()); - let store = CachedCredentialStore::with_arc(inner.clone(), fast_config()); - - // Initially missing. - let r1 = store.lookup_credential("AKIANEW").await.unwrap(); - assert!(r1.is_none()); - - // Within negative_ttl, second call hits cache. - let r2 = store.lookup_credential("AKIANEW").await.unwrap(); - assert!(r2.is_none()); - assert_eq!(inner.calls(), 1); - - // Operator inserts the key. - inner.insert("AKIANEW", make_cred("s", "bob")); - - // Wait past negative_ttl (50ms). - tokio::time::sleep(Duration::from_millis(80)).await; - - // Lookup now sees it. - let r3 = store.lookup_credential("AKIANEW").await.unwrap().unwrap(); - assert_eq!(r3.principal_name, "bob"); - } - - /// CB-12 (cache-hit path): a cached session credential whose `expires_at` - /// has passed must NOT authenticate, even when the cache TTL hasn't - /// elapsed yet. Without the cache-hit expiry check, a session could - /// keep working for up to `auth.cache.ttl_seconds` past its expiry. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn cached_session_past_expires_at_returns_expired_token() { - let inner = Arc::new(CountingCredStore::new()); - // A session that "expires" 10 seconds in the past. The CountingCredStore - // mock returns the credential unconditionally; the wrapper layer is - // what we're testing here. - let mut cred = make_cred("s", "alice"); - cred.is_session = true; - cred.session_token = Some("tok".to_owned()); - cred.expires_at = Some(time::OffsetDateTime::now_utc() - time::Duration::seconds(10)); - inner.insert("ASIATEST00000000", cred); - - let store = CachedCredentialStore::with_arc(inner.clone(), fast_config()); - - let r1 = store.lookup_credential("ASIATEST00000000").await; - match r1 { - Err(DynamoDbError::ExpiredTokenException(_)) => {} - Err(other) => { - panic!("expected ExpiredTokenException from cache-hit expiry check, got {other:?}") - } - Ok(_) => panic!("expected ExpiredTokenException, got Ok"), - } - // The cached entry was dropped on the expiry check. A second call - // re-hits the inner store rather than serving the cached expired cred. - let calls_after_first = inner.calls(); - let r2 = store.lookup_credential("ASIATEST00000000").await; - match r2 { - Err(DynamoDbError::ExpiredTokenException(_)) => {} - Err(other) => { - panic!("expected ExpiredTokenException on re-fetch, got {other:?}") - } - Ok(_) => panic!("expected ExpiredTokenException on re-fetch, got Ok"), - } - assert!( - inner.calls() > calls_after_first, - "expired-session cache hit must drop the entry, forcing a re-fetch on the next call \ - (calls_after_first={calls_after_first}, after_second={})", - inner.calls() - ); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn invalidation_after_delete_returns_none() { - let inner = Arc::new(CountingCredStore::new()); - inner.insert("AKIATEST", make_cred("s", "alice")); - let store = CachedCredentialStore::with_arc(inner.clone(), fast_config()); - - // Prime cache. - let r1 = store.lookup_credential("AKIATEST").await.unwrap().unwrap(); - assert_eq!(r1.principal_name, "alice"); - - // Simulate admin deletion: remove from inner, invalidate cache. - inner.remove("AKIATEST"); - store.invalidate("AKIATEST").await; - - // Next lookup reflects the deletion. - let r2 = store.lookup_credential("AKIATEST").await.unwrap(); - assert!(r2.is_none(), "post-invalidation lookup must see deletion"); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn many_concurrent_lookups_for_same_key_collapse_to_few_loads() { - let inner = Arc::new(CountingCredStore::new()); - inner.insert("AKIATEST", make_cred("s", "alice")); - let store = CachedCredentialStore::with_arc(inner.clone(), fast_config()); - - let mut handles = Vec::new(); - for _ in 0..64 { - let store = store.clone(); - handles.push(tokio::spawn(async move { - store.lookup_credential("AKIATEST").await.unwrap().unwrap() - })); - } - for h in handles { - let _ = h.await.unwrap(); - } - - // The cache deduplicates *post-warmup*; cold-start may incur a few - // duplicate inserts on the way to the first cached entry. Verify the - // deduplication is meaningful (≤ caller count, and warmup is cheap). - let n = inner.calls(); - assert!( - n <= 64, - "loader call count must not exceed concurrent caller count, got {n}" - ); - // Once warm, no further lookups. - let _ = store.lookup_credential("AKIATEST").await.unwrap(); - assert_eq!(inner.calls(), n, "warm lookup must hit cache"); + /// The credential's fields, with no keys. + fn fields(&self) -> CachedCredential { + CachedCredential::from_stored(&self.0) } } + +#[cfg(test)] +mod tests; diff --git a/crates/auth/src/credential_cache/entry.rs b/crates/auth/src/credential_cache/entry.rs new file mode 100644 index 000000000..9a43f2910 --- /dev/null +++ b/crates/auth/src/credential_cache/entry.rs @@ -0,0 +1,325 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The cache entry of one access key, the value `lookup` gives a request, +//! the scope-date rules, and the temporary buffers of the cache. + +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use sha2::{Digest, Sha256}; +use time::OffsetDateTime; +use zeroize::Zeroize; + +use crate::StoredCredential; +use crate::secmem::{KeySlot, StoreFull}; +use crate::sigv4::verify::constant_time_eq; + +/// The clock skew the server accepts, which decides when two scope dates are +/// valid at once (`verify.rs`, `MAX_CLOCK_SKEW_SECS`). +const SKEW: time::Duration = time::Duration::seconds(15 * 60); + +/// A `SigV4` scope date, `YYYYMMDD`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct ScopeDate([u8; 8]); + +/// The signing key of one scope date, shared with the requests that use it. +pub(super) type DatedKey = (ScopeDate, Arc); + +impl ScopeDate { + pub(super) fn parse(date: &str) -> Option { + date.as_bytes().try_into().ok().map(Self) + } + + pub(super) fn of(date: time::Date) -> Self { + let text = format!( + "{:04}{:02}{:02}", + date.year(), + u8::from(date.month()), + date.day() + ); + // A year outside four digits cannot come from a server clock; the + // all-zero date matches no request and only skips caching. + Self::parse(&text).unwrap_or(Self([b'0'; 8])) + } + + pub(super) fn as_str(&self) -> &str { + std::str::from_utf8(&self.0).unwrap_or("") + } +} + +/// The scope dates the server accepts at `now`: the UTC date, and the +/// adjacent date when `now` is within the skew window of midnight. From +/// 23:45 to 00:15 UTC one access key can therefore need two signing keys. +pub(super) fn valid_dates(now: OffsetDateTime) -> (ScopeDate, Option) { + let today = now.date(); + let adjacent = if now.time() < time::Time::MIDNIGHT + SKEW { + today.previous_day() + } else if now.time() >= time::Time::MIDNIGHT - SKEW { + today.next_day() + } else { + None + }; + (ScopeDate::of(today), adjacent.map(ScopeDate::of)) +} + +/// The cache entry of one access key. No plaintext secret, no plaintext +/// token. +pub struct CachedCredential { + /// The account ID that owns this credential. + pub account_id: String, + /// The user name (for AKIA* keys) or role name (for ASIA* session keys). + pub principal_name: String, + /// For session credentials: the session name. + pub session_name: Option, + /// Whether this is a session credential (ASIA*). + pub is_session: bool, + /// Whether the credential is active. Inactive keys are cached so the auth + /// layer can produce the correct error response. + pub is_active: bool, + /// For session credentials: the absolute expiry time. Auth checks this + /// on every cache hit so cached sessions do not outlive their + /// `expires_at` window. + pub expires_at: Option, + /// The SHA-256 of the session token. + session_token_hash: Option<[u8; 32]>, + /// The signing key of each scope date in use, at most two. + pub(super) keys: Mutex<[Option; 2]>, +} + +impl CachedCredential { + pub(super) fn from_stored(stored: &StoredCredential) -> Self { + Self { + account_id: stored.account_id.clone(), + principal_name: stored.principal_name.clone(), + session_name: stored.session_name.clone(), + is_session: stored.is_session, + is_active: stored.is_active, + expires_at: stored.expires_at, + session_token_hash: stored + .session_token + .as_deref() + .map(|token| Sha256::digest(token.as_bytes()).into()), + keys: Mutex::new([None, None]), + } + } + + /// Whether `other` names the same identity: every field but the keys. + pub(super) fn same_identity(&self, other: &Self) -> bool { + let Self { + account_id, + principal_name, + session_name, + is_session, + is_active, + expires_at, + session_token_hash, + keys: _, + } = self; + *account_id == other.account_id + && *principal_name == other.principal_name + && *session_name == other.session_name + && *is_session == other.is_session + && *is_active == other.is_active + && *expires_at == other.expires_at + && *session_token_hash == other.session_token_hash + } + + /// Whether `presented` is the session token: its SHA-256 is compared + /// with the stored hash in constant time, over a fixed 32 bytes, so + /// neither the token's contents nor its length changes the timing. + /// `false` for a long-term key, which has no token. + #[must_use] + pub fn session_token_matches(&self, presented: &str) -> bool { + let Some(stored) = &self.session_token_hash else { + return false; + }; + let presented: [u8; 32] = Sha256::digest(presented.as_bytes()).into(); + constant_time_eq(&presented, stored) + } + + pub(super) fn key(&self, date: ScopeDate) -> Option> { + self.keys + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .flatten() + .find(|(d, _)| *d == date) + .map(|(_, slot)| Arc::clone(slot)) + } + + /// Record `slot` as the signing key of `date`, in a free position, in + /// the position that already holds `date` (two requests derived it at + /// once), or in the position of a stale date: one that is neither the + /// current UTC date nor the adjacent date inside the skew window at + /// `now`. When both positions hold other valid dates, the key serves this + /// request only. + pub(super) fn insert_key(&self, date: ScopeDate, slot: Arc, now: OffsetDateTime) { + let (today, adjacent) = valid_dates(now); + let mut keys = self.keys.lock().unwrap_or_else(PoisonError::into_inner); + let position = keys.iter().position(|k| match k { + None => true, + Some((d, _)) => *d == date || (*d != today && Some(*d) != adjacent), + }); + if let Some(position) = position { + keys[position] = Some((date, slot)); + } + } +} + +/// What `lookup` gives one request: the entry, and the signing key of the +/// request's scope date. The key is in the entry's slot, or in a temporary +/// buffer that is wiped and returned to the pool when this value drops. +pub struct ResolvedCredential { + pub(super) entry: Arc, + pub(super) key: Key, +} + +pub(super) enum Key { + Slot(Arc), + Buffer(BufferLease), +} + +/// Where a key about to be derived goes. +pub(super) enum Destination { + Slot(KeySlot), + Buffer(BufferLease), +} + +impl ResolvedCredential { + /// The cached fields of the credential. + #[must_use] + pub fn credential(&self) -> &CachedCredential { + &self.entry + } + + /// The 32-byte `SigV4` signing key for the request's scope date. + #[must_use] + pub fn signing_key(&self) -> &[u8; 32] { + match &self.key { + Key::Slot(slot) => slot.expose(), + Key::Buffer(lease) => lease.expose(), + } + } +} + +impl std::fmt::Debug for ResolvedCredential { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ResolvedCredential") + .field("account_id", &self.entry.account_id) + .field("principal_name", &self.entry.principal_name) + .field("is_session", &self.entry.is_session) + .field("is_active", &self.entry.is_active) + .field( + "key", + &match &self.key { + Key::Slot(_) => "slot", + Key::Buffer(_) => "temporary buffer", + }, + ) + .finish_non_exhaustive() + } +} + +/// The temporary buffers of a cache: one slot per runtime worker thread, +/// reserved when the cache is built, for a miss that finds the key store +/// full. A request takes its buffer after the credential read, and the +/// derive and the signature check then run in one synchronous section, so +/// each worker thread holds one buffer at a time. +pub(super) struct BufferPool { + free: Mutex>, + pub(super) full_warning: Warning, + pub(super) exhausted_warning: Warning, +} + +impl BufferPool { + pub(super) fn new(workers: usize) -> Arc { + let mut free = Vec::with_capacity(workers); + for _ in 0..workers { + match KeySlot::new() { + Ok(slot) => free.push(slot), + Err(StoreFull) => { + tracing::error!( + reserved = free.len(), + wanted = workers, + "the locked key store is too small to reserve one temporary buffer \ + per worker thread; it needs two slots per cache entry, one per key \ + that startup loads, and one per worker thread" + ); + break; + } + } + } + Arc::new(Self { + free: Mutex::new(free), + full_warning: Warning::default(), + exhausted_warning: Warning::default(), + }) + } + + pub(super) fn lease(self: &Arc) -> Option { + let slot = self + .free + .lock() + .unwrap_or_else(PoisonError::into_inner) + .pop()?; + Some(BufferLease { + pool: Arc::clone(self), + slot: Some(slot), + }) + } +} + +/// A temporary buffer on loan from the pool, wiped and returned on drop. +pub(super) struct BufferLease { + pool: Arc, + /// `Some` until `drop` returns the slot to the pool. + slot: Option, +} + +impl BufferLease { + pub(super) fn expose(&self) -> &[u8; 32] { + self.slot + .as_ref() + .expect("a leased buffer holds its slot until it drops") + .expose() + } + + pub(super) fn expose_mut(&mut self) -> &mut [u8; 32] { + self.slot + .as_mut() + .expect("a leased buffer holds its slot until it drops") + .expose_mut() + } +} + +impl Drop for BufferLease { + fn drop(&mut self) { + if let Some(mut slot) = self.slot.take() { + slot.expose_mut().zeroize(); + self.pool + .free + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(slot); + } + } +} + +/// A warning logged at most once a minute. +#[derive(Default)] +pub(super) struct Warning { + last: Mutex>, +} + +impl Warning { + pub(super) fn due(&self) -> bool { + let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); + let now = Instant::now(); + if last.is_some_and(|t| now.duration_since(t) < Duration::from_secs(60)) { + return false; + } + *last = Some(now); + true + } +} diff --git a/crates/auth/src/credential_cache/tests.rs b/crates/auth/src/credential_cache/tests.rs new file mode 100644 index 000000000..8a079ce77 --- /dev/null +++ b/crates/auth/src/credential_cache/tests.rs @@ -0,0 +1,688 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use super::*; +use crate::StoredCredential; +use crate::secmem; +use crate::sigv4::signing_key::derive_signing_key; +use crate::test_support::{is_child, run_test_in_child}; + +const SECRET: &str = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; +const REGION: &str = "us-east-1"; + +/// In-process credential store backed by a Mutex-protected map. Counts +/// `lookup_credential` invocations, which is the decrypt count, so tests can +/// assert cache behavior. +struct CountingCredStore { + creds: Mutex>, + calls: AtomicUsize, +} + +impl CountingCredStore { + fn new() -> Self { + Self { + creds: Mutex::new(std::collections::HashMap::new()), + calls: AtomicUsize::new(0), + } + } + + fn insert(&self, key: &str, cred: StoredCredential) { + self.creds.lock().unwrap().insert(key.to_owned(), cred); + } + + fn remove(&self, key: &str) { + self.creds.lock().unwrap().remove(key); + } + + fn calls(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } +} + +#[async_trait::async_trait] +impl CredentialStore for CountingCredStore { + async fn lookup_credential( + &self, + access_key_id: &str, + ) -> Result, DynamoDbError> { + self.calls.fetch_add(1, Ordering::SeqCst); + Ok(self.creds.lock().unwrap().get(access_key_id).cloned()) + } +} + +fn make_cred(secret: &str, principal: &str) -> StoredCredential { + StoredCredential { + secret_key: secret.to_owned(), + account_id: "123456789012".to_owned(), + principal_name: principal.to_owned(), + session_name: None, + is_session: false, + session_token: None, + is_active: true, + expires_at: None, + } +} + +fn fast_config() -> SwrCacheConfig { + SwrCacheConfig { + ttl: Duration::from_millis(200), + soft_ttl: Duration::from_millis(50), + negative_ttl: Duration::from_millis(50), + max_entries: 100, + name: "test-cred", + } +} + +fn cached(inner: Arc) -> CachedCredentialStore { + CachedCredentialStore::with_arc(inner, fast_config(), REGION, 1) +} + +/// A UTC instant from its calendar fields. +fn at(year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> OffsetDateTime { + let date = + time::Date::from_calendar_date(year, time::Month::try_from(month).unwrap(), day).unwrap(); + date.with_hms(hour, minute, second).unwrap().assume_utc() +} + +/// The scope date of the current UTC date. +fn today() -> String { + ScopeDate::of(OffsetDateTime::now_utc().date()) + .as_str() + .to_owned() +} + +async fn lookup(store: &CachedCredentialStore, key: &str) -> Option { + store.lookup(key, &today()).await.unwrap() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn invalidate_principal_drops_all_keys_for_user() { + let inner = Arc::new(CountingCredStore::new()); + inner.insert("AKIAALICE1", make_cred("s1", "alice")); + inner.insert("AKIAALICE2", make_cred("s2", "alice")); + inner.insert("AKIABOB", make_cred("s3", "bob")); + let store = cached(inner.clone()); + + // Prime all three. + let _ = lookup(&store, "AKIAALICE1").await.unwrap(); + let _ = lookup(&store, "AKIAALICE2").await.unwrap(); + let _ = lookup(&store, "AKIABOB").await.unwrap(); + assert_eq!(inner.calls(), 3); + + store.invalidate_principal("123456789012", "alice").unwrap(); + store.cache.run_pending_tasks().await; + + // Re-fetch each. + let _ = lookup(&store, "AKIAALICE1").await.unwrap(); + let _ = lookup(&store, "AKIAALICE2").await.unwrap(); + let _ = lookup(&store, "AKIABOB").await.unwrap(); + assert_eq!( + inner.calls(), + 5, + "alice's two keys re-fetched (2); bob still cached (0). Initial=3, total=5." + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn invalidate_account_drops_all_creds_for_account() { + let inner = Arc::new(CountingCredStore::new()); + let mut a1 = make_cred("s1", "alice"); + a1.account_id = "a1".to_owned(); + let mut a2 = make_cred("s2", "alice"); + a2.account_id = "a2".to_owned(); + inner.insert("AKIAA1", a1); + inner.insert("AKIAA2", a2); + let store = cached(inner.clone()); + + let _ = lookup(&store, "AKIAA1").await.unwrap(); + let _ = lookup(&store, "AKIAA2").await.unwrap(); + assert_eq!(inner.calls(), 2); + + store.invalidate_account("a1").unwrap(); + store.cache.run_pending_tasks().await; + + let _ = lookup(&store, "AKIAA1").await.unwrap(); + let _ = lookup(&store, "AKIAA2").await.unwrap(); + assert_eq!( + inner.calls(), + 3, + "AKIAA1 (account a1) re-fetched; AKIAA2 (account a2) still cached" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn pass_through_skips_cache_on_every_lookup() { + let inner = Arc::new(CountingCredStore::new()); + inner.insert("AKIATEST", make_cred("s", "alice")); + let store = CachedCredentialStore::pass_through_arc(inner.clone(), fast_config(), REGION, 1); + + for _ in 0..5 { + let r = lookup(&store, "AKIATEST").await.unwrap(); + assert_eq!(r.credential().principal_name, "alice"); + } + assert_eq!( + inner.calls(), + 5, + "pass-through must invoke inner store on every call" + ); +} + +/// A second lookup for the same key and date is a hit: no decrypt, and the +/// signing key is the one the miss derived, which equals the key +/// `derive_signing_key` gives for the same inputs. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn second_lookup_hits_cache_and_derives_nothing() { + let inner = Arc::new(CountingCredStore::new()); + inner.insert("AKIATEST", make_cred(SECRET, "alice")); + let store = cached(inner.clone()); + let date = today(); + + let r1 = store.lookup("AKIATEST", &date).await.unwrap().unwrap(); + let r2 = store.lookup("AKIATEST", &date).await.unwrap().unwrap(); + + assert_eq!(r1.credential().principal_name, "alice"); + assert_eq!(r2.credential().principal_name, "alice"); + assert_eq!(inner.calls(), 1, "second lookup must hit cache"); + let expected = derive_signing_key(SECRET, &date, REGION, "dynamodb"); + assert_eq!(r1.signing_key(), &*expected); + assert_eq!(r2.signing_key(), &*expected); +} + +/// A cached key asked for a scope date it has no key for costs one decrypt +/// and one derive. When that read gives the entry's identity, the new key is +/// cached beside the first. When it gives another (the access key ID was +/// deleted and imported for another principal, or changed, through another +/// server that shares the catalog), the request is answered from that read +/// with its key, and the entry is dropped. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_new_scope_date_is_one_decrypt_and_answers_from_that_read() { + /// The change to the credential before the new date's read, and whether + /// the entry is kept. + type Case = (fn(&mut StoredCredential), bool); + let cases: [Case; 8] = [ + (|_| {}, true), + (|c| *c = make_cred("bobSecretAccessKey", "bob"), false), + (|c| c.account_id = "210987654321".to_owned(), false), + (|c| c.session_name = Some("s".to_owned()), false), + (|c| c.is_session = true, false), + (|c| c.session_token = Some("t".to_owned()), false), + (|c| c.is_active = false, false), + (|c| c.expires_at = Some(OffsetDateTime::UNIX_EPOCH), false), + ]; + for (row, (change, kept)) in cases.into_iter().enumerate() { + let mut cred = make_cred(SECRET, "alice"); + let inner = Arc::new(CountingCredStore::new()); + inner.insert("AKIATEST", cred.clone()); + let store = cached(inner.clone()); + let first = store.lookup("AKIATEST", "20260415").await.unwrap().unwrap(); + change(&mut cred); + inner.insert("AKIATEST", cred.clone()); + let calls = inner.calls(); + let one_date_before = entry::valid_dates(OffsetDateTime::now_utc()).1.is_none(); + let r = store.lookup("AKIATEST", "20260416").await.unwrap().unwrap(); + assert_eq!(inner.calls(), calls + 1, "row {row}: one decrypt"); + let key = derive_signing_key(&cred.secret_key, "20260416", REGION, "dynamodb"); + assert_eq!(r.signing_key(), &*key, "row {row}: the key of the read"); + let read = CachedCredential::from_stored(&cred); + assert!( + r.credential().same_identity(&read), + "row {row}: the read's identity" + ); + let again = store.lookup("AKIATEST", "20260416").await.unwrap().unwrap(); + for answer in [&r, &again] { + assert_eq!(Arc::ptr_eq(&first.entry, &answer.entry), kept, "row {row}"); + } + if kept && one_date_before && entry::valid_dates(OffsetDateTime::now_utc()).1.is_none() { + // From 23:45 to 00:15 UTC the load fills both slots with the two + // valid dates, so the test's fixed date gets no slot to hit. + assert_eq!(inner.calls(), calls + 1, "the new date is a hit now"); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn invalidate_forces_refetch() { + let inner = Arc::new(CountingCredStore::new()); + inner.insert("AKIATEST", make_cred("s", "alice")); + let store = cached(inner.clone()); + + let _ = lookup(&store, "AKIATEST").await.unwrap(); + store.invalidate("AKIATEST").await; + let _ = lookup(&store, "AKIATEST").await.unwrap(); + + assert_eq!( + inner.calls(), + 2, + "invalidation must force a re-fetch from the inner store" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn negative_lookup_is_cached_then_picks_up_new_key_after_negative_ttl() { + let inner = Arc::new(CountingCredStore::new()); + let store = cached(inner.clone()); + + // Initially missing. + let r1 = lookup(&store, "AKIANEW").await; + assert!(r1.is_none()); + + // Within negative_ttl, second call hits cache. + let r2 = lookup(&store, "AKIANEW").await; + assert!(r2.is_none()); + assert_eq!(inner.calls(), 1); + + // Operator inserts the key. + inner.insert("AKIANEW", make_cred("s", "bob")); + + // Wait past negative_ttl (50ms). + tokio::time::sleep(Duration::from_millis(80)).await; + + // Lookup now sees it. + let r3 = lookup(&store, "AKIANEW").await.unwrap(); + assert_eq!(r3.credential().principal_name, "bob"); +} + +/// CB-12 (cache-hit path): a cached session credential whose `expires_at` +/// has passed must NOT authenticate, even when the cache TTL hasn't +/// elapsed yet. Without the cache-hit expiry check, a session could +/// keep working for up to `auth.cache.ttl_seconds` past its expiry. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn cached_session_past_expires_at_returns_expired_token() { + let inner = Arc::new(CountingCredStore::new()); + // A session that "expires" 10 seconds in the past. The CountingCredStore + // mock returns the credential unconditionally; the wrapper layer is + // what we're testing here. + let mut cred = make_cred("s", "alice"); + cred.is_session = true; + cred.session_token = Some("tok".to_owned()); + cred.expires_at = Some(OffsetDateTime::now_utc() - time::Duration::seconds(10)); + inner.insert("ASIATEST00000000", cred); + + let store = cached(inner.clone()); + + let r1 = store.lookup("ASIATEST00000000", &today()).await; + match r1 { + Err(DynamoDbError::ExpiredTokenException(_)) => {} + Err(other) => { + panic!("expected ExpiredTokenException from cache-hit expiry check, got {other:?}") + } + Ok(_) => panic!("expected ExpiredTokenException, got Ok"), + } + // The cached entry was dropped on the expiry check. A second call + // re-hits the inner store rather than serving the cached expired cred. + let calls_after_first = inner.calls(); + let r2 = store.lookup("ASIATEST00000000", &today()).await; + match r2 { + Err(DynamoDbError::ExpiredTokenException(_)) => {} + Err(other) => { + panic!("expected ExpiredTokenException on re-fetch, got {other:?}") + } + Ok(_) => panic!("expected ExpiredTokenException on re-fetch, got Ok"), + } + assert!( + inner.calls() > calls_after_first, + "expired-session cache hit must drop the entry, forcing a re-fetch on the next call \ + (calls_after_first={calls_after_first}, after_second={})", + inner.calls() + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn invalidation_after_delete_returns_none() { + let inner = Arc::new(CountingCredStore::new()); + inner.insert("AKIATEST", make_cred("s", "alice")); + let store = cached(inner.clone()); + + // Prime cache. + let r1 = lookup(&store, "AKIATEST").await.unwrap(); + assert_eq!(r1.credential().principal_name, "alice"); + + // Simulate admin deletion: remove from inner, invalidate cache. + inner.remove("AKIATEST"); + store.invalidate("AKIATEST").await; + + // Next lookup reflects the deletion. + let r2 = lookup(&store, "AKIATEST").await; + assert!(r2.is_none(), "post-invalidation lookup must see deletion"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn many_concurrent_lookups_for_same_key_collapse_to_few_loads() { + let inner = Arc::new(CountingCredStore::new()); + inner.insert("AKIATEST", make_cred("s", "alice")); + let store = cached(inner.clone()); + + let mut handles = Vec::new(); + for _ in 0..64 { + let store = store.clone(); + handles.push(tokio::spawn(async move { + lookup(&store, "AKIATEST") + .await + .unwrap() + .credential() + .account_id + .clone() + })); + } + for h in handles { + let _ = h.await.unwrap(); + } + + // The cache deduplicates *post-warmup*; cold-start may incur a few + // duplicate inserts on the way to the first cached entry. Verify the + // deduplication is meaningful (at most the caller count, and warmup is cheap). + let n = inner.calls(); + assert!( + n <= 64, + "loader call count must not exceed concurrent caller count, got {n}" + ); + // Once warm, no further lookups. + let _ = lookup(&store, "AKIATEST").await.unwrap(); + assert_eq!(inner.calls(), n, "warm lookup must hit cache"); +} + +/// The scope dates valid at a server time: the UTC date alone from 00:15 to +/// 23:45, and the adjacent date too within the 900 s skew window of midnight. +#[test] +fn valid_dates_follow_the_skew_window() { + let cases = [ + (at(2026, 4, 15, 0, 0, 0), "20260415", Some("20260414")), + (at(2026, 4, 15, 0, 14, 59), "20260415", Some("20260414")), + (at(2026, 4, 15, 0, 15, 0), "20260415", None), + (at(2026, 4, 15, 12, 0, 0), "20260415", None), + (at(2026, 4, 15, 23, 44, 59), "20260415", None), + (at(2026, 4, 15, 23, 45, 0), "20260415", Some("20260416")), + (at(2026, 4, 15, 23, 59, 59), "20260415", Some("20260416")), + (at(2026, 12, 31, 23, 50, 0), "20261231", Some("20270101")), + (at(2027, 1, 1, 0, 10, 0), "20270101", Some("20261231")), + ]; + for (now, today, adjacent) in cases { + let (t, a) = valid_dates(now); + assert_eq!(t.as_str(), today, "{now}"); + assert_eq!( + a.map(|d| d.as_str().to_owned()).as_deref(), + adjacent, + "{now}" + ); + } +} + +/// Which slot a new scope date takes: a free one, the one holding the same +/// date, or the one holding a date that is neither the UTC date nor the +/// adjacent date inside the skew window. +#[test] +fn a_new_date_takes_the_slot_of_a_stale_date() { + let slot = || Arc::new(secmem::KeySlot::new().unwrap()); + let date = |s: &str| ScopeDate::parse(s).unwrap(); + // (slots held, now, new date, dates held afterwards, position of the new slot) + let cases = [ + // A free slot is used first. + ( + vec!["20260415"], + at(2026, 4, 15, 23, 50, 0), + "20260416", + vec!["20260415", "20260416"], + Some(1), + ), + // Yesterday is stale at 23:50, so tomorrow takes its slot. + ( + vec!["20260414", "20260415"], + at(2026, 4, 15, 23, 50, 0), + "20260416", + vec!["20260416", "20260415"], + Some(0), + ), + // At 00:10 yesterday is still valid, so the day before is the stale one. + ( + vec!["20260413", "20260414"], + at(2026, 4, 15, 0, 10, 0), + "20260415", + vec!["20260415", "20260414"], + Some(0), + ), + // Both dates valid: the key serves the request only, nothing changes. + ( + vec!["20260414", "20260415"], + at(2026, 4, 15, 0, 10, 0), + "20260416", + vec!["20260414", "20260415"], + None, + ), + // A date derived twice at once replaces its own slot, not a valid one. + ( + vec!["20260414", "20260415"], + at(2026, 4, 15, 0, 10, 0), + "20260415", + vec!["20260414", "20260415"], + Some(1), + ), + ]; + for (held, now, new, expected, position) in cases { + let entry = CachedCredential::from_stored(&make_cred(SECRET, "alice")); + { + let mut keys = entry.keys.lock().unwrap(); + for (i, d) in held.iter().enumerate() { + keys[i] = Some((date(d), slot())); + } + } + let new_slot = slot(); + entry.insert_key(date(new), Arc::clone(&new_slot), now); + let keys = entry.keys.lock().unwrap(); + let after: Vec = keys + .iter() + .flatten() + .map(|(d, _)| d.as_str().to_owned()) + .collect(); + assert_eq!(after, expected, "held {held:?} at {now}, new {new}"); + let found = keys + .iter() + .position(|k| k.as_ref().is_some_and(|(_, s)| Arc::ptr_eq(s, &new_slot))); + assert_eq!(found, position, "held {held:?} at {now}, new {new}"); + } +} + +/// The session token compare: the presented token's SHA-256 against the +/// stored hash. A long-term key matches no token. +#[test] +fn session_token_matches_compares_hashes() { + let session = |token: &str| { + let mut cred = make_cred(SECRET, "alice"); + cred.is_session = true; + cred.session_token = Some(token.to_owned()); + CachedCredential::from_stored(&cred) + }; + let long_term = CachedCredential::from_stored(&make_cred(SECRET, "alice")); + let cases = [ + (&session("stored-token"), "stored-token", true), + (&session("stored-token"), "stored-tokem", false), + (&session("stored-token"), "stored-token-and-more", false), + (&session("stored-token"), "", false), + (&long_term, "stored-token", false), + (&long_term, "", false), + ]; + for (entry, presented, expected) in cases { + assert_eq!( + entry.session_token_matches(presented), + expected, + "{presented:?}" + ); + } +} + +/// A scope date that is not eight bytes is a scope complaint, not a lookup. +#[tokio::test] +async fn a_malformed_scope_date_is_refused_before_the_lookup() { + let inner = Arc::new(CountingCredStore::new()); + inner.insert("AKIATEST", make_cred(SECRET, "alice")); + let store = cached(inner.clone()); + for date in ["", "2026041", "202604155"] { + match store.lookup("AKIATEST", date).await { + Err(DynamoDbError::InvalidSignatureException(msg)) => { + assert_eq!(msg, SCOPE_DATE_COMPLAINT, "{date:?}"); + } + other => panic!("{date:?}: expected InvalidSignatureException, got {other:?}"), + } + } + assert_eq!(inner.calls(), 0); +} + +const FULL_STORE_CHILD: &str = "EXTENDDB_TEST_FULL_STORE_CHILD"; + +/// A store too small for the live entries: the miss derives into a +/// temporary buffer and caches no key, and when every buffer is in use the +/// request fails with `InternalServerError`. Runs in a child process, which +/// owns the process-wide store. +#[test] +fn a_full_store_uses_the_temporary_buffer_then_refuses() { + let output = run_test_in_child( + "credential_cache::tests::full_store_child_process", + FULL_STORE_CHILD, + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn full_store_child_process() { + if !is_child(FULL_STORE_CHILD) { + return; + } + assert_eq!(secmem::init_unlocked(4), secmem::Protection::Unlocked); + let inner = Arc::new(CountingCredStore::new()); + inner.insert("AKIABOB", make_cred(SECRET, "bob")); + // The cache reserves its two buffers; the test holds every other slot. + let store = CachedCredentialStore::with_arc(inner.clone(), fast_config(), REGION, 2); + let mut held = Vec::new(); + while let Ok(slot) = secmem::KeySlot::new() { + held.push(slot); + } + assert_eq!(held.len(), 2); + let date = today(); + let expected = derive_signing_key(SECRET, &date, REGION, "dynamodb"); + + // No free slot: the key is derived into a buffer, and is correct. The + // load caches the fields only, so this first lookup decrypts twice: once + // in the loader and once for the key. + let bob = store.lookup("AKIABOB", &date).await.unwrap().unwrap(); + assert_eq!(bob.signing_key(), &*expected); + assert_eq!(inner.calls(), 2); + // No key was cached: the next lookup decrypts again, into the second + // buffer. + let bob_again = store.lookup("AKIABOB", &date).await.unwrap().unwrap(); + assert_eq!(inner.calls(), 3); + + // Both buffers are on loan: the next miss fails closed. The buffer is + // taken after the read, so the refused request has decrypted once. + match store.lookup("AKIABOB", &date).await { + Err(DynamoDbError::InternalServerError(msg)) => { + assert_eq!(msg, AUTH_INTERNAL_ERROR); + } + other => panic!("expected InternalServerError, got {other:?}"), + } + assert_eq!(inner.calls(), 4); + + // A returned buffer serves the next request. + drop(bob_again); + let third = store.lookup("AKIABOB", &date).await.unwrap().unwrap(); + assert_eq!(inner.calls(), 5); + drop(third); + drop(bob); + + // With a slot free again the key is cached, and the next lookup is a hit. + held.pop(); + let cached = store.lookup("AKIABOB", &date).await.unwrap().unwrap(); + assert_eq!(cached.signing_key(), &*expected); + assert_eq!(inner.calls(), 6); + let _ = store.lookup("AKIABOB", &date).await.unwrap().unwrap(); + assert_eq!(inner.calls(), 6, "the cached key is a hit"); +} + +const ONE_THREAD_CHILD: &str = "EXTENDDB_TEST_ONE_THREAD_CHILD"; + +/// One worker thread, one temporary buffer and no free slot: two requests +/// that wait on the credential read at the same time both succeed, because +/// each takes the buffer after its read and gives it back before its task +/// yields again. Runs in a child process, which owns the process-wide store. +#[test] +fn one_buffer_serves_two_requests_that_wait_on_the_read_at_once() { + let output = run_test_in_child( + "credential_cache::tests::one_thread_child_process", + ONE_THREAD_CHILD, + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +/// A credential store whose read waits, as a database round trip does, so +/// the task yields its worker thread during the read. +struct SlowCredStore(CountingCredStore); + +#[async_trait::async_trait] +impl CredentialStore for SlowCredStore { + async fn lookup_credential( + &self, + access_key_id: &str, + ) -> Result, DynamoDbError> { + tokio::time::sleep(Duration::from_millis(100)).await; + self.0.lookup_credential(access_key_id).await + } +} + +/// One request: the lookup, then a use of the key that ends before the task +/// yields again, as `authenticate` uses it. +async fn key_matches( + store: &CachedCredentialStore, + date: &str, + expected: &[u8; 32], +) -> Result, DynamoDbError> { + store + .lookup("AKIABOB", date) + .await + .map(|resolved| resolved.map(|r| r.signing_key() == expected)) +} + +#[tokio::test(flavor = "current_thread")] +async fn one_thread_child_process() { + if !is_child(ONE_THREAD_CHILD) { + return; + } + assert_eq!(secmem::init_unlocked(1), secmem::Protection::Unlocked); + let inner = CountingCredStore::new(); + inner.insert("AKIABOB", make_cred(SECRET, "bob")); + let config = SwrCacheConfig { + ttl: Duration::from_secs(60), + soft_ttl: Duration::from_secs(30), + negative_ttl: Duration::from_secs(5), + max_entries: 100, + name: "test-cred", + }; + // One worker thread: the store's one slot becomes the one buffer. + let store = CachedCredentialStore::with_arc(Arc::new(SlowCredStore(inner)), config, REGION, 1); + assert!( + secmem::KeySlot::new().is_err(), + "the store has no free slot" + ); + let date = today(); + let expected = derive_signing_key(SECRET, &date, REGION, "dynamodb"); + + assert_eq!( + key_matches(&store, &date, &expected).await.unwrap(), + Some(true) + ); + let (a, b) = tokio::join!( + key_matches(&store, &date, &expected), + key_matches(&store, &date, &expected) + ); + assert_eq!(a.unwrap(), Some(true)); + assert_eq!(b.unwrap(), Some(true)); +} diff --git a/crates/auth/src/lib.rs b/crates/auth/src/lib.rs index db09024fc..b5da1b271 100644 --- a/crates/auth/src/lib.rs +++ b/crates/auth/src/lib.rs @@ -4,21 +4,23 @@ //! Authentication and authorization for extenddb. //! //! Defines the `AuthProvider` trait for pluggable auth backends. Ships with -//! `BuiltinAuthProvider` (full `SigV4` verification with local credential store). +//! `BuiltinAuthProvider` (full `SigV4` verification over the signing-key +//! cache of a local credential store) and the locked key store (`secmem`). pub mod cache_registry; pub mod credential_cache; pub mod policy; +pub mod secmem; pub mod sigv4; pub use cache_registry::{AuthCacheRegistry, AuthzCacheInvalidator, TableKeyInfoCacheInvalidator}; -pub use credential_cache::CachedCredentialStore; +pub use credential_cache::{CachedCredential, CachedCredentialStore, ResolvedCredential}; use axum::http::HeaderMap; use extenddb_core::error::DynamoDbError; use zeroize::{Zeroize, ZeroizeOnDrop}; -/// Auth provider trait — pluggable authentication. +/// Auth provider trait: pluggable authentication. /// /// `BuiltinAuthProvider` performs `SigV4` verification. /// Fix #11: Accept `&HeaderMap` directly to avoid per-request `HashMap` allocation. @@ -102,33 +104,30 @@ pub trait CredentialStore: Send + Sync { ) -> Result, DynamoDbError>; } -/// `SigV4` auth provider with local credential store. +/// `SigV4` auth provider over the signing-key cache. /// /// Parses the `Authorization` header, validates the request timestamp, checks -/// the credential scope, looks up the access key, decrypts the secret and -/// verifies the `SigV4` signature, in that order (the service's order). -/// Handles both long-lived (AKIA*) and temporary (ASIA* + X-Amz-Security-Token) -/// credentials. The credential scope must name this server's region. -pub struct BuiltinAuthProvider { - credential_store: C, - region: String, +/// the credential scope, looks the access key up in the cache and verifies the +/// `SigV4` signature under the cached signing key, in that order (the +/// service's order). Handles both long-lived (AKIA*) and temporary (ASIA* + +/// X-Amz-Security-Token) credentials. The credential scope must name the +/// cache's region, which is this server's region. +pub struct BuiltinAuthProvider { + credentials: CachedCredentialStore, } -impl BuiltinAuthProvider { - /// Create a new `BuiltinAuthProvider` over `credential_store` for a server - /// deployed as `region`. A request whose credential scope names another - /// region is rejected, as the service rejects a scope for a region other - /// than the endpoint's. - pub fn new(credential_store: C, region: impl Into) -> Self { - Self { - credential_store, - region: region.into(), - } +impl BuiltinAuthProvider { + /// Create a new `BuiltinAuthProvider` over `credentials`. A request whose + /// credential scope names a region other than the cache's is rejected, as + /// the service rejects a scope for a region other than the endpoint's. + #[must_use] + pub fn new(credentials: CachedCredentialStore) -> Self { + Self { credentials } } } #[async_trait::async_trait] -impl AuthProvider for BuiltinAuthProvider { +impl AuthProvider for BuiltinAuthProvider { async fn authenticate( &self, headers: &HeaderMap, @@ -154,27 +153,28 @@ impl AuthProvider for BuiltinAuthProvider { // Neither check reads the stored credential, so running them first // leaves the S-5 timing argument below unchanged. // - // Validate timestamp (±15 minute window). The X-Amz-Date value it + // Validate timestamp (within 15 minutes). The X-Amz-Date value it // returns is what the scope date is compared against. let timestamp = sigv4::verify::validate_timestamp(headers)?; // The credential scope must name this server's region, the dynamodb // service and the date of X-Amz-Date; the service reports every // complaint in one message when more than one is wrong. - sigv4::verify::check_scope(&parsed, &self.region, ×tamp)?; + sigv4::verify::check_scope(&parsed, self.credentials.region(), ×tamp)?; - let credential = self - .credential_store - .lookup_credential(&parsed.access_key_id) + let resolved = self + .credentials + .lookup(&parsed.access_key_id, &parsed.date) .await? .ok_or_else(|| { DynamoDbError::UnrecognizedClientException( "The security token included in the request is invalid.".to_owned(), ) })?; + let credential = resolved.credential(); // S-5: Track inactive status but do NOT return early. Continue through - // signature verification to ensure constant-time failure paths — no + // signature verification to ensure constant-time failure paths: no // timing difference between inactive, invalid, and absent keys. let is_inactive = !credential.is_active; @@ -183,11 +183,11 @@ impl AuthProvider for BuiltinAuthProvider { // the service validates any presented token and a long-term key has // none, so the request fails as an invalid token. // CB-12: Session expiration is enforced at the credential store layer (fail-closed). - // Expired sessions are never returned — the storage layer returns + // Expired sessions are never returned: the storage layer returns // ExpiredTokenException on the cache-miss path, and CachedCredentialStore // re-validates `expires_at` on every cache hit before returning so cached // entries cannot survive past their issued lifetime. - // S-5: Compare the session token in constant time and defer the + // S-5: Compare the token's hash in constant time and defer the // rejection until after signature verification, so neither the token's // byte contents nor its presence changes the failure-path timing. // A header value that is not visible ASCII cannot be compared with @@ -198,17 +198,15 @@ impl AuthProvider for BuiltinAuthProvider { .get("x-amz-security-token") .and_then(|v| v.to_str().ok()); let session_token_ok = if credential.is_session { - let token = presented_token.unwrap_or(""); - let expected = credential.session_token.as_deref().unwrap_or(""); - sigv4::verify::constant_time_eq(token.as_bytes(), expected.as_bytes()) + credential.session_token_matches(presented_token.unwrap_or("")) } else { !token_header_present }; - // Verify SigV4 signature — always, even for inactive keys (S-5). + // Verify the SigV4 signature, always, even for inactive keys (S-5). sigv4::verify::verify_signature( &parsed, - &credential.secret_key, + resolved.signing_key(), "POST", // DynamoDB is always POST "/", // DynamoDB is always / "", // DynamoDB has no query string @@ -232,8 +230,7 @@ impl AuthProvider for BuiltinAuthProvider { )); } - // Build identity from credential (clone fields because ZeroizeOnDrop - // prevents moving out of the struct). + // Build identity from the cached fields. if credential.is_session { Ok(AuthIdentity::RoleSession { account_id: credential.account_id.clone(), @@ -249,5 +246,7 @@ impl AuthProvider for BuiltinAuthProvider { } } +#[cfg(test)] +mod test_support; #[cfg(test)] mod tests; diff --git a/crates/auth/src/secmem.rs b/crates/auth/src/secmem.rs new file mode 100644 index 000000000..ada5af4ef --- /dev/null +++ b/crates/auth/src/secmem.rs @@ -0,0 +1,537 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The locked key store: 32-byte key slots in memory that stays out of swap +//! and out of core dumps (RFC-0000, section 6.2). +//! +//! The store is set up once per process with [`init`] or [`init_unlocked`]. +//! It holds the signing keys of the credential cache, the data encryption +//! key, and the temporary buffers of the cache. A [`KeySlot`] is one slot; +//! it is wiped and returned to the store when it drops. Before any init a +//! slot is a heap `Zeroizing` buffer, so tests and tools need no setup. +//! +//! On Linux the store tries `memfd_secret` first. Its pages leave the kernel +//! direct map, never reach swap and stay out of core dumps. When the kernel +//! has no `memfd_secret` or refuses it, the store is an anonymous private +//! mapping under `mlock`, `MADV_DONTDUMP` and `MADV_WIPEONFORK`. macOS locks +//! with `mlock`, Windows with `VirtualLock`. Other targets cannot lock. + +use std::fmt; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; + +use zeroize::{Zeroize, Zeroizing}; + +/// The size of one slot: an AES-256 key or an HMAC-SHA256 signing key. +const SLOT_BYTES: usize = 32; + +static STORE: OnceLock> = OnceLock::new(); + +/// How the store's pages are protected. +/// +/// `Display` gives the word for the startup log line: `memfd_secret`, +/// `locked pages` or `none`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Protection { + /// Linux `memfd_secret` pages: outside the kernel direct map, never + /// swapped, absent from core dumps. + MemfdSecret, + /// An anonymous private mapping under `mlock`; on Linux also + /// `MADV_DONTDUMP` and `MADV_WIPEONFORK`. macOS: `mlock`. Windows: + /// `VirtualLock`. + LockedPages, + /// Ordinary heap memory: before `init`, after `init_unlocked`, and on + /// targets with no lock call. + Unlocked, +} + +impl fmt::Display for Protection { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::MemfdSecret => "memfd_secret", + Self::LockedPages => "locked pages", + Self::Unlocked => "none", + }) + } +} + +/// The store could not lock its memory. +/// +/// `Display` names the bytes needed, the call that failed with its errno +/// text, and the two fixes. It never names a key. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LockError { + /// The locked memory the store needs, `required_bytes(slots)`. + pub bytes: usize, + /// The call that failed: `memfd_secret`, `ftruncate`, `mmap`, `close`, + /// `mlock`, `madvise`, `VirtualAlloc`, `VirtualLock`, or `unsupported` + /// on a target with no lock call. + pub call: &'static str, + /// The errno of that call, 0 for `unsupported`. + pub errno: i32, +} + +impl fmt::Display for LockError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.call == "unsupported" { + return write!( + f, + "this platform has no memory lock call, so the key store cannot lock {} bytes", + self.bytes + ); + } + write!( + f, + "cannot lock {} bytes of memory for the key store ({}: {}); raise the memlock \ + limit to at least {} bytes (LimitMEMLOCK= in the systemd unit, --ulimit memlock= \ + in Docker) or lower [auth.cache] max_entries", + self.bytes, + self.call, + std::io::Error::from_raw_os_error(self.errno), + self.bytes, + ) + } +} + +impl std::error::Error for LockError {} + +/// The store has no free slot. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StoreFull; + +impl fmt::Display for StoreFull { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("the locked key store has no free slot") + } +} + +impl std::error::Error for StoreFull {} + +/// Set the process-wide store up with `slots` slots in locked memory. +/// +/// `serve` and each encryption-key command call this once at startup, after +/// they decided from `key_file` and `require_locked_memory` that locking is +/// required. On failure nothing is set up, so the caller may call +/// [`init_unlocked`] next. A second call after a store exists changes +/// nothing and returns the protection in force. +/// +/// # Errors +/// +/// [`LockError`] when the platform cannot lock `required_bytes(slots)`. +pub fn init(slots: usize) -> Result { + if let Some(store) = STORE.get() { + return Ok(store.protection); + } + let store = Store::locked(slots)?; + Ok(STORE.get_or_init(|| Arc::new(store)).protection) +} + +/// Set the store up with `slots` slots in unlocked heap memory: the +/// warn-and-start path. Returns [`Protection::Unlocked`], or the protection +/// in force when a store exists. +pub fn init_unlocked(slots: usize) -> Protection { + STORE + .get_or_init(|| Arc::new(Store::unlocked(slots))) + .protection +} + +/// The protection in force. [`Protection::Unlocked`] before any init. +#[must_use] +pub fn protection() -> Protection { + STORE.get().map_or(Protection::Unlocked, |s| s.protection) +} + +/// The locked memory `init(slots)` needs: `slots * 32` rounded up to whole +/// pages, the unit that the memlock limit counts in. +#[must_use] +pub fn required_bytes(slots: usize) -> usize { + let page = platform::page_size(); + (slots * SLOT_BYTES).div_ceil(page) * page +} + +/// One 32-byte key in a slot of the store. +/// +/// The slot is wiped and returned to the store when the value drops. Before +/// any init a slot is a heap `Zeroizing` buffer. Not `Clone`: each slot has +/// one owner. `Debug` prints no bytes. +pub struct KeySlot(Inner); + +enum Inner { + // Boxed, so a move of the slot copies a pointer and leaves no unwiped + // copy of the key behind. + Heap(Box>), + Store { store: Arc, index: usize }, +} + +impl KeySlot { + /// A zeroed slot. + /// + /// # Errors + /// + /// [`StoreFull`] when the store has no free slot. Never fails before + /// init. + pub fn new() -> Result { + match STORE.get() { + Some(store) => Self::in_store(store), + None => Ok(Self(Inner::Heap(Box::new(Zeroizing::new([0; SLOT_BYTES]))))), + } + } + + /// A zeroed slot of `store`. + fn in_store(store: &Arc) -> Result { + store.take().map(|index| { + Self(Inner::Store { + store: Arc::clone(store), + index, + }) + }) + } + + /// A slot holding a copy of `bytes`. + /// + /// # Errors + /// + /// [`StoreFull`] when the store has no free slot. + pub fn from_bytes(bytes: &[u8; SLOT_BYTES]) -> Result { + let mut slot = Self::new()?; + slot.expose_mut().copy_from_slice(bytes); + Ok(slot) + } + + /// The key bytes. + #[must_use] + pub fn expose(&self) -> &[u8; SLOT_BYTES] { + match &self.0 { + Inner::Heap(bytes) => bytes, + // SAFETY: `index` was taken from the store's free list and is + // released only in `drop`, so this slot's 32 bytes are reachable + // through this value alone, and the `Arc` keeps the region + // mapped for as long as the value lives. + Inner::Store { store, index } => unsafe { &*store.slot_ptr(*index) }, + } + } + + /// The key bytes, for writing a derived key straight into the slot. + pub fn expose_mut(&mut self) -> &mut [u8; SLOT_BYTES] { + match &mut self.0 { + Inner::Heap(bytes) => bytes, + // SAFETY: as in `expose`; `&mut self` makes the access exclusive. + Inner::Store { store, index } => unsafe { &mut *store.slot_ptr(*index) }, + } + } +} + +impl Drop for KeySlot { + fn drop(&mut self) { + if let Inner::Store { store, index } = &self.0 { + // SAFETY: as in `expose_mut`; the index is still ours until the + // `release` call below. + unsafe { &mut *store.slot_ptr(*index) }.zeroize(); + store.release(*index); + } + } +} + +impl fmt::Debug for KeySlot { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let protection = match &self.0 { + Inner::Heap(_) => Protection::Unlocked, + Inner::Store { store, .. } => store.protection, + }; + write!(f, "KeySlot({SLOT_BYTES} bytes, {protection})") + } +} + +/// A region of `len` bytes holding `slots` slots, and the free slot indices. +struct Store { + region: platform::Region, + slots: usize, + protection: Protection, + free: Mutex>, +} + +// SAFETY: the region pointer is shared only through `slot_ptr`, whose +// callers hold distinct indices, and the free list is behind a mutex. +unsafe impl Send for Store {} +unsafe impl Sync for Store {} + +impl Store { + fn locked(slots: usize) -> Result { + let bytes = required_bytes(slots); + let (region, protection) = platform::lock(bytes.max(platform::page_size()))?; + Ok(Self::new(region, slots, protection)) + } + + fn unlocked(slots: usize) -> Self { + let bytes = (slots * SLOT_BYTES).max(SLOT_BYTES); + Self::new(platform::Region::heap(bytes), slots, Protection::Unlocked) + } + + fn new(region: platform::Region, slots: usize, protection: Protection) -> Self { + Self { + region, + slots, + protection, + free: Mutex::new((0..slots).rev().collect()), + } + } + + fn take(&self) -> Result { + self.free + .lock() + .unwrap_or_else(PoisonError::into_inner) + .pop() + .ok_or(StoreFull) + } + + fn release(&self, index: usize) { + self.free + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(index); + } + + fn slot_ptr(&self, index: usize) -> *mut [u8; SLOT_BYTES] { + debug_assert!(index < self.slots); + // SAFETY: `index < slots` and `slots * 32 <= len`, so the offset is + // inside the region. + unsafe { self.region.ptr().add(index * SLOT_BYTES) }.cast() + } +} + +impl Drop for Store { + fn drop(&mut self) { + // SAFETY: every `KeySlot` holds an `Arc`, so none is alive + // here and the whole region is ours to wipe before it is released. + unsafe { std::slice::from_raw_parts_mut(self.region.ptr(), self.region.len()) }.zeroize(); + } +} + +mod platform; + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::{is_child, run_test_in_child}; + + /// Before any init a slot is a heap buffer: it holds its bytes, prints + /// none of them, and the protection reads `none`. + #[test] + fn a_slot_before_init_is_a_heap_buffer() { + assert_eq!(protection(), Protection::Unlocked); + let mut slot = KeySlot::from_bytes(&[7; SLOT_BYTES]).unwrap(); + assert_eq!(slot.expose(), &[7; SLOT_BYTES]); + slot.expose_mut()[0] = 9; + assert_eq!(slot.expose()[0], 9); + assert_eq!(format!("{slot:?}"), "KeySlot(32 bytes, none)"); + } + + /// Slot allocation, exhaustion, free and wipe on a store of three slots, + /// in each protection the host gives. + #[test] + fn slots_are_distinct_refused_when_full_and_wiped_when_freed() { + let stores = [ + ("unlocked", Arc::new(Store::unlocked(3))), + ("locked", Arc::new(Store::locked(3).unwrap())), + ]; + for (name, store) in stores { + let mut slots: Vec = (0..3) + .map(|i| { + let mut slot = KeySlot::in_store(&store).unwrap(); + slot.expose_mut().fill(i + 1); + slot + }) + .collect(); + assert!( + matches!(KeySlot::in_store(&store), Err(StoreFull)), + "{name}" + ); + let indices: Vec = slots + .iter() + .map(|s| match &s.0 { + Inner::Store { index, .. } => *index, + Inner::Heap(_) => unreachable!("a store slot"), + }) + .collect(); + let mut sorted = indices.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, vec![0, 1, 2], "{name}"); + for (slot, fill) in slots.iter().zip(1u8..) { + assert_eq!(slot.expose(), &[fill; SLOT_BYTES], "{name}"); + } + + // Freeing one slot wipes it and makes it the next one handed out. + let freed = indices[1]; + drop(slots.remove(1)); + // SAFETY: the slot was freed, so no `KeySlot` reaches it, and the + // store is alive. + let bytes = unsafe { &*store.slot_ptr(freed) }; + assert_eq!(bytes, &[0; SLOT_BYTES], "{name}: wiped on drop"); + let again = KeySlot::in_store(&store).unwrap(); + assert!( + matches!(&again.0, Inner::Store { index, .. } if *index == freed), + "{name}" + ); + assert_eq!( + again.expose(), + &[0; SLOT_BYTES], + "{name}: handed out zeroed" + ); + assert_eq!( + format!("{again:?}"), + format!("KeySlot(32 bytes, {})", store.protection), + "{name}" + ); + } + } + + /// The store the host gives: `memfd_secret` on a kernel that has it, + /// locked pages otherwise, and locked pages when `memfd_secret` is + /// switched off. + #[cfg(target_os = "linux")] + #[test] + fn linux_locks_with_memfd_secret_or_falls_back() { + let (region, protection) = platform::lock(platform::page_size()).unwrap(); + assert!( + matches!( + protection, + Protection::MemfdSecret | Protection::LockedPages + ), + "{protection}" + ); + assert_eq!(region.len(), platform::page_size()); + let (_, fallback) = platform::lock_with(platform::page_size(), false).unwrap(); + assert_eq!(fallback, Protection::LockedPages); + } + + /// The `memfd_secret` descriptor is close-on-exec, so a process that + /// another thread spawns before the store closes it does not inherit it. + /// The flag check runs everywhere; the descriptor check needs a kernel + /// that has `memfd_secret`. + #[cfg(target_os = "linux")] + #[test] + fn the_memfd_secret_descriptor_is_close_on_exec() { + assert_eq!(platform::SECRET_FD_FLAGS, libc::O_CLOEXEC); + match platform::secret_fd(platform::page_size()) { + Ok(fd) => { + // SAFETY: `F_GETFD` reads the flags of a descriptor this test holds. + let flags = unsafe { libc::fcntl(fd.0, libc::F_GETFD) }; + assert_eq!(flags & libc::FD_CLOEXEC, libc::FD_CLOEXEC, "{flags}"); + } + Err(e) => eprintln!("skipped the descriptor check: {e}"), + } + } + + /// `required_bytes` rounds the slots up to whole pages. + #[test] + fn required_bytes_rounds_up_to_pages() { + let page = platform::page_size(); + let per_page = page / SLOT_BYTES; + let cases = [ + (0, 0), + (1, page), + (per_page, page), + (per_page + 1, 2 * page), + (20_001, (20_001 * SLOT_BYTES).div_ceil(page) * page), + ]; + for (slots, bytes) in cases { + assert_eq!(required_bytes(slots), bytes, "{slots} slots"); + } + } + + /// The refusal names the bytes, the call and both fixes, and no key. + #[test] + fn lock_error_names_the_limit_and_the_fixes() { + let error = LockError { + bytes: 655_360, + call: "mlock", + errno: 12, + }; + let text = error.to_string(); + for part in [ + "655360 bytes", + "mlock", + "LimitMEMLOCK=", + "--ulimit memlock=", + "[auth.cache] max_entries", + ] { + assert!(text.contains(part), "{part:?} not in {text:?}"); + } + let unsupported = LockError { + bytes: 4096, + call: "unsupported", + errno: 0, + } + .to_string(); + assert!(unsupported.contains("no memory lock call"), "{unsupported}"); + assert!(unsupported.contains("4096"), "{unsupported}"); + assert_eq!(Protection::MemfdSecret.to_string(), "memfd_secret"); + assert_eq!(Protection::LockedPages.to_string(), "locked pages"); + assert_eq!(Protection::Unlocked.to_string(), "none"); + } + + const MEMLOCK_CHILD: &str = "EXTENDDB_TEST_MEMLOCK_CHILD"; + + /// Under a memlock limit below the store, `init` refuses with the bytes + /// it needs and sets nothing up; `init_unlocked` then starts the store + /// unlocked, and the first call decides for the process. Runs in a child + /// process, which owns the limit and the process-wide store. + #[cfg(unix)] + #[test] + fn init_refuses_under_a_low_memlock_limit_then_starts_unlocked() { + let output = run_test_in_child("secmem::tests::memlock_limit_child_process", MEMLOCK_CHILD); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + } + + #[cfg(unix)] + #[test] + fn memlock_limit_child_process() { + if !is_child(MEMLOCK_CHILD) { + return; + } + // SAFETY: `geteuid` takes no arguments and cannot fail. + if unsafe { libc::geteuid() } == 0 { + // Root holds CAP_IPC_LOCK, which the limit does not bind. + eprintln!("running as root: the memlock limit does not apply, skipping"); + return; + } + let limit = libc::rlimit { + rlim_cur: 64 * 1024, + rlim_max: 64 * 1024, + }; + // SAFETY: a valid `rlimit`; lowering a limit needs no privilege. + assert_eq!( + unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &raw const limit) }, + 0 + ); + + // 1 MiB of slots is above the limit. + let slots = (1024 * 1024) / SLOT_BYTES; + let error = init(slots).unwrap_err(); + assert_eq!(error.bytes, required_bytes(slots)); + assert!( + matches!(error.call, "mlock" | "mmap"), + "{}: {error}", + error.call + ); + assert_eq!(protection(), Protection::Unlocked, "nothing was set up"); + + // 32 KiB of slots is within the limit. + let small = Store::locked((32 * 1024) / SLOT_BYTES).unwrap(); + assert_ne!(small.protection, Protection::Unlocked); + drop(small); + + assert_eq!(init_unlocked(4), Protection::Unlocked); + assert_eq!(protection(), Protection::Unlocked); + assert_eq!(init(4), Ok(Protection::Unlocked), "the first call decides"); + let slot = KeySlot::from_bytes(&[3; SLOT_BYTES]).unwrap(); + assert_eq!(slot.expose(), &[3; SLOT_BYTES]); + assert_eq!(format!("{slot:?}"), "KeySlot(32 bytes, none)"); + let held: Vec = (0..3).map(|_| KeySlot::new().unwrap()).collect(); + assert_eq!(KeySlot::new().map(|_| ()), Err(StoreFull)); + drop(held); + } +} diff --git a/crates/auth/src/secmem/platform.rs b/crates/auth/src/secmem/platform.rs new file mode 100644 index 000000000..874965d1c --- /dev/null +++ b/crates/auth/src/secmem/platform.rs @@ -0,0 +1,315 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The platform calls. `lock` returns a region of `len` bytes that the +//! platform locked, and the protection it gave. Every return value is +//! checked. + +use std::ptr::NonNull; + +use super::{LockError, Protection}; + +/// A region of memory and how to release it. +pub(super) struct Region { + ptr: NonNull, + len: usize, + kind: Kind, +} + +enum Kind { + Heap(std::alloc::Layout), + #[cfg(unix)] + Mapped, + #[cfg(windows)] + Virtual, +} + +impl Region { + /// `len` zeroed bytes from the heap. + pub(super) fn heap(len: usize) -> Self { + let layout = std::alloc::Layout::from_size_align(len, super::SLOT_BYTES) + .expect("a slot count that fits in memory"); + // SAFETY: `len >= 32`, so the layout has a non-zero size. + let ptr = unsafe { std::alloc::alloc_zeroed(layout) }; + let ptr = NonNull::new(ptr).unwrap_or_else(|| std::alloc::handle_alloc_error(layout)); + Self { + ptr, + len, + kind: Kind::Heap(layout), + } + } + + pub(super) fn ptr(&self) -> *mut u8 { + self.ptr.as_ptr() + } + + pub(super) fn len(&self) -> usize { + self.len + } +} + +impl Drop for Region { + fn drop(&mut self) { + match self.kind { + // SAFETY: `ptr` came from `alloc_zeroed` with this layout. + Kind::Heap(layout) => unsafe { std::alloc::dealloc(self.ptr.as_ptr(), layout) }, + // SAFETY: `ptr` and `len` are the mapping `mmap` returned. + #[cfg(unix)] + Kind::Mapped => unsafe { + libc::munmap(self.ptr.as_ptr().cast(), self.len); + }, + // SAFETY: `ptr` is the base `VirtualAlloc` returned. + #[cfg(windows)] + Kind::Virtual => unsafe { + win::VirtualFree(self.ptr.as_ptr().cast(), 0, win::MEM_RELEASE); + }, + } + } +} + +fn last_errno() -> i32 { + std::io::Error::last_os_error().raw_os_error().unwrap_or(0) +} + +#[cfg(unix)] +pub(super) fn page_size() -> usize { + // SAFETY: `sysconf` reads a constant; a failure returns -1. + let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + usize::try_from(page).unwrap_or(4096) +} + +#[cfg(not(unix))] +pub(super) fn page_size() -> usize { + 4096 +} + +/// Linux: `memfd_secret`, then an anonymous mapping under `mlock` with +/// `MADV_DONTDUMP` and `MADV_WIPEONFORK`. +#[cfg(target_os = "linux")] +pub(super) fn lock(len: usize) -> Result<(Region, Protection), LockError> { + lock_with(len, true) +} + +/// `lock`, with the `memfd_secret` attempt switched off by tests that +/// exercise the fallback on a kernel that has it. +#[cfg(target_os = "linux")] +pub(super) fn lock_with( + len: usize, + try_memfd_secret: bool, +) -> Result<(Region, Protection), LockError> { + if try_memfd_secret { + match memfd_secret(len) { + Ok(region) => return Ok((region, Protection::MemfdSecret)), + Err(e) if matches!(e.errno, libc::ENOSYS | libc::EPERM | libc::EAGAIN) => {} + Err(e) => return Err(e), + } + } + mlocked(len).map(|region| (region, Protection::LockedPages)) +} + +/// macOS and the other Unix targets: an anonymous mapping under `mlock`. +#[cfg(all(unix, not(target_os = "linux")))] +pub(super) fn lock(len: usize) -> Result<(Region, Protection), LockError> { + mlocked(len).map(|region| (region, Protection::LockedPages)) +} + +/// Windows: `VirtualAlloc` and `VirtualLock`. +#[cfg(windows)] +pub(super) fn lock(len: usize) -> Result<(Region, Protection), LockError> { + let fail = |call: &'static str| LockError { + bytes: len, + call, + errno: last_errno(), + }; + // SAFETY: a fresh allocation; the arguments are the documented + // constants and `len` is a whole number of pages. + let ptr = unsafe { + win::VirtualAlloc( + std::ptr::null_mut(), + len, + win::MEM_COMMIT | win::MEM_RESERVE, + win::PAGE_READWRITE, + ) + }; + let Some(ptr) = NonNull::new(ptr.cast::()) else { + return Err(fail("VirtualAlloc")); + }; + let region = Region { + ptr, + len, + kind: Kind::Virtual, + }; + // SAFETY: `ptr` and `len` are the allocation above. + if unsafe { win::VirtualLock(ptr.as_ptr().cast(), len) } == 0 { + return Err(fail("VirtualLock")); + } + Ok((region, Protection::LockedPages)) +} + +#[cfg(not(any(unix, windows)))] +pub(super) fn lock(len: usize) -> Result<(Region, Protection), LockError> { + Err(LockError { + bytes: len, + call: "unsupported", + errno: 0, + }) +} + +/// The flags of `memfd_secret`: `O_CLOEXEC`, its one flag, so that a process +/// that another thread spawns before the store closes the descriptor does +/// not inherit it across `exec`. +#[cfg(target_os = "linux")] +pub(super) const SECRET_FD_FLAGS: libc::c_int = libc::O_CLOEXEC; + +#[cfg(target_os = "linux")] +fn memfd_secret(len: usize) -> Result { + let fail = |call: &'static str| LockError { + bytes: len, + call, + errno: last_errno(), + }; + let fd = secret_fd(len)?; + let Ok(size) = libc::off_t::try_from(len) else { + return Err(LockError { + bytes: len, + call: "ftruncate", + errno: libc::EINVAL, + }); + }; + // SAFETY: `fd` is the descriptor opened above. + if unsafe { libc::ftruncate(fd.0, size) } != 0 { + return Err(fail("ftruncate")); + } + // SAFETY: a fresh shared mapping of the whole descriptor. + let ptr = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + fd.0, + 0, + ) + }; + if ptr == libc::MAP_FAILED { + return Err(fail("mmap")); + } + let region = Region { + ptr: NonNull::new(ptr.cast::()).expect("mmap returns a null page only as MAP_FAILED"), + len, + kind: Kind::Mapped, + }; + fd.close().map_err(|_| fail("close"))?; + // SAFETY: the mapping is `len` writable bytes. Writing it faults + // every page in now, so a later key write cannot hit a page the + // kernel refuses to allocate. + unsafe { std::ptr::write_bytes(region.ptr(), 0, len) }; + Ok(region) +} + +/// A `memfd_secret` descriptor for a store of `len` bytes, opened with +/// [`SECRET_FD_FLAGS`]. +#[cfg(target_os = "linux")] +pub(super) fn secret_fd(len: usize) -> Result { + // SAFETY: `memfd_secret` takes its flags and no pointer; it returns a + // file descriptor or -1 with errno set. + let fd = unsafe { libc::syscall(libc::SYS_memfd_secret, SECRET_FD_FLAGS) }; + match libc::c_int::try_from(fd) { + Ok(fd) if fd >= 0 => Ok(SecretFd(fd)), + _ => Err(LockError { + bytes: len, + call: "memfd_secret", + errno: last_errno(), + }), + } +} + +/// A descriptor closed once, with the return value read. +#[cfg(target_os = "linux")] +pub(super) struct SecretFd(pub(super) libc::c_int); + +#[cfg(target_os = "linux")] +impl SecretFd { + fn close(self) -> Result<(), ()> { + let fd = self.0; + std::mem::forget(self); + // SAFETY: `fd` is open and closed only here. + if unsafe { libc::close(fd) } == 0 { + Ok(()) + } else { + Err(()) + } + } +} + +#[cfg(target_os = "linux")] +impl Drop for SecretFd { + fn drop(&mut self) { + // SAFETY: `fd` is open; this is the error path, so the result is + // not needed. + unsafe { libc::close(self.0) }; + } +} + +#[cfg(unix)] +fn mlocked(len: usize) -> Result { + let fail = |call: &'static str| LockError { + bytes: len, + call, + errno: last_errno(), + }; + // SAFETY: a fresh anonymous private mapping. + let ptr = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + if ptr == libc::MAP_FAILED { + return Err(fail("mmap")); + } + let region = Region { + ptr: NonNull::new(ptr.cast::()).expect("mmap returns a null page only as MAP_FAILED"), + len, + kind: Kind::Mapped, + }; + // SAFETY: `ptr` and `len` are the mapping above. + if unsafe { libc::mlock(ptr, len) } != 0 { + return Err(fail("mlock")); + } + #[cfg(target_os = "linux")] + for advice in [libc::MADV_DONTDUMP, libc::MADV_WIPEONFORK] { + // SAFETY: `ptr` and `len` are the mapping above. + if unsafe { libc::madvise(ptr, len, advice) } != 0 { + return Err(fail("madvise")); + } + } + Ok(region) +} + +/// The four kernel32 calls, declared here so that no crate is added. +#[cfg(windows)] +mod win { + use std::ffi::c_void; + + pub const MEM_COMMIT: u32 = 0x1000; + pub const MEM_RESERVE: u32 = 0x2000; + pub const MEM_RELEASE: u32 = 0x8000; + pub const PAGE_READWRITE: u32 = 0x04; + + #[link(name = "kernel32")] + unsafe extern "system" { + pub fn VirtualAlloc( + address: *mut c_void, + size: usize, + allocation_type: u32, + protect: u32, + ) -> *mut c_void; + pub fn VirtualFree(address: *mut c_void, size: usize, free_type: u32) -> i32; + pub fn VirtualLock(address: *mut c_void, size: usize) -> i32; + } +} diff --git a/crates/auth/src/sigv4/signing_key.rs b/crates/auth/src/sigv4/signing_key.rs index 2449e3b41..3f263f403 100755 --- a/crates/auth/src/sigv4/signing_key.rs +++ b/crates/auth/src/sigv4/signing_key.rs @@ -12,34 +12,69 @@ //! ``` use aws_lc_rs::hmac; +use zeroize::Zeroizing; -/// Derive the `SigV4` signing key from a secret access key. +/// Derive the `SigV4` signing key of `secret` into `out`. +/// +/// The prefixed secret and the three intermediate keys live in `Zeroizing` +/// buffers and are wiped before this returns, so the only copy of key +/// material left behind is in `out`. The caller passes a slot of the locked +/// key store, or a `Zeroizing` buffer. (The tag that `hmac::sign` returns is +/// a stack value this function cannot wipe.) /// /// # Arguments -/// * `secret` — The plaintext secret access key. -/// * `date` — Date string in `YYYYMMDD` format. -/// * `region` — AWS region (e.g. `us-east-1`). -/// * `service` — Service name (e.g. `dynamodb`). +/// * `secret` - The plaintext secret access key. +/// * `date` - Date string in `YYYYMMDD` format. +/// * `region` - AWS region (e.g. `us-east-1`). +/// * `service` - Service name (e.g. `dynamodb`). +pub fn derive_signing_key_into( + secret: &[u8], + date: &str, + region: &str, + service: &str, + out: &mut [u8; 32], +) { + let mut prefixed = Zeroizing::new(Vec::with_capacity(4 + secret.len())); + prefixed.extend_from_slice(b"AWS4"); + prefixed.extend_from_slice(secret); + let mut k_date = Zeroizing::new([0u8; 32]); + hmac_sha256(&prefixed, date.as_bytes(), &mut k_date); + let mut k_region = Zeroizing::new([0u8; 32]); + hmac_sha256(&k_date[..], region.as_bytes(), &mut k_region); + let mut k_service = Zeroizing::new([0u8; 32]); + hmac_sha256(&k_region[..], service.as_bytes(), &mut k_service); + hmac_sha256(&k_service[..], b"aws4_request", out); +} + +/// Derive the `SigV4` signing key from a secret access key, as +/// [`derive_signing_key_into`], into a `Zeroizing` buffer. #[must_use] -pub fn derive_signing_key(secret: &str, date: &str, region: &str, service: &str) -> Vec { - let k_date = hmac_sha256(format!("AWS4{secret}").as_bytes(), date.as_bytes()); - let k_region = hmac_sha256(&k_date, region.as_bytes()); - let k_service = hmac_sha256(&k_region, service.as_bytes()); - hmac_sha256(&k_service, b"aws4_request") +pub fn derive_signing_key( + secret: &str, + date: &str, + region: &str, + service: &str, +) -> Zeroizing<[u8; 32]> { + let mut out = Zeroizing::new([0u8; 32]); + derive_signing_key_into(secret.as_bytes(), date, region, service, &mut out); + out } /// Compute the final signature: HMAC-SHA256(signing_key, `string_to_sign`), hex-encoded. #[must_use] -pub fn compute_signature(signing_key: &[u8], string_to_sign: &str) -> String { - hex::encode(hmac_sha256(signing_key, string_to_sign.as_bytes())) +pub fn compute_signature(signing_key: &[u8; 32], string_to_sign: &str) -> String { + // The signature is sent on the wire, so it needs no wipe. + let mut mac = [0u8; 32]; + hmac_sha256(signing_key, string_to_sign.as_bytes(), &mut mac); + hex::encode(mac) } -fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec { +fn hmac_sha256(key: &[u8], data: &[u8], out: &mut [u8; 32]) { // HMAC-SHA256 accepts a key of any length (RFC 2104). `Key::new` panics // only if AWS-LC cannot set up the HMAC context, which does not depend on - // the key. + // the key. AWS-LC cleanses its copy of the key when `key` drops. let key = hmac::Key::new(hmac::HMAC_SHA256, key); - hmac::sign(&key, data).as_ref().to_vec() + out.copy_from_slice(hmac::sign(&key, data).as_ref()); } #[cfg(test)] @@ -90,4 +125,40 @@ mod tests { "5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7" ); } + + /// A key derived into a caller's buffer equals the one `derive_signing_key` + /// returns, for the AWS test vector and the documentation example pair. + #[test] + fn derive_into_matches_derive() { + let cases = [ + ( + "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", + "20150830", + "us-east-1", + "iam", + ), + ( + "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", + "20260415", + "us-east-1", + "dynamodb", + ), + ( + "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", + "20260416", + "eu-west-1", + "dynamodb", + ), + ]; + for (secret, date, region, service) in cases { + let mut out = [0u8; 32]; + derive_signing_key_into(secret.as_bytes(), date, region, service, &mut out); + // The message names the scope alone, so a failure prints no secret + // and no key. + assert!( + out == *derive_signing_key(secret, date, region, service), + "{date} {region} {service}" + ); + } + } } diff --git a/crates/auth/src/sigv4/verify.rs b/crates/auth/src/sigv4/verify.rs index 803cb7d0a..7b2b6a891 100755 --- a/crates/auth/src/sigv4/verify.rs +++ b/crates/auth/src/sigv4/verify.rs @@ -19,7 +19,7 @@ const MAX_CLOCK_SKEW_SECS: i64 = 15 * 60; /// The scope complaint for a date that is not the `YYYYMMDD` prefix of /// `X-Amz-Date`, with the trailing period and space the service sends. -const SCOPE_DATE_COMPLAINT: &str = +pub(crate) const SCOPE_DATE_COMPLAINT: &str = "Date in Credential scope does not match YYYYMMDD from ISO-8601 version of date from HTTP. "; /// Whether the scope `date` is the `YYYYMMDD` prefix of `timestamp`. @@ -79,18 +79,19 @@ pub fn check_scope( /// Verify a `SigV4` signature against the request. /// /// # Arguments -/// * `parsed` — The parsed `Authorization` header. -/// * `secret_key` — The plaintext secret access key. -/// * `method` — HTTP method (e.g. `POST`). -/// * `uri_path` — URI path (e.g. `/`). -/// * `query_string` — Query string (empty for `DynamoDB`). -/// * `headers` — The full request headers. -/// * `body` — The request body bytes. +/// * `parsed` - The parsed `Authorization` header. +/// * `signing_key` - The `SigV4` signing key of the access key for the +/// request's scope date, region and service, from the credential cache. +/// * `method` - HTTP method (e.g. `POST`). +/// * `uri_path` - URI path (e.g. `/`). +/// * `query_string` - Query string (empty for `DynamoDB`). +/// * `headers` - The full request headers. +/// * `body` - The request body bytes. /// /// Returns `Ok(())` on success, or an appropriate auth error on failure. pub fn verify_signature( parsed: &ParsedAuthorization, - secret_key: &str, + signing_key: &[u8; 32], method: &str, uri_path: &str, query_string: &str, @@ -141,10 +142,8 @@ pub fn verify_signature( let sts = canonical::string_to_sign(×tamp, &scope, &creq); - // Derive signing key and compute expected signature - let signing_key = - signing_key::derive_signing_key(secret_key, &parsed.date, &parsed.region, &parsed.service); - let expected = signing_key::compute_signature(&signing_key, &sts); + // Compute the expected signature under the cached signing key. + let expected = signing_key::compute_signature(signing_key, &sts); // auth H-1: Use InvalidSignatureException for signature mismatches, // distinct from UnrecognizedClientException (unknown key). @@ -308,7 +307,7 @@ mod tests { fn reject_wrong_service_in_scope() { let parsed = make_parsed("s3", "20260415", "content-type;host;x-amz-date"); let headers = make_headers("20260415T120000Z"); - let err = verify_signature(&parsed, "secret", "POST", "/", "", &headers, b"{}"); + let err = verify_signature(&parsed, &key(SECRET), "POST", "/", "", &headers, b"{}"); match err { Err(DynamoDbError::InvalidSignatureException(msg)) => { assert!(msg.contains("dynamodb"), "Expected 'dynamodb' in: {msg}"); @@ -322,7 +321,7 @@ mod tests { fn reject_scope_date_mismatch() { let parsed = make_parsed("dynamodb", "20260414", "content-type;host;x-amz-date"); let headers = make_headers("20260415T120000Z"); - let err = verify_signature(&parsed, "secret", "POST", "/", "", &headers, b"{}"); + let err = verify_signature(&parsed, &key(SECRET), "POST", "/", "", &headers, b"{}"); match err { Err(DynamoDbError::InvalidSignatureException(msg)) => { assert_eq!(msg, SCOPE_DATE_COMPLAINT); @@ -385,7 +384,7 @@ mod tests { fn reject_missing_host_in_signed_headers() { let parsed = make_parsed("dynamodb", "20260415", "content-type;x-amz-date"); let headers = make_headers("20260415T120000Z"); - let err = verify_signature(&parsed, "secret", "POST", "/", "", &headers, b"{}"); + let err = verify_signature(&parsed, &key(SECRET), "POST", "/", "", &headers, b"{}"); match err { Err(DynamoDbError::InvalidSignatureException(msg)) => { assert!(msg.contains("Host"), "Expected 'Host' in message: {msg}"); @@ -413,10 +412,17 @@ mod tests { "20260415/us-east-1/dynamodb/aws4_request", &creq, ); - let key = signing_key::derive_signing_key(SECRET, "20260415", "us-east-1", "dynamodb"); let mut parsed = make_parsed("dynamodb", "20260415", signed); - parsed.signature = signing_key::compute_signature(&key, &sts); - match verify_signature(&parsed, SECRET, "POST", "/", "", &headers, SIGNED_BODY) { + parsed.signature = signing_key::compute_signature(&key(SECRET), &sts); + match verify_signature( + &parsed, + &key(SECRET), + "POST", + "/", + "", + &headers, + SIGNED_BODY, + ) { Err(DynamoDbError::InvalidSignatureException(msg)) => { assert!( msg.starts_with("The request signature we calculated does not match"), @@ -434,7 +440,15 @@ mod tests { let parsed = make_parsed("dynamodb", "20260415", "content-type;host;x-amz-date"); let headers = make_headers("20260415T120000Z"); // Wrong secret → wrong signature → InvalidSignatureException - let err = verify_signature(&parsed, "wrong-secret", "POST", "/", "", &headers, b"{}"); + let err = verify_signature( + &parsed, + &key("wrong-secret"), + "POST", + "/", + "", + &headers, + b"{}", + ); match err { Err(DynamoDbError::InvalidSignatureException(msg)) => { assert!( @@ -459,12 +473,16 @@ mod tests { "20260415/us-east-1/dynamodb/aws4_request", &creq, ); - let key = signing_key::derive_signing_key(SECRET, "20260415", "us-east-1", "dynamodb"); let mut parsed = make_parsed("dynamodb", "20260415", signed_headers); - parsed.signature = signing_key::compute_signature(&key, &sts); + parsed.signature = signing_key::compute_signature(&key(SECRET), &sts); parsed } + /// The signing key of `secret` for the scope every test here signs with. + fn key(secret: &str) -> zeroize::Zeroizing<[u8; 32]> { + signing_key::derive_signing_key(secret, "20260415", "us-east-1", "dynamodb") + } + fn assert_signature_mismatch(result: Result<(), DynamoDbError>) { match result { Err(DynamoDbError::InvalidSignatureException(msg)) => { @@ -481,7 +499,16 @@ mod tests { fn correctly_signed_body_verifies() { let headers = make_headers("20260415T120000Z"); let parsed = sign(&headers, "content-type;host;x-amz-date", SIGNED_BODY); - verify_signature(&parsed, SECRET, "POST", "/", "", &headers, SIGNED_BODY).unwrap(); + verify_signature( + &parsed, + &key(SECRET), + "POST", + "/", + "", + &headers, + SIGNED_BODY, + ) + .unwrap(); } #[test] @@ -490,7 +517,7 @@ mod tests { let parsed = sign(&headers, "content-type;host;x-amz-date", SIGNED_BODY); assert_signature_mismatch(verify_signature( &parsed, - SECRET, + &key(SECRET), "POST", "/", "", @@ -513,10 +540,19 @@ mod tests { let signed = "content-type;host;x-amz-content-sha256;x-amz-date"; let parsed = sign(&headers, signed, SIGNED_BODY); // Sanity: the same request with the signed body verifies. - verify_signature(&parsed, SECRET, "POST", "/", "", &headers, SIGNED_BODY).unwrap(); + verify_signature( + &parsed, + &key(SECRET), + "POST", + "/", + "", + &headers, + SIGNED_BODY, + ) + .unwrap(); assert_signature_mismatch(verify_signature( &parsed, - SECRET, + &key(SECRET), "POST", "/", "", @@ -533,6 +569,15 @@ mod tests { let mut headers = make_headers("20260415T120000Z"); headers.insert("x-amz-content-sha256", "0".repeat(64).parse().unwrap()); let parsed = sign(&headers, "content-type;host;x-amz-date", SIGNED_BODY); - verify_signature(&parsed, SECRET, "POST", "/", "", &headers, SIGNED_BODY).unwrap(); + verify_signature( + &parsed, + &key(SECRET), + "POST", + "/", + "", + &headers, + SIGNED_BODY, + ) + .unwrap(); } } diff --git a/crates/auth/src/test_support.rs b/crates/auth/src/test_support.rs new file mode 100644 index 000000000..faa1e00e8 --- /dev/null +++ b/crates/auth/src/test_support.rs @@ -0,0 +1,24 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Helpers for the tests of this crate. + +use std::process::Output; + +/// Run the test at `test_path` (its full module path) in a child process, +/// with `env` set to `1`, and return its output. The locked key store is set +/// up once per process, so a test that sets it up runs in a child of its own: +/// the child test function returns at once when `env` is unset, and does its +/// work when it is set. +pub(crate) fn run_test_in_child(test_path: &str, env: &str) -> Output { + std::process::Command::new(std::env::current_exe().expect("test binary")) + .args(["--exact", test_path, "--nocapture", "--test-threads=1"]) + .env(env, "1") + .output() + .expect("child") +} + +/// Whether this is the child process of [`run_test_in_child`] for `env`. +pub(crate) fn is_child(env: &str) -> bool { + std::env::var_os(env).is_some() +} diff --git a/crates/auth/src/tests.rs b/crates/auth/src/tests.rs index bec44b6f3..cf4ecc5e5 100644 --- a/crates/auth/src/tests.rs +++ b/crates/auth/src/tests.rs @@ -75,7 +75,7 @@ async fn expired_session_returns_expired_token_exception() { credential: None, error: Some("The security token included in the request is expired"), }; - let provider = BuiltinAuthProvider::new(store, "us-east-1"); + let provider = provider_over(store); let headers = make_headers_with_auth("ASIAEXTENDDB00000000", Some("test-token-value")); let result = provider.authenticate(&headers, b"{}").await; @@ -96,7 +96,7 @@ async fn nonexistent_key_returns_unrecognized_client() { credential: None, error: None, }; - let provider = BuiltinAuthProvider::new(store, "us-east-1"); + let provider = provider_over(store); let headers = make_headers_with_auth("AKIAXXXXXXXXXXXXXXXX", None); let result = provider.authenticate(&headers, b"{}").await; @@ -150,14 +150,22 @@ fn signed_headers(access_key: &str, region: &str, token: Option<&str>, body: &[u headers } -fn provider(is_session: bool) -> BuiltinAuthProvider { - BuiltinAuthProvider::new( - MockCredentialStore { - credential: Some(credential(is_session)), - error: None, - }, +fn provider(is_session: bool) -> BuiltinAuthProvider { + provider_over(MockCredentialStore { + credential: Some(credential(is_session)), + error: None, + }) +} + +/// A provider for a server in `us-east-1` whose credential cache passes every +/// lookup through to `store`. +fn provider_over(store: MockCredentialStore) -> BuiltinAuthProvider { + BuiltinAuthProvider::new(CachedCredentialStore::pass_through( + store, + extenddb_cache::SwrCacheConfig::default(), "us-east-1", - ) + 1, + )) } #[tokio::test] @@ -320,14 +328,11 @@ async fn scope_wrong_in_region_and_service_reports_both() { } /// A provider whose store holds no credential at all. -fn provider_without_credentials() -> BuiltinAuthProvider { - BuiltinAuthProvider::new( - MockCredentialStore { - credential: None, - error: None, - }, - "us-east-1", - ) +fn provider_without_credentials() -> BuiltinAuthProvider { + provider_over(MockCredentialStore { + credential: None, + error: None, + }) } /// Move the request date one hour into the past, re-signing the scope diff --git a/crates/auth/tests/sigv4_differential/harness.rs b/crates/auth/tests/sigv4_differential/harness.rs index 58ab885ce..6f0bce8bc 100644 --- a/crates/auth/tests/sigv4_differential/harness.rs +++ b/crates/auth/tests/sigv4_differential/harness.rs @@ -15,7 +15,8 @@ use aws_sigv4::sign::v4; use axum::http::{HeaderMap, HeaderName, HeaderValue}; use extenddb_auth::sigv4::{canonical, parse}; use extenddb_auth::{ - AuthIdentity, AuthProvider, BuiltinAuthProvider, CredentialStore, StoredCredential, + AuthIdentity, AuthProvider, BuiltinAuthProvider, CachedCredentialStore, CredentialStore, + StoredCredential, }; use extenddb_core::error::DynamoDbError; @@ -433,7 +434,12 @@ impl Authorization { /// The authentication call the HTTP layer makes for a DynamoDB request, on a /// server deployed as `SERVER_REGION`. pub fn authenticate(wire: &Wire) -> Result { - let provider = BuiltinAuthProvider::new(MemoryStore, SERVER_REGION); + let provider = BuiltinAuthProvider::new(CachedCredentialStore::pass_through( + MemoryStore, + extenddb_cache::SwrCacheConfig::default(), + SERVER_REGION, + 1, + )); futures::executor::block_on(provider.authenticate(&wire.header_map(), &wire.body)) } diff --git a/crates/auth/tests/sigv4_differential/reject.rs b/crates/auth/tests/sigv4_differential/reject.rs index d14b7c001..0289d1e23 100644 --- a/crates/auth/tests/sigv4_differential/reject.rs +++ b/crates/auth/tests/sigv4_differential/reject.rs @@ -4,7 +4,7 @@ //! A request changed after `aws-sigv4` signed it, in a part the signature //! covers, or signed for another region or another service, is refused. -use extenddb_auth::sigv4::{parse, verify}; +use extenddb_auth::sigv4::{parse, signing_key, verify}; use extenddb_core::error::DynamoDbError; use crate::corpus::{self, REGIONS}; @@ -159,10 +159,16 @@ fn method_path_and_query_string_are_covered_by_the_signature() { let header = signed.wire.value("authorization").unwrap(); let parsed = parse::parse_authorization(header).unwrap(); let headers = signed.wire.header_map(); + let signing_key = signing_key::derive_signing_key( + key.secret(), + &parsed.date, + &parsed.region, + &parsed.service, + ); let verify = |method: &str, path: &str, query: &str| { verify::verify_signature( &parsed, - key.secret(), + &signing_key, method, path, query, diff --git a/crates/backup-store/src/fs.rs b/crates/backup-store/src/fs.rs index 65db015c0..e147376e0 100644 --- a/crates/backup-store/src/fs.rs +++ b/crates/backup-store/src/fs.rs @@ -891,12 +891,27 @@ pub fn check_private_directory(dir: &Path, what: &str) -> Result<(), StoreError> } fn check_private_tree(root: &Path, meta: &std::fs::Metadata, what: &str) -> Result<(), StoreError> { + check_owner_only(root, meta)?; + check_private_ancestors(root, what) +} + +/// The ancestor half of the owner-only rule, for the canonical path `path`: +/// every ancestor is a directory, not a symlink, owned by the effective user +/// or by root, and not writable by group or others unless its sticky bit is +/// set. `what` names `path` in the messages. The backup root, the restore +/// spool and the KEK file (RFC-0000 section 2, check 2) use it. No check is +/// made on other platforms. +/// +/// # Errors +/// +/// `PermissionDenied` naming the ancestor and what it needs; `Io` when an +/// ancestor cannot be read. +pub fn check_private_ancestors(path: &Path, what: &str) -> Result<(), StoreError> { #[cfg(unix)] { use std::os::unix::fs::MetadataExt; - check_owner_only(root, meta)?; let euid = effective_uid(); - let mut ancestor = root.parent(); + let mut ancestor = path.parent(); while let Some(dir) = ancestor { let m = std::fs::symlink_metadata(dir) .map_err(|e| StoreError::io(format!("stat {}", dir.display()), e))?; @@ -914,7 +929,8 @@ fn check_private_tree(root: &Path, meta: &std::fs::Metadata, what: &str) -> Resu if m.uid() != euid && m.uid() != 0 { return Err(StoreError::PermissionDenied(format!( "{} (an ancestor of the {what}) is owned by uid {}; the {what} must sit \ - under directories owned by root or by the extenddb user", + under directories owned by root or by the user extenddb runs as (uid \ + {euid})", dir.display(), m.uid() ))); @@ -932,7 +948,7 @@ fn check_private_tree(root: &Path, meta: &std::fs::Metadata, what: &str) -> Resu } #[cfg(not(unix))] { - let _ = (root, meta, what); + let _ = (path, what); } Ok(()) } @@ -992,8 +1008,9 @@ fn check_root_is_directory(root: &Path, meta: &std::fs::Metadata) -> Result<(), Ok(()) } +/// The effective user ID of this process. #[cfg(unix)] -fn effective_uid() -> u32 { +pub fn effective_uid() -> u32 { // SAFETY: geteuid has no preconditions and cannot fail. unsafe { libc::geteuid() } } diff --git a/crates/backup-store/src/lib.rs b/crates/backup-store/src/lib.rs index 8b7e8308e..fc16ed4cf 100644 --- a/crates/backup-store/src/lib.rs +++ b/crates/backup-store/src/lib.rs @@ -33,7 +33,9 @@ mod s3; pub use config::{BackupStoreConfig, BackupStoreKind, FilesystemStoreConfig, S3StoreConfig}; pub use error::StoreError; -pub use fs::{FilesystemStore, check_private_directory}; +#[cfg(unix)] +pub use fs::effective_uid; +pub use fs::{FilesystemStore, check_private_ancestors, check_private_directory}; pub use s3::{ ATTEMPT_TIMEOUT as S3_ATTEMPT_TIMEOUT, MAX_PART_SIZE_BYTES, MAX_STORE_PREFIX_LEN, MIN_PART_SIZE_BYTES, S3Store, diff --git a/crates/config/src/display.rs b/crates/config/src/display.rs index f626b75a2..46330c6d7 100644 --- a/crates/config/src/display.rs +++ b/crates/config/src/display.rs @@ -168,6 +168,7 @@ mod tests { for key in [ "encryption_key", "Encryption_KEY", + "encryption_key_ring", "connection_string", "storage.Connection_String", "password", diff --git a/crates/config/src/encryption.rs b/crates/config/src/encryption.rs new file mode 100644 index 000000000..3e63b7c3d --- /dev/null +++ b/crates/config/src/encryption.rs @@ -0,0 +1,170 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `[auth.encryption]` section. + +use serde::{Deserialize, Deserializer}; + +use crate::expand_tilde; + +/// The `[auth.encryption]` section: the key-encryption key (KEK) file and the +/// locked memory rule. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EncryptionConfig { + /// Path of the KEK file. Not set: the server uses the catalog key in the + /// `encryption_key` settings row. Set: the server unwraps the data + /// encryption key in the `encryption_key_ring` row with the KEK in this + /// file. A leading `~` expands as in the TLS key path + /// ([`EncryptionConfig::key_file_path`]), and the path must then be + /// absolute: the parse refuses a relative one. + #[serde(default, deserialize_with = "absolute_key_file")] + pub key_file: Option, + /// With `key_file` set, refuse to start when the locked key store cannot + /// lock its memory. `false` turns the refusal into a warning. Without + /// `key_file` the server warns and starts either way. + #[serde(default = "default_require_locked_memory")] + pub require_locked_memory: bool, +} + +impl Default for EncryptionConfig { + fn default() -> Self { + Self { + key_file: None, + require_locked_memory: default_require_locked_memory(), + } + } +} + +impl EncryptionConfig { + /// The KEK file path with a leading `~` expanded ([`expand_tilde`]), or + /// `None` when `key_file` is not set. + #[must_use] + pub fn key_file_path(&self) -> Option { + self.key_file.as_deref().map(expand_tilde) + } +} + +/// `key_file` as written, refused when it is relative after the `~` +/// expansion of [`EncryptionConfig::key_file_path`]: `serve` detaches into +/// `/` before it reads the file, so a relative path names another file. +fn absolute_key_file<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let path = Option::::deserialize(d)?; + if let Some(path) = &path + && !std::path::Path::new(&expand_tilde(path)).is_absolute() + { + return Err(serde::de::Error::custom(format!( + "[auth.encryption] key_file = {path:?} is a relative path; the path must be absolute \ + (a leading `~/` expands to the home directory), because `extenddb serve` changes \ + its working directory to `/` when it detaches" + ))); + } + Ok(path) +} + +fn default_require_locked_memory() -> bool { + true +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{AuthConfig, environment}; + + /// `[auth.encryption]` as `load` reads it: the file's text, then the + /// `EXTENDDB__` variables in `vars`. `Ok` holds `key_file_path()` and + /// `require_locked_memory`; `Err` holds a part of the error. + #[test] + fn auth_encryption_parses_with_its_defaults_and_overrides() { + type Expected = Result<(Option, bool), &'static str>; + /// The file's text, the `EXTENDDB__` variables, and the outcome. + type Case = ( + &'static str, + &'static [(&'static str, &'static str)], + Expected, + ); + let home = std::env::var("HOME").unwrap(); + let kek = |path: &str| Some(path.to_owned()); + let cases: [Case; 11] = [ + ("", &[], Ok((None, true))), + ("[auth]\nprovider = \"builtin\"\n", &[], Ok((None, true))), + ( + "[auth.encryption]\nkey_file = \"/etc/extenddb/kek\"\n", + &[], + Ok((kek("/etc/extenddb/kek"), true)), + ), + ( + "[auth.encryption]\nkey_file = \"~/kek\"\n", + &[], + Ok((Some(format!("{home}/kek")), true)), + ), + ( + "[auth.encryption]\nrequire_locked_memory = false\n", + &[], + Ok((None, false)), + ), + ( + "[auth.encryption]\nkey_file = \"/etc/extenddb/kek\"\n", + &[( + "EXTENDDB__AUTH__ENCRYPTION__KEY_FILE", + "/run/credentials/extenddb.service/extenddb-kek", + )], + Ok((kek("/run/credentials/extenddb.service/extenddb-kek"), true)), + ), + ( + "", + &[("EXTENDDB__AUTH__ENCRYPTION__REQUIRE_LOCKED_MEMORY", "false")], + Ok((None, false)), + ), + ( + "[auth.encryption]\nkeyfile = \"/etc/extenddb/kek\"\n", + &[], + Err("unknown field `keyfile`"), + ), + ( + "[auth.encryption]\nkey_file = \"/a\"\npassphrase = \"x\"\n", + &[], + Err("unknown field `passphrase`"), + ), + ( + "[auth.encryption]\nkey_file = \"kek\"\n", + &[], + Err("[auth.encryption] key_file = \"kek\" is a relative path; the path must be"), + ), + ( + "", + &[("EXTENDDB__AUTH__ENCRYPTION__KEY_FILE", "etc/kek")], + Err("[auth.encryption] key_file = \"etc/kek\" is a relative path"), + ), + ]; + /// The one section this test reads. + #[derive(Deserialize)] + struct Auth { + #[serde(default)] + auth: AuthConfig, + } + for (text, vars, expected) in cases { + let vars = vars + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(); + let parsed = config::Config::builder() + .add_source(config::File::from_str(text, config::FileFormat::Toml)) + .add_source(environment(Some(vars))) + .build() + .and_then(|c| c.try_deserialize::()) + .map(|Auth { auth }| { + ( + auth.encryption.key_file_path(), + auth.encryption.require_locked_memory, + ) + }) + .map_err(|e| e.to_string()); + match (&parsed, &expected) { + (Ok(got), Ok(want)) => assert_eq!(got, want, "{text:?}"), + (Err(got), Err(part)) => assert!(got.contains(part), "{text:?}: {got}"), + _ => panic!("{text:?}: got {parsed:?}, want {expected:?}"), + } + } + } +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index a480096c6..57802782c 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -284,6 +284,11 @@ pub struct AuthConfig { /// apply when absent. #[serde(default)] pub cache: AuthCacheConfigToml, + /// Where the key that encrypts stored secrets comes from + /// (`[auth.encryption]`). Optional; without it the server uses the + /// catalog key. + #[serde(default)] + pub encryption: EncryptionConfig, } impl Default for AuthConfig { @@ -291,6 +296,7 @@ impl Default for AuthConfig { Self { provider: default_provider(), cache: AuthCacheConfigToml::default(), + encryption: EncryptionConfig::default(), } } } @@ -453,11 +459,21 @@ pub fn serves_tls(tls: &TlsConfig) -> bool { pub fn load(config_path: &str) -> anyhow::Result { let config = config::Config::builder() .add_source(config::File::with_name(config_path).required(false)) - .add_source(config::Environment::with_prefix("EXTENDDB").separator("__")) + .add_source(environment(None)) .build()?; validated(config.try_deserialize()?) } +/// The `EXTENDDB__*` variables as a configuration source, `__` between +/// section names (`EXTENDDB__AUTH__ENCRYPTION__KEY_FILE` sets +/// `auth.encryption.key_file`). `vars` replaces the process environment in +/// tests. +fn environment(vars: Option>) -> config::Environment { + config::Environment::with_prefix("EXTENDDB") + .separator("__") + .source(vars) +} + /// The cross-field checks a deserialized config still has to pass, and the /// paths made absolute while the working directory is still the shell's. fn validated(mut config: AppConfig) -> anyhow::Result { @@ -494,7 +510,7 @@ pub fn load_builtin_defaults() -> anyhow::Result { &storage_section, config::FileFormat::Toml, )) - .add_source(config::Environment::with_prefix("EXTENDDB").separator("__")) + .add_source(environment(None)) .build()?; validated(config.try_deserialize()?) } @@ -545,7 +561,9 @@ pub fn pid_file_path_default(port: u16) -> PathBuf { pub mod backup; mod display; +mod encryption; pub use display::{MASK, build_config_entries, should_redact}; +pub use encryption::EncryptionConfig; #[cfg(test)] mod tests { diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 8251d1bbf..d0d7a7410 100755 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -53,6 +53,8 @@ base64 = { workspace = true } time = { workspace = true } sha2 = { workspace = true } rand = { workspace = true } +# The KEK file's bytes and text (`key_file`), wiped when they drop. +zeroize = { workspace = true } axum-server = { workspace = true } rustls = { workspace = true } tracing-subscriber = { workspace = true } diff --git a/crates/server/src/console/pages/account_scope_reads_tests.rs b/crates/server/src/console/pages/account_scope_reads_tests.rs index 628eba2b3..4654d0ae1 100644 --- a/crates/server/src/console/pages/account_scope_reads_tests.rs +++ b/crates/server/src/console/pages/account_scope_reads_tests.rs @@ -27,8 +27,10 @@ use extenddb_storage::authorization_store::{AuthorizationStore, SessionData as R use extenddb_storage::management_store::{ AccessKeyCreated, AccountDetail, AdminEntry, AdminStore, GroupDetail, GroupListEntry, ManagementStore, MetricsFilter, MetricsRow, MetricsStore, OpError, OpResult, PasswordHashStore, - RateLimitStore, RoleDetail, RoleListEntry, SettingsStore, UserDetail, UserListEntry, + RateLimitStore, RoleDetail, RoleListEntry, SecretPage, SecretWrite, SettingsStore, UserDetail, + UserListEntry, }; +use extenddb_storage::secret_keys::SecretTable; use futures::future::BoxFuture; use serde_json::Value; use time::OffsetDateTime; @@ -137,6 +139,10 @@ impl ManagementStore for CountingStore { &str, &str, &[u8], &str, &str, &str, &Option, &Option, OffsetDateTime ) -> (); fetch_caller_tags(&str, &str) -> Vec<(String, String)>; + read_secret_page(SecretTable, Option<&str>, usize) -> SecretPage; + write_secrets(SecretTable, &[SecretWrite]) -> (); + delete_secrets(SecretTable, &[String]) -> (); + delete_setting(&str) -> (); } } @@ -209,11 +215,7 @@ impl PasswordHashStore for CountingStore { } } -impl CatalogStore for CountingStore { - fn cached_encryption_key(&self) -> Option { - None - } -} +impl CatalogStore for CountingStore {} /// The password hash every test session logs in with. It is made at run /// time, so that no literal reaches the session stamp. diff --git a/crates/server/src/dev_credentials_seed_tests.rs b/crates/server/src/dev_credentials_seed_tests.rs index 0444a7637..92b385601 100644 --- a/crates/server/src/dev_credentials_seed_tests.rs +++ b/crates/server/src/dev_credentials_seed_tests.rs @@ -55,9 +55,12 @@ async fn start(path: &Path) -> Start { // Any fixed 32-byte key: the two stores only have to agree on it. let key = base64::engine::general_purpose::STANDARD.encode([7u8; 32]); - let catalog = SqliteCatalogStore::with_encryption_key( + let keys = Some(Arc::new( + extenddb_storage::secret_keys::SecretKeys::catalog_key(&key).expect("a catalog key"), + )); + let catalog = SqliteCatalogStore::with_secret_keys( pool.clone(), - key.clone(), + keys.clone(), Arc::new(tokio::sync::Mutex::new(())), ); match catalog.create_account(ACCOUNT, "dev").await { @@ -70,7 +73,7 @@ async fn start(path: &Path) -> Start { .expect("record the default account"); Start { catalog, - credentials: SqliteCredentialStore::new(pool, key), + credentials: SqliteCredentialStore::new(pool, keys), } } diff --git a/crates/server/src/key_file.rs b/crates/server/src/key_file.rs new file mode 100644 index 000000000..8461b34c8 --- /dev/null +++ b/crates/server/src/key_file.rs @@ -0,0 +1,493 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The key-encryption key (KEK) file: the file rule that `serve` and every +//! `extenddb encryption-key` command apply before they read the key, and the +//! file's format. +//! +//! The file rule, in order: +//! +//! 1. The path resolves to its canonical form, so a Kubernetes secret volume's +//! symlink is judged by its target. +//! 2. Every parent directory of the canonical path passes the backup store's +//! ancestor check: owned by root or the effective user, and not writable by +//! group or others unless sticky. +//! 3. The canonical path opens with `O_NOFOLLOW`, and the checks run on the +//! descriptor's `fstat`, so the file cannot be swapped between the check +//! and the read. It is a regular file that root or the effective user +//! owns, and others have no permission bits. +//! 4. On Linux the POSIX ACL of the descriptor is read before the group bits +//! are judged, because with a mask entry the group bits of `st_mode` are +//! the mask (acl(5)). Each named user entry names the effective user, each +//! named group entry names the effective group, and the entry for others +//! grants nothing. Group access (the mode's group bits without a mask, the +//! owning group's entry under one, a named group entry) is accepted only +//! on a file that root owns, and only for the effective group: the rule +//! cannot see the group's other members. Other platforms check the owner +//! and the mode only ([`ACL_NOT_READ`]). +//! +//! The file's format is the key ring's ([`parse_kek_file`]): the 32-byte key +//! in standard base64 with padding, 44 characters, and at most one trailing +//! newline. Every buffer that holds the file's bytes or the key is wiped when +//! it drops, and no message carries a byte of the file. The key is decoded +//! into one heap allocation ([`Kek`]), so a move of it leaves no copy. + +// The ACL parser runs on Linux only, and the descriptor checks on Unix only; +// the tests run every part on every platform. +#![cfg_attr(not(target_os = "linux"), allow(dead_code))] + +use std::path::Path; + +use extenddb_storage::key_ring::{Kek, parse_kek_file}; +use extenddb_storage::secret_cipher::KEY_LEN; +use zeroize::Zeroizing; + +/// The startup log line on a platform where the file rule reads no ACL, or +/// `None` on Linux, where it does. +pub const ACL_NOT_READ: Option<&str> = if cfg!(target_os = "linux") { + None +} else { + Some( + "The KEK file check reads the file's owner and mode only on this platform; an access \ + control list on the file is not checked.", + ) +}; + +/// A KEK file at a configured path, read through the file rule each time the +/// commands ask for it ([`read_key_file`]). +#[derive(Debug, Clone)] +pub struct KeyFile(pub String); + +impl extenddb_storage::key_commands::KekFile for KeyFile { + fn path(&self) -> &str { + &self.0 + } + + fn read(&self) -> Result, String> { + read_key_file(&self.0).map(|kek| Zeroizing::new(**kek)) + } +} + +use extenddb_auth::secmem; +pub use extenddb_auth::secmem::Protection; + +/// The keys that the startup loader can hold at once (RFC-0000 section 7): the +/// two DEKs of a ring with an unfinished replacement, which it unwraps before +/// it reads the other fields, and the catalog key. The DEK the server keeps is +/// one of them. +const STARTUP_KEY_SLOTS: usize = 3; + +/// The locked key store's slots for `serve`: two signing keys per entry of +/// the credential cache (`[auth.cache] max_entries`), the keys of startup +/// ([`STARTUP_KEY_SLOTS`]), and one temporary buffer per runtime worker +/// thread. +#[must_use] +pub fn serve_slots(max_entries: u64, workers: usize) -> usize { + usize::try_from(max_entries) + .unwrap_or(usize::MAX) + .saturating_mul(2) + .saturating_add(STARTUP_KEY_SLOTS) + .saturating_add(workers) +} + +/// The locked key store's slots for an `encryption-key` command, which +/// caches no credential: one 4 KiB page of 32-byte slots, which the store +/// locks whole for any smaller count, and more than a run holds at once (the +/// catalog key, the two DEKs of a ring, a new DEK, and their copies inside a +/// step). +pub const COMMAND_SLOTS: usize = 128; + +/// Set the process's locked key store up with `slots` slots, as the last +/// rows of RFC-0000 section 7 say: when locking fails, refuse while a KEK is +/// in use (`key_file` set, or a command's `--key-file`) and +/// `require_locked_memory` is true; otherwise log a warning and keep the +/// keys in memory that is not locked. Returns the protection in force, the +/// word of the startup log line. +/// +/// # Errors +/// +/// The refusal, with the memory the store needs and the fixes. +pub fn init_key_store( + kek_in_use: bool, + require_locked_memory: bool, + slots: usize, +) -> Result { + match secmem::init(slots) { + Ok(protection) => Ok(protection), + Err(error) => { + let warning = lock_failure(kek_in_use, require_locked_memory, &error)?; + tracing::warn!("{warning}"); + Ok(secmem::init_unlocked(slots)) + } + } +} + +/// The warning for a store that could not lock, or the refusal when a KEK is +/// in use and locked memory is required. +fn lock_failure( + kek_in_use: bool, + require_locked_memory: bool, + error: &dyn std::fmt::Display, +) -> Result { + if kek_in_use && require_locked_memory { + return Err(format!( + "{error}. With a KEK file the keys must be in locked memory; \ + [auth.encryption] require_locked_memory = false starts with them in ordinary \ + memory instead, which swap and core dumps can hold" + )); + } + Ok(format!( + "{error}. The keys are in ordinary memory, which swap and core dumps can hold" + )) +} + +/// The key a factory loads for this configuration (RFC-0000 section 7): the +/// KEK read through the file rule when `[auth.encryption] key_file` is set, +/// else the catalog key. `serve` and the backup commands pass it in +/// `ServerComponentsOptions::key_source`. +/// +/// # Errors +/// +/// The file rule's refusal. +pub fn key_source( + encryption: &extenddb_config::EncryptionConfig, +) -> Result { + use extenddb_storage::server_components::KeySource; + let Some(path) = encryption.key_file_path() else { + return Ok(KeySource::CatalogKey); + }; + if let Some(note) = ACL_NOT_READ { + tracing::info!("{note}"); + } + read_key_file(&path).map(KeySource::Kek) +} + +/// Read the KEK file at `path` through the file rule. +/// +/// # Errors +/// +/// The refusal, naming the path and the check that failed; on a platform +/// without POSIX ownership and modes, a refusal of every path. +pub fn read_key_file(path: &str) -> Result { + let canonical = std::fs::canonicalize(path) + .map_err(|e| format!("KEK file {path} cannot be resolved: {e}"))?; + let name = if canonical == Path::new(path) { + path.to_owned() + } else { + format!("{path} (resolved to {})", canonical.display()) + }; + // Check 2: the backup store's ancestor check, which the backup root and + // the restore spool use too. + extenddb_backup_store::check_private_ancestors(&canonical, "KEK file") + .map_err(|e| format!("KEK file {name}: {e}"))?; + read_checked(&canonical).map_err(|reason| format!("KEK file {name} {reason}")) +} + +/// Whether the files at `a` and `b` are on one file system (the same +/// `st_dev`), so that one snapshot of it holds both (RFC-0000 section 11). +/// `false` when either cannot be read, and where there is no `st_dev`. +#[must_use] +pub fn same_file_system(a: &Path, b: &Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + matches!( + (std::fs::metadata(a), std::fs::metadata(b)), + (Ok(a), Ok(b)) if a.dev() == b.dev() + ) + } + #[cfg(not(unix))] + { + let _ = (a, b); + false + } +} + +/// Checks 3 and 4 and the format, on the file at the canonical path. The +/// reason starts with a verb, after the file's name. +#[cfg(unix)] +fn read_checked(canonical: &Path) -> Result { + use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _}; + + // `O_NONBLOCK` keeps the open of a FIFO from waiting for a writer and + // `O_NOCTTY` keeps a terminal from becoming the daemon's; check 3 then + // refuses both as not a regular file. + let mut file = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_NOCTTY) + .open(canonical) + .map_err(|e| { + if e.raw_os_error() == Some(libc::ELOOP) { + "was replaced by a symlink after its path was resolved".to_owned() + } else { + format!("cannot be opened: {e}") + } + })?; + let meta = file + .metadata() + .map_err(|e| format!("cannot be read: {e}"))?; + let facts = FileFacts { + regular: meta.file_type().is_file(), + uid: meta.uid(), + gid: meta.gid(), + mode: meta.mode() & 0o7777, + }; + let acl = read_acl(&file)?; + judge(&facts, acl.as_deref(), effective_ids())?; + + // A KEK file holds at most 45 bytes; this many more lets the parser say + // how long a wrong file is, up to its size. + let mut contents = Zeroizing::new([0u8; 4096]); + let filled = + read_bounded(&mut file, &mut contents[..]).map_err(|e| format!("cannot be read: {e}"))?; + parse_kek_file(&contents[..filled]).map_err(|reason| format!("is not a KEK file: {reason}")) +} + +/// Read `reader` to its end, or until `buffer` is full, and return the +/// count. The buffer has a fixed size, so no reallocation leaves a copy of a +/// secret behind; the KEK file and the connection string that two commands +/// read from standard input go through it. +/// +/// # Errors +/// +/// The reader's error, other than an interrupted read, which is retried. +pub fn read_bounded( + reader: &mut R, + buffer: &mut [u8], +) -> std::io::Result { + let mut filled = 0; + while filled < buffer.len() { + match reader.read(&mut buffer[filled..]) { + Ok(0) => break, + Ok(n) => filled += n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + Ok(filled) +} + +#[cfg(not(unix))] +fn read_checked(_canonical: &Path) -> Result { + Err( + "cannot be checked on this platform: the KEK file rule needs POSIX file ownership \ + and modes" + .to_owned(), + ) +} + +/// What checks 3 and 4 read of the descriptor's `fstat`. +#[derive(Debug, Clone, Copy)] +struct FileFacts { + regular: bool, + uid: u32, + gid: u32, + /// The permission bits, with setuid, setgid and sticky. + mode: u32, +} + +/// The effective user and group of this process. +#[derive(Debug, Clone, Copy)] +struct Ids { + uid: u32, + gid: u32, +} + +#[cfg(unix)] +fn effective_ids() -> Ids { + Ids { + uid: extenddb_backup_store::effective_uid(), + // SAFETY: getegid has no preconditions and cannot fail. + gid: unsafe { libc::getegid() }, + } +} + +/// One entry of a POSIX ACL, as the kernel stores it in the +/// `system.posix_acl_access` extended attribute. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct AclEntry { + tag: u16, + perm: u16, + id: u32, +} + +/// The ACL entry tags (`linux/posix_acl.h`). +const ACL_USER_OBJ: u16 = 0x01; +const ACL_USER: u16 = 0x02; +const ACL_GROUP_OBJ: u16 = 0x04; +const ACL_GROUP: u16 = 0x08; +const ACL_MASK: u16 = 0x10; +const ACL_OTHER: u16 = 0x20; + +/// The version word of the attribute (`POSIX_ACL_XATTR_VERSION`). +const ACL_XATTR_VERSION: u32 = 2; + +/// The entries of a `system.posix_acl_access` value: a 4-byte little-endian +/// version, then 8 bytes per entry (tag, permission, id). `None` for any +/// other layout or an unknown tag. +fn parse_acl(bytes: &[u8]) -> Option> { + let (version, entries) = bytes.split_first_chunk::<4>()?; + if u32::from_le_bytes(*version) != ACL_XATTR_VERSION || entries.len() % 8 != 0 { + return None; + } + entries + .chunks_exact(8) + .map(|e| { + let entry = AclEntry { + tag: u16::from_le_bytes([e[0], e[1]]), + perm: u16::from_le_bytes([e[2], e[3]]), + id: u32::from_le_bytes([e[4], e[5], e[6], e[7]]), + }; + [ + ACL_USER_OBJ, + ACL_USER, + ACL_GROUP_OBJ, + ACL_GROUP, + ACL_MASK, + ACL_OTHER, + ] + .contains(&entry.tag) + .then_some(entry) + }) + .collect() +} + +/// The access ACL of `file`, or `None` when it has none (the file system +/// keeps no ACL, or the file's ACL is its mode). +#[cfg(target_os = "linux")] +fn read_acl(file: &std::fs::File) -> Result>, String> { + use std::os::fd::AsRawFd as _; + + const NAME: &std::ffi::CStr = c"system.posix_acl_access"; + let fd = file.as_raw_fd(); + let failed = |e: std::io::Error| match e.raw_os_error() { + Some(libc::ENODATA | libc::EOPNOTSUPP) => Ok(None), + _ => Err(format!( + "has an access control list that cannot be read: {e}" + )), + }; + // SAFETY: a zero size asks for the value's length and writes nothing. + let len = unsafe { libc::fgetxattr(fd, NAME.as_ptr(), std::ptr::null_mut(), 0) }; + let Ok(len) = usize::try_from(len) else { + return failed(std::io::Error::last_os_error()); + }; + let mut value = vec![0u8; len]; + // SAFETY: `value` has room for `len` bytes, and the call writes at most + // that many. + let read = unsafe { libc::fgetxattr(fd, NAME.as_ptr(), value.as_mut_ptr().cast(), len) }; + let Ok(read) = usize::try_from(read) else { + return failed(std::io::Error::last_os_error()); + }; + value.truncate(read); + parse_acl(&value).map(Some).ok_or_else(|| { + "has an access control list in a format this server does not read".to_owned() + }) +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn read_acl(_file: &std::fs::File) -> Result>, String> { + Ok(None) +} + +/// Checks 3 and 4 on what the descriptor gave, with `acl` read before the +/// group bits are judged. The reason starts with a verb, after the file's +/// name. +fn judge(facts: &FileFacts, acl: Option<&[AclEntry]>, ids: Ids) -> Result<(), String> { + let mode = facts.mode; + if !facts.regular { + return Err("is not a regular file".to_owned()); + } + if facts.uid != 0 && facts.uid != ids.uid { + return Err(format!( + "is owned by uid {}; root or the server's user (uid {}) must own it", + facts.uid, ids.uid + )); + } + if mode & 0o007 != 0 { + return Err(format!( + "has mode {mode:04o}, which gives other users access; remove it with `chmod o-rwx`" + )); + } + let entries = acl.unwrap_or_default(); + // Group access is accepted only on a file that root owns (the Kubernetes + // `fsGroup` route), and then only for the server's group. The rule cannot + // see who else is in that group. + let root_owned = facts.uid == 0; + for entry in entries { + match entry.tag { + ACL_USER if entry.id != ids.uid => { + return Err(format!( + "has an access control list entry for uid {}, which is not the server's \ + user (uid {}); remove it with `setfacl -x u:{}`", + entry.id, ids.uid, entry.id + )); + } + ACL_GROUP if entry.id != ids.gid => { + return Err(format!( + "has an access control list entry for gid {}, which is not the server's \ + group (gid {}); remove it with `setfacl -x g:{}`", + entry.id, ids.gid, entry.id + )); + } + ACL_GROUP if !root_owned && entry.perm != 0 => { + return Err(format!( + "has an access control list entry for the server's group (gid {}), and \ + group access is accepted only on a file that root owns; remove it with \ + `setfacl -x g:{}`", + entry.id, entry.id + )); + } + ACL_OTHER if entry.perm != 0 => { + return Err( + "has an access control list entry that gives other users access; remove \ + it with `setfacl -m o::---`" + .to_owned(), + ); + } + _ => {} + } + } + if root_owned && facts.gid == ids.gid { + return Ok(()); + } + // Why the owning group may have no access, and the second fix. + let (why, or_chgrp) = if root_owned { + ( + format!("that group is not the server's group (gid {})", ids.gid), + format!( + ", or give the file to the server's group with `chgrp {}`", + ids.gid + ), + ) + } else { + ( + "group access is accepted only on a file that root owns".to_owned(), + String::new(), + ) + }; + // With a mask entry the mode's group bits are the mask, and the owning + // group's own permission is its entry (acl(5)). + if entries.iter().any(|e| e.tag == ACL_MASK) { + if entries + .iter() + .any(|e| e.tag == ACL_GROUP_OBJ && e.perm != 0) + { + return Err(format!( + "gives its group (gid {}) access through its access control list, and {why}; \ + remove it with `setfacl -m g::---`{or_chgrp}", + facts.gid + )); + } + } else if mode & 0o070 != 0 { + return Err(format!( + "has mode {mode:04o}, which gives its group (gid {}) access, and {why}; remove it \ + with `chmod g-rwx`{or_chgrp}", + facts.gid + )); + } + Ok(()) +} + +#[cfg(test)] +#[path = "key_file_tests.rs"] +mod tests; diff --git a/crates/server/src/key_file_tests.rs b/crates/server/src/key_file_tests.rs new file mode 100644 index 000000000..7d736592b --- /dev/null +++ b/crates/server/src/key_file_tests.rs @@ -0,0 +1,495 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Tests of the KEK file rule and format. +//! +//! The rule's judgement is one table over `fstat` facts and ACL entries, so +//! that root-owned files and other users' ids are covered without root. The +//! file tests then run the descriptor path on real files. + +use super::*; + +/// The server's ids in the judgement table: the image's uid and gid. +const SERVER: Ids = Ids { + uid: 10001, + gid: 10001, +}; + +/// An ACL entry with no id, for the owner, owning group, mask and others. +fn base(tag: u16, perm: u16) -> AclEntry { + AclEntry { + tag, + perm, + id: u32::MAX, + } +} + +fn named(tag: u16, perm: u16, id: u32) -> AclEntry { + AclEntry { tag, perm, id } +} + +fn facts(uid: u32, gid: u32, mode: u32) -> FileFacts { + FileFacts { + regular: true, + uid, + gid, + mode, + } +} + +/// Checks 3 and 4: each case is the file's owner, group, mode and ACL, the +/// server's ids, and `None` for a file the rule accepts or a part of the +/// refusal. +#[test] +fn the_file_rule_judges_owner_mode_and_acl() { + const R: u16 = 4; + const RW: u16 = 6; + // systemd's tmpfs credential: root:root at 0400 with an entry for the + // service user, which the kernel reports as 0440 (the mask). + let systemd = |user: u32, group_obj: u16| { + vec![ + base(ACL_USER_OBJ, R), + named(ACL_USER, R, user), + base(ACL_GROUP_OBJ, group_obj), + base(ACL_MASK, R), + base(ACL_OTHER, 0), + ] + }; + let not_regular = FileFacts { + regular: false, + ..facts(SERVER.uid, SERVER.gid, 0o600) + }; + let in_group_0 = Ids { gid: 0, ..SERVER }; + /// What the case is, the file, its ACL, the server's ids, the refusal. + type Case = ( + &'static str, + FileFacts, + Option>, + Ids, + Option<&'static str>, + ); + let cases: Vec = vec![ + ( + "own file 0600", + facts(10001, 10001, 0o600), + None, + SERVER, + None, + ), + ( + "own file 0400", + facts(10001, 10001, 0o400), + None, + SERVER, + None, + ), + ( + "own file 0640, the server's group", + facts(10001, 10001, 0o640), + None, + SERVER, + Some( + "has mode 0640, which gives its group (gid 10001) access, and group access is \ + accepted only on a file that root owns", + ), + ), + ( + "own file, the server's group readable through the ACL", + facts(10001, 10001, 0o640), + Some(vec![ + base(ACL_USER_OBJ, RW), + base(ACL_GROUP_OBJ, R), + base(ACL_MASK, R), + base(ACL_OTHER, 0), + ]), + SERVER, + Some( + "gives its group (gid 10001) access through its access control list, and group \ + access is accepted only on a file that root owns", + ), + ), + ( + "systemd tmpfs: root owner, named-user entry for the server", + facts(0, 0, 0o440), + Some(systemd(10001, 0)), + SERVER, + None, + ), + ( + "root owner, named-user entry for another user", + facts(0, 0, 0o440), + Some(systemd(10002, 0)), + SERVER, + Some("entry for uid 10002, which is not the server's user (uid 10001)"), + ), + ( + "root owner, the owning group readable through the ACL", + facts(0, 0, 0o440), + Some(systemd(10001, R)), + SERVER, + Some("gives its group (gid 0) access through its access control list"), + ), + ( + "the owning group readable through the ACL, the server's group", + facts(0, 10001, 0o440), + Some(systemd(10001, R)), + SERVER, + None, + ), + ( + "Kubernetes fsGroup: root owner, group 10001, 0440", + facts(0, 10001, 0o440), + None, + SERVER, + None, + ), + ( + "Kubernetes fsGroup, server with effective group 0", + facts(0, 10001, 0o440), + None, + in_group_0, + Some( + "gives its group (gid 10001) access, and that group is not the server's group (gid 0)", + ), + ), + ( + "group-readable, root owner, the group is not the server's", + facts(0, 20, 0o640), + None, + SERVER, + Some("has mode 0640, which gives its group (gid 20) access"), + ), + ( + "readable by others", + facts(10001, 10001, 0o604), + None, + SERVER, + Some("has mode 0604, which gives other users access"), + ), + ( + "owned by another user", + facts(10002, 10001, 0o600), + None, + SERVER, + Some("is owned by uid 10002; root or the server's user (uid 10001) must own it"), + ), + ( + "not a regular file", + not_regular, + None, + SERVER, + Some("is not a regular file"), + ), + ( + "named-group entry for another group", + facts(10001, 10001, 0o640), + Some(vec![ + base(ACL_USER_OBJ, RW), + base(ACL_GROUP_OBJ, 0), + named(ACL_GROUP, R, 30), + base(ACL_MASK, R), + base(ACL_OTHER, 0), + ]), + SERVER, + Some("entry for gid 30, which is not the server's group (gid 10001)"), + ), + ( + "named-group entry for the server's group, another owning group", + facts(10001, 20, 0o640), + Some(vec![ + base(ACL_USER_OBJ, RW), + base(ACL_GROUP_OBJ, 0), + named(ACL_GROUP, R, 10001), + base(ACL_MASK, R), + base(ACL_OTHER, 0), + ]), + SERVER, + Some( + "entry for the server's group (gid 10001), and group access is accepted only on \ + a file that root owns", + ), + ), + ( + "root owner, named-group entry for the server's group, another owning group", + facts(0, 20, 0o440), + Some(vec![ + base(ACL_USER_OBJ, R), + base(ACL_GROUP_OBJ, 0), + named(ACL_GROUP, R, 10001), + base(ACL_MASK, R), + base(ACL_OTHER, 0), + ]), + SERVER, + None, + ), + ( + "an ACL entry for others that grants access", + facts(10001, 10001, 0o600), + Some(vec![ + base(ACL_USER_OBJ, RW), + base(ACL_GROUP_OBJ, 0), + base(ACL_OTHER, R), + ]), + SERVER, + Some("entry that gives other users access"), + ), + ]; + for (what, facts, acl, ids, refusal) in cases { + let got = judge(&facts, acl.as_deref(), ids); + match refusal { + None => assert_eq!(got, Ok(()), "{what}"), + Some(part) => { + let reason = got.expect_err(what); + assert!( + reason.contains(part), + "{what}: the refusal does not contain {part:?}" + ); + } + } + } +} + +/// A store that could not lock refuses startup only while a KEK is in use +/// and locked memory is required; every other case warns. Both carry the +/// store's own error, which names the memory needed and the fixes. +#[test] +fn a_lock_failure_refuses_only_with_a_kek_and_the_requirement() { + let error = "the locked key store needs 643072 bytes"; + for (kek_in_use, required, refuses) in [ + (true, true, true), + (true, false, false), + (false, true, false), + (false, false, false), + ] { + let outcome = lock_failure(kek_in_use, required, &error); + let text = match &outcome { + Ok(warning) => warning, + Err(refusal) => refusal, + }; + assert_eq!(outcome.is_err(), refuses, "{kek_in_use} {required}: {text}"); + assert!(text.starts_with(error), "{text}"); + assert_eq!( + text.contains("require_locked_memory = false"), + refuses, + "{text}" + ); + } + assert_eq!(serve_slots(10_000, 16), 20_019); + assert_eq!(serve_slots(u64::MAX, 16), usize::MAX); +} + +/// The attribute's layout: a version word of 2, then whole 8-byte entries of +/// known tags. +#[test] +fn the_acl_attribute_parses_only_in_the_kernel_layout() { + let entry = |tag: u16, perm: u16, id: u32| { + let mut bytes = tag.to_le_bytes().to_vec(); + bytes.extend(perm.to_le_bytes()); + bytes.extend(id.to_le_bytes()); + bytes + }; + let value = |version: u32, entries: &[Vec]| { + let mut bytes = version.to_le_bytes().to_vec(); + for e in entries { + bytes.extend(e); + } + bytes + }; + let owner = entry(ACL_USER_OBJ, 6, u32::MAX); + let user = entry(ACL_USER, 4, 10001); + let one = std::slice::from_ref(&owner); + /// What the case is, the attribute's bytes, and its entries. + type Case = (&'static str, Vec, Option>); + let cases: Vec = vec![ + ( + "two entries", + value(2, &[owner.clone(), user]), + Some(vec![base(ACL_USER_OBJ, 6), named(ACL_USER, 4, 10001)]), + ), + ("version 1", value(1, one), None), + ("a cut entry", value(2, one)[..11].to_vec(), None), + ("an unknown tag", value(2, &[entry(0x40, 4, 0)]), None), + ("no version word", vec![2, 0], None), + ]; + for (what, bytes, expected) in cases { + assert_eq!(parse_acl(&bytes), expected, "{what}"); + } +} + +#[cfg(unix)] +mod files { + use std::os::unix::fs::PermissionsExt as _; + use std::path::{Path, PathBuf}; + + use super::*; + + const KEY: &str = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="; + + /// A private directory for one test's files. + fn private_dir() -> tempfile::TempDir { + let dir = tempfile::tempdir().expect("tempdir"); + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)) + .expect("chmod dir"); + dir + } + + /// A KEK file holding `KEY` and a newline, at `mode`. + fn key_file(dir: &Path, name: &str, mode: u32) -> PathBuf { + let path = dir.join(name); + std::fs::write(&path, format!("{KEY}\n")).expect("write"); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).expect("chmod"); + path + } + + fn key_bytes() -> Vec { + (0u8..32).collect() + } + + /// Checks 3 and 4 and the format, through the descriptor: each case is a + /// file this user makes, and `None` for a file the rule reads or a part + /// of the refusal. + #[test] + fn the_descriptor_checks_run_on_real_files() { + let dir = private_dir(); + let fifo = dir.path().join("fifo"); + let fifo_c = std::ffi::CString::new(fifo.as_os_str().as_encoded_bytes()).expect("path"); + // SAFETY: `fifo_c` is a NUL-terminated path. + assert_eq!(unsafe { libc::mkfifo(fifo_c.as_ptr(), 0o600) }, 0, "mkfifo"); + let target = key_file(dir.path(), "target", 0o600); + let link = dir.path().join("link"); + std::os::unix::fs::symlink(&target, &link).expect("symlink"); + let subdir = dir.path().join("dir"); + std::fs::create_dir(&subdir).expect("mkdir"); + // The key with one character outside the base64 alphabet, which the + // refusal must not repeat. + let bad = dir.path().join("bad"); + std::fs::write(&bad, format!("{}*{}\n", &KEY[..5], &KEY[6..])).expect("write"); + std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o600)).expect("chmod"); + let cases: Vec<(&str, PathBuf, Option<&str>)> = vec![ + ("0600", key_file(dir.path(), "a", 0o600), None), + ("0400", key_file(dir.path(), "b", 0o400), None), + ( + "0640, own group", + key_file(dir.path(), "c", 0o640), + Some("group access is accepted only on a file that root owns"), + ), + ( + "0604", + key_file(dir.path(), "d", 0o604), + Some("has mode 0604, which gives other users access"), + ), + ( + "a FIFO, which must not block the open", + fifo, + Some("is not a regular file"), + ), + ("a directory", subdir, Some("is not a regular file")), + ( + "a symlink at the resolved path", + link, + Some("was replaced by a symlink after its path was resolved"), + ), + ( + "a character outside the alphabet", + bad, + Some("is not a KEK file: decode encryption key: invalid symbol at offset 5"), + ), + ]; + for (what, path, refusal) in cases { + match (read_checked(&path), refusal) { + (Ok(key), None) => assert_eq!(key.as_slice(), key_bytes(), "{what}"), + (Err(reason), Some(part)) => { + assert!(reason.contains(part), "{what}: {reason}"); + assert!(!reason.contains('*'), "{what}: {reason}"); + } + (got, _) => panic!("{what}: {:?}", got.map(|_| "a key")), + } + } + } + + /// An ACL the kernel stored reads back as its entries, and the rule + /// accepts one whose named entries are the server's own ids and whose + /// group entries grant nothing, on a file the server's user owns. + #[cfg(target_os = "linux")] + #[test] + fn an_acl_the_kernel_stored_is_read_from_the_descriptor() { + let dir = private_dir(); + let path = key_file(dir.path(), "kek", 0o600); + let ids = effective_ids(); + let entries = [ + base(ACL_USER_OBJ, 6), + named(ACL_USER, 4, ids.uid), + base(ACL_GROUP_OBJ, 0), + named(ACL_GROUP, 0, ids.gid), + base(ACL_MASK, 4), + base(ACL_OTHER, 0), + ]; + let mut value = ACL_XATTR_VERSION.to_le_bytes().to_vec(); + for e in &entries { + value.extend(e.tag.to_le_bytes()); + value.extend(e.perm.to_le_bytes()); + value.extend(e.id.to_le_bytes()); + } + let file = std::fs::File::open(&path).expect("open"); + { + use std::os::fd::AsRawFd as _; + // SAFETY: `value` is valid for its length, and the name is + // NUL-terminated. + let set = unsafe { + libc::fsetxattr( + file.as_raw_fd(), + c"system.posix_acl_access".as_ptr(), + value.as_ptr().cast(), + value.len(), + 0, + ) + }; + if set != 0 { + let e = std::io::Error::last_os_error(); + eprintln!("skipped: this file system keeps no ACL here: {e}"); + return; + } + } + assert_eq!(read_acl(&file).expect("read"), Some(entries.to_vec())); + // The mask is now the mode's group bits. + let mode = std::fs::metadata(&path).expect("stat").permissions().mode() & 0o777; + assert_eq!(mode, 0o640); + assert_eq!(read_checked(&path).expect("read").as_slice(), key_bytes()); + } + + /// The whole rule from the configured path: a missing file names the + /// path, a parent writable by others is refused as an ancestor, and a + /// symlink is judged by its target. + #[test] + fn the_rule_resolves_the_path_and_checks_its_ancestors() { + let dir = private_dir(); + let missing = dir.path().join("missing"); + let missing = missing.to_str().expect("utf-8"); + let reason = read_key_file(missing).expect_err("missing"); + assert!( + reason.starts_with(&format!("KEK file {missing} cannot be resolved: ")), + "{reason}" + ); + + let open = dir.path().join("open"); + std::fs::create_dir(&open).expect("mkdir"); + let in_open = key_file(&open, "kek", 0o600); + std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o777)).expect("chmod"); + let reason = read_key_file(in_open.to_str().expect("utf-8")).expect_err("open parent"); + assert!(reason.contains("an ancestor of the KEK file"), "{reason}"); + assert!(reason.contains("writable by group or others"), "{reason}"); + + let target = key_file(dir.path(), "target", 0o600); + let link = dir.path().join("link"); + std::os::unix::fs::symlink(&target, &link).expect("symlink"); + match read_key_file(link.to_str().expect("utf-8")) { + Ok(key) => assert_eq!(key.as_slice(), key_bytes()), + // A host whose directories above the temp directory belong to a + // user outside this user namespace refuses every path there. + Err(reason) if reason.contains("(an ancestor of the KEK file) is owned by uid") => { + eprintln!("skipped the symlink case: {reason}"); + } + Err(reason) => panic!("{reason}"), + } + } +} diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index f723b3790..c80ccde4c 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -19,6 +19,7 @@ mod handler; mod import_export_paths; mod import_export_roots; mod item_authz; +pub mod key_file; pub mod key_info_cache; mod leading_keys; mod listener; diff --git a/crates/server/src/management/assume_role.rs b/crates/server/src/management/assume_role.rs index 94d0bf457..7b4d42bf1 100755 --- a/crates/server/src/management/assume_role.rs +++ b/crates/server/src/management/assume_role.rs @@ -17,9 +17,7 @@ use serde_json::Value; use super::ManagementState; use super::auth::authenticate_admin; -use super::crypto::{ - encrypt_secret, generate_secret_key, generate_session_key_id, generate_session_token, -}; +use super::crypto::{generate_secret_key, generate_session_key_id, generate_session_token}; use extenddb_auth::policy::arn_value::{ fail_closed_trust_arn_value, invalid_trust_arn_value, trust_arn_value_message, }; @@ -28,6 +26,7 @@ use extenddb_auth::policy::context::AssumeRoleContext; use extenddb_auth::policy::document::{ Condition, PolicyDocument, PolicyParseError, parse_conditions, }; +use extenddb_storage::secret_keys::SecretRow; #[derive(Deserialize)] pub struct AssumeRoleRequest { @@ -289,30 +288,33 @@ async fn generate_and_store_session( request: &AssumeRoleRequest, caller_arn: &str, ) -> Response { - // P119: Use cached encryption key if available, fall back to DB query. - let enc_key_b64: String = - if let Some(k) = extenddb_storage::CatalogStore::cached_encryption_key(store) { - k - } else { - match store.get_setting("encryption_key").await { - Ok(Some(k)) => k, - Ok(None) => { - tracing::error!("Management API: encryption key not found in settings"); - return StatusCode::INTERNAL_SERVER_ERROR.into_response(); - } - Err(e) => { - tracing::error!("Management API: fetch encryption key failed: {e:?}"); - return StatusCode::INTERNAL_SERVER_ERROR.into_response(); - } - } - }; + // The store's one key holder (RFC-0000 section 6.2): the catalog key or + // the DEK. A store opened without a key creates no credential. + let Some(keys) = extenddb_storage::CatalogStore::secret_keys(store) else { + tracing::error!("Management API: the catalog store holds no encryption key"); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + }; // Generate ASIA* temporary credentials. let access_key_id = generate_session_key_id(); let secret_key = generate_secret_key(); let session_token = generate_session_token(); - let encrypted = match encrypt_secret(&secret_key, &enc_key_b64, &access_key_id) { + // Fixed before the encrypt, in whole seconds: the AAD of a secret under a + // DEK binds `expires_at` in whole Unix seconds (RFC-0000 section 5), and + // the row stores the same value. + let expires_at = + time::OffsetDateTime::now_utc() + time::Duration::seconds(request.duration_seconds); + let expires_at = expires_at.replace_nanosecond(0).unwrap_or(expires_at); + + let row = SecretRow::session( + &access_key_id, + account_id, + role_name, + &request.session_name, + expires_at.unix_timestamp(), + ); + let encrypted = match keys.encrypt(&row, &secret_key) { Ok(e) => e, Err(msg) => { tracing::error!("Management API: encrypt session secret failed: {msg}"); @@ -320,9 +322,6 @@ async fn generate_and_store_session( } }; - let expires_at = - time::OffsetDateTime::now_utc() + time::Duration::seconds(request.duration_seconds); - match store .store_session( &session_token, diff --git a/crates/server/src/management/crypto.rs b/crates/server/src/management/crypto.rs index e5cd6152f..83e50e051 100755 --- a/crates/server/src/management/crypto.rs +++ b/crates/server/src/management/crypto.rs @@ -1,18 +1,13 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! Shared cryptographic helpers for the management API. -//! -//! Provides secret key generation for the temporary session credentials that -//! `assume_role` issues, and re-exports the AES-256-GCM secret encryption that -//! every storage backend uses, from `extenddb_storage::secret_cipher`. +//! Shared cryptographic helpers for the management API: the secret key, +//! session key ID and session token that `assume_role` issues. The secret is +//! encrypted through the catalog store's key holder +//! (`extenddb_storage::secret_keys::SecretKeys`). use rand::Rng; -/// Encrypt a secret key under the base64 catalog encryption key, with the -/// access key id as the AAD. Returns `nonce || ciphertext || tag`. -pub use extenddb_storage::secret_cipher::encrypt_secret; - /// Generate a 40-character secret access key branded with `extenddb` prefix. /// /// Format: `extenddb` + 32 random chars = 40 total. diff --git a/crates/server/src/management/settings.rs b/crates/server/src/management/settings.rs index d148367e1..56b8b57d4 100755 --- a/crates/server/src/management/settings.rs +++ b/crates/server/src/management/settings.rs @@ -25,6 +25,18 @@ struct SettingEntry { value: String, } +/// The value a route returns for the row `key`: [`MASK`] for a key that +/// [`should_redact`] matches, with the stored value wiped first, so the route +/// keeps no copy of a secret such as the catalog key; else the value. +fn shown(key: &str, mut value: String) -> String { + if should_redact(key) { + zeroize::Zeroize::zeroize(&mut value); + MASK.to_owned() + } else { + value + } +} + fn op_err_to_response(e: extenddb_storage::management_store::OpError) -> Response { super::ops::op_err_to_response(super::ops::OpError::from_storage(e)) } @@ -46,11 +58,7 @@ pub async fn list_settings( let entries: Vec = rows .into_iter() .map(|(key, value)| SettingEntry { - value: if should_redact(&key) { - MASK.to_owned() - } else { - value - }, + value: shown(&key, value), key, }) .collect(); @@ -74,18 +82,11 @@ pub async fn get_setting( } match state.catalog_store.get_setting(&key).await { - Ok(Some(value)) => { - let display_value = if should_redact(&key) { - MASK.to_owned() - } else { - value - }; - Json(SettingEntry { - key, - value: display_value, - }) - .into_response() - } + Ok(Some(value)) => Json(SettingEntry { + value: shown(&key, value), + key, + }) + .into_response(), Ok(None) => (axum::http::StatusCode::NOT_FOUND, "Setting not found").into_response(), Err(e) => op_err_to_response(e), } @@ -111,18 +112,38 @@ pub async fn set_setting( } match ops_settings::set_setting(&*state.catalog_store, &key, &body.value).await { - Ok(()) => { - let display_value = if should_redact(&key) { - MASK.to_owned() - } else { - body.value - }; - Json(SettingEntry { - key, - value: display_value, - }) - .into_response() - } + Ok(()) => Json(SettingEntry { + value: shown(&key, body.value), + key, + }) + .into_response(), Err(e) => op_err_to_response(e), } } + +#[cfg(test)] +mod tests { + use super::{MASK, shown}; + + /// A row whose key has a secret pattern is masked, the key ring of a KEK + /// deployment among them; any other value passes through. + #[test] + fn a_secret_row_is_masked_and_others_pass_through() { + for (key, value, expected) in [ + ( + "encryption_key", + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", + MASK, + ), + ("encryption_key_ring", "{\"version\":1}", MASK), + ( + "data_database_connection_string", + "postgresql://extenddb:apppassword@127.0.0.1/extenddb", + MASK, + ), + ("log_level", "info", "info"), + ] { + assert_eq!(shown(key, value.to_owned()), expected, "{key}"); + } + } +} diff --git a/crates/server/src/serve.rs b/crates/server/src/serve.rs index f1554b677..788593630 100644 --- a/crates/server/src/serve.rs +++ b/crates/server/src/serve.rs @@ -404,6 +404,21 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { tracing::warn!("{}", warning.log_message()); } + // The key the factory loads (RFC-0000 section 7). With `[auth.encryption] + // key_file` set it is the KEK, read through the file rule; the factory's + // loader unwraps the ring's DEK with it and drops it, which wipes it. + let key_file = app_config.auth.encryption.key_file_path(); + let key_source = + crate::key_file::key_source(&app_config.auth.encryption).map_err(anyhow::Error::msg)?; + // Before the factory, which puts the key in the store. + let workers = tokio::runtime::Handle::current().metrics().num_workers(); + let protection = crate::key_file::init_key_store( + key_file.is_some(), + app_config.auth.encryption.require_locked_memory, + crate::key_file::serve_slots(app_config.auth.cache.max_entries, workers), + ) + .map_err(anyhow::Error::msg)?; + // Create server components via factory pattern. Dev mode asks the backend // to bootstrap an uninitialized catalog at serve time (zero-config use). let mut component_options = @@ -413,6 +428,7 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { component_options.max_item_size_bytes = app_config.limits.max_item_size_bytes; component_options.release = build.version; component_options.max_concurrent_jobs = app_config.backup.max_concurrent_jobs; + component_options.key_source = key_source; // Wire the node's own bind address as the instance ID so each ExtendDB node // has a distinct node ID (to support logical clocks for sequences, etc.). @@ -440,6 +456,28 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { } Err(other) => return Err(other.into()), }; + // The options and the KEK they carried are dropped: the KEK is wiped. + // The catalog key warning is serve's alone, so the commands that open the + // catalog through the same factory print nothing new. + match key_file.as_deref() { + None => tracing::warn!( + "The stored secrets are encrypted under the catalog key, which the catalog holds, \ + so a copy of the catalog decrypts every stored secret. `extenddb encryption-key \ + switch --key-file ` moves the key to a KEK file outside the catalog." + ), + Some(path) => { + if let Some(database) = app_config.storage.database_file() + && crate::key_file::same_file_system(std::path::Path::new(path), &database) + { + tracing::warn!( + "The KEK file {path} and the database file {} are on the same file \ + system, so one snapshot of it holds the key ring and the KEK that opens \ + it. Keep the KEK file on another file system.", + database.display() + ); + } + } + } let storage = components.engine; let catalog_store = components.catalog_store; @@ -519,20 +557,28 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { // Phase 2: Wrap the raw credential store. In pass-through mode the // wrapper bypasses the cache and forwards every lookup to the inner - // store; otherwise it caches per the TOML config. + // store; otherwise it caches per the TOML config. The cache derives + // signing keys for the server's region and reserves one temporary + // buffer per runtime worker thread (RFC-0000 section 6.1). + let region = app_config.server.region.as_str(); let cached_cred_store = Arc::new(if cache_enabled { - extenddb_auth::CachedCredentialStore::with_arc(cred_store, make_cache_cfg("credential")) + extenddb_auth::CachedCredentialStore::with_arc( + cred_store, + make_cache_cfg("credential"), + region, + workers, + ) } else { extenddb_auth::CachedCredentialStore::pass_through_arc( cred_store, make_cache_cfg("credential"), + region, + workers, ) }); - let auth: Arc = - Arc::new(extenddb_auth::BuiltinAuthProvider::new( - (*cached_cred_store).clone(), - app_config.server.region.as_str(), - )); + let auth: Arc = Arc::new( + extenddb_auth::BuiltinAuthProvider::new((*cached_cred_store).clone()), + ); // Phase 3: Build the authorization cache. let authz_cache: Arc = { @@ -579,10 +625,11 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { .and_then(|h| h.backend_info()) .unwrap_or_else(|| "(unknown)".to_owned()); - // REQ-LOG-001: Startup banner with effective configuration. + // REQ-LOG-001: Startup banner with effective configuration, and the + // protection of the locked key store (RFC-0000 section 6.2). // REQ-LOG-002: Connection strings redact passwords. tracing::info!( - "extenddb {} (catalog {}) starting — bind={}:{}, region={}, auth={}, catalog_db={}, data_db={}, log_output={}, log_level={}", + "extenddb {} (catalog {}) starting — bind={}:{}, region={}, auth={}, catalog_db={}, data_db={}, log_output={}, log_level={}, key_store={}", build.version, catalog_version, app_config.server.bind_addr, @@ -593,6 +640,7 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { data_db_info, log_target.label(), app_config.logging.level, + protection, ); // Convert pre-bound std listener to tokio (D-4: bind before fork). diff --git a/crates/storage-cassandra/src/bootstrapper.rs b/crates/storage-cassandra/src/bootstrapper.rs index 0eef33130..6052d62a0 100644 --- a/crates/storage-cassandra/src/bootstrapper.rs +++ b/crates/storage-cassandra/src/bootstrapper.rs @@ -954,6 +954,7 @@ impl Bootstrapper for CassandraBootstrapper { password: self.config.admin_password.clone(), }), data_connection: None, + ..Target::default() } } diff --git a/crates/storage-cassandra/src/cassandra_util.rs b/crates/storage-cassandra/src/cassandra_util.rs index 1cf51f9e2..8705e5773 100644 --- a/crates/storage-cassandra/src/cassandra_util.rs +++ b/crates/storage-cassandra/src/cassandra_util.rs @@ -35,15 +35,25 @@ pub enum Stmt { Lwt, /// A read at `LOCAL_SERIAL`, which sees every committed Paxos round. SerialRead, - /// A read at `ALL`. Use it only to read rows that an earlier version of - /// ExtendDB wrote at `ONE`: the in-catalog backup payload that - /// `backup migrate-legacy` reads. A quorum read can miss a row that only - /// one replica holds. At `ALL`, every replica answers, so a replica that - /// is down fails the read instead of shortening it. The restore of an - /// in-catalog backup reads the same rows as [`Stmt::Read`]: a row that - /// read misses fails the restore with an item count mismatch. Remove - /// this kind when `backup migrate-legacy` is removed. + /// A read at `ALL`, for two kinds of read. The first reads rows that an + /// earlier version of ExtendDB wrote at `ONE`: the in-catalog backup + /// payload that `backup migrate-legacy` reads. A quorum read can miss a + /// row that only one replica holds. At `ALL`, every replica answers, so a + /// replica that is down fails the read instead of shortening it. The + /// restore of an in-catalog backup reads the same rows as [`Stmt::Read`]: + /// a row that read misses fails the restore with an item count mismatch. + /// The second is the encryption-key commands' reads of the key rows and + /// of the stored secrets ([`Stmt::WriteAll`]). ReadAll, + /// A write without a condition at `ALL`. The encryption-key commands + /// (RFC-0000 section 8.4) write the key ring row, and rewrite and delete + /// the stored secrets, at `ALL`, so every replica holds the new + /// ciphertexts and the new ring before the old key goes. A replica that + /// is down fails the write. + WriteAll, + /// A conditional write (LWT) of the encryption-key commands: Paxos at + /// `LOCAL_SERIAL`, commit at `ALL` ([`Stmt::WriteAll`]). + LwtAll, /// `CREATE`, `ALTER`, `DROP`, `GRANT` or `REVOKE`: `ONE`. Cassandra does /// not use the client's consistency level for these statements. Ddl, @@ -77,8 +87,9 @@ fn levels( match kind { Stmt::Read | Stmt::Write => (Consistency::LocalQuorum, None), Stmt::Lwt => (Consistency::LocalQuorum, Some(Consistency::LocalSerial)), + Stmt::LwtAll => (Consistency::All, Some(Consistency::LocalSerial)), Stmt::SerialRead => (Consistency::LocalSerial, None), - Stmt::ReadAll => (Consistency::All, None), + Stmt::ReadAll | Stmt::WriteAll => (Consistency::All, None), Stmt::Ddl | Stmt::SystemRead => (Consistency::One, None), } } @@ -241,9 +252,10 @@ impl PolicySession for CassandraSession { /// - [`Stmt::Read`], [`Stmt::SerialRead`] and [`Stmt::ReadAll`]: a `SELECT` that does not read /// `system.*` or `system_schema.*`. /// - [`Stmt::SystemRead`]: a `SELECT` from `system.*` or `system_schema.*`. -/// - [`Stmt::Write`]: an `INSERT`, `UPDATE`, `DELETE` or `BEGIN BATCH` with -/// no `IF` condition. -/// - [`Stmt::Lwt`]: an `INSERT`, `UPDATE` or `DELETE` with an `IF` condition. +/// - [`Stmt::Write`] and [`Stmt::WriteAll`]: an `INSERT`, `UPDATE`, `DELETE` +/// or `BEGIN BATCH` with no `IF` condition. +/// - [`Stmt::Lwt`] and [`Stmt::LwtAll`]: an `INSERT`, `UPDATE` or `DELETE` +/// with an `IF` condition. /// - [`Stmt::Ddl`]: a `CREATE`, `ALTER`, `DROP`, `GRANT` or `REVOKE`. /// /// Quoted literals and identifiers are removed before the check, so an `IF` @@ -278,16 +290,16 @@ pub fn shape_error(kind: Stmt, query: &str) -> Option<&'static str> { Some("a system read must read system.* or system_schema.*") } } - Stmt::Write => { + Stmt::Write | Stmt::WriteAll => { if !matches!(first, "INSERT" | "UPDATE" | "DELETE" | "BEGIN") { Some("a write must be an INSERT, UPDATE, DELETE or BEGIN BATCH") } else if conditional { - Some("a write with an IF condition must use Stmt::Lwt") + Some("a write with an IF condition must use Stmt::Lwt or Stmt::LwtAll") } else { None } } - Stmt::Lwt => { + Stmt::Lwt | Stmt::LwtAll => { if !matches!(first, "INSERT" | "UPDATE" | "DELETE") { Some("an LWT must be an INSERT, UPDATE or DELETE") } else if conditional { @@ -391,7 +403,11 @@ pub async fn system_read( } /// Run `query` with `values` as a statement of `kind` and return its rows. -async fn rows_at( +/// The error keeps the driver's message. +/// +/// # Errors +/// Returns an error if the Cassandra query fails or the response cannot be parsed. +pub(crate) async fn rows_at( session: &Arc, query: &str, kind: Stmt, @@ -531,6 +547,29 @@ pub async fn execute( Ok(()) } +/// Execute a non-query statement of `kind`, at the level [`params`] gives +/// that kind. Unlike [`execute`], the error keeps the driver's message. +/// +/// Name the kind for writes that are prerequisites for a later read at that +/// level, or whose loss would make an absence decision unsafe. +/// +/// # Errors +/// Returns an error if Cassandra does not acknowledge the statement at the +/// level of `kind`. +pub(crate) async fn execute_at( + session: &Arc, + query: &str, + values: QueryValues, + kind: Stmt, + context: &str, +) -> Result<(), E> { + session.run(kind, query, values).await.map_err(|error| { + tracing::error!("{context} {kind:?} execute failed: {error}"); + E::db_error(format!("{context}: {error}")) + })?; + Ok(()) +} + // ══════════════════════════════════════════════════════════════════════════════ // Type Conversion Helpers // ══════════════════════════════════════════════════════════════════════════════ @@ -674,7 +713,24 @@ pub async fn apply_lwt( values: QueryValues, context: &str, ) -> Result { - let result = session.run(Stmt::Lwt, query, values).await.map_err(|e| { + apply_lwt_at(session, query, values, Stmt::Lwt, context).await +} + +/// [`apply_lwt`] as a statement of `kind`: [`Stmt::Lwt`], or +/// [`Stmt::LwtAll`] for the commit phase at `ALL`. The serial phase runs at +/// `LOCAL_SERIAL` for both. +/// +/// # Errors +/// Returns an error if Cassandra does not acknowledge the statement at the +/// level of `kind` or the response cannot be parsed. +pub(crate) async fn apply_lwt_at( + session: &Arc, + query: &str, + values: QueryValues, + kind: Stmt, + context: &str, +) -> Result { + let result = session.run(kind, query, values).await.map_err(|e| { tracing::error!("{context} lwt failed: {e}"); E::db_error("Database error".to_owned()) })?; @@ -880,8 +936,23 @@ mod tests { } #[test] - fn a_read_all_runs_at_all() { + fn the_all_kinds_run_at_all() { assert_eq!(levels(Stmt::ReadAll), (Consistency::All, None)); + assert_eq!(levels(Stmt::WriteAll), (Consistency::All, None)); + assert_eq!( + levels(Stmt::LwtAll), + (Consistency::All, Some(Consistency::LocalSerial)) + ); + } + + #[test] + fn a_write_all_has_no_condition_and_an_lwt_all_has_one() { + let plain = "UPDATE ks.t SET a = ? WHERE pk = ?"; + let conditional = "UPDATE ks.t SET a = ? WHERE pk = ? IF a = ?"; + assert_eq!(shape_error(Stmt::WriteAll, plain), None); + assert!(shape_error(Stmt::WriteAll, conditional).is_some()); + assert_eq!(shape_error(Stmt::LwtAll, conditional), None); + assert!(shape_error(Stmt::LwtAll, plain).is_some()); } #[test] @@ -940,7 +1011,13 @@ mod tests { ] { assert!(kind.is_read(), "{kind:?}"); } - for kind in [Stmt::Write, Stmt::Lwt, Stmt::Ddl] { + for kind in [ + Stmt::Write, + Stmt::Lwt, + Stmt::WriteAll, + Stmt::LwtAll, + Stmt::Ddl, + ] { assert!(!kind.is_read(), "{kind:?}"); } } diff --git a/crates/storage-cassandra/src/catalog_store.rs b/crates/storage-cassandra/src/catalog_store.rs index 542e6a26d..bf5cfcd74 100644 --- a/crates/storage-cassandra/src/catalog_store.rs +++ b/crates/storage-cassandra/src/catalog_store.rs @@ -18,8 +18,11 @@ use cdrs_tokio::query_values; use cdrs_tokio::transport::TransportTcp; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::management_store::{OpError, OpResult}; +use extenddb_storage::secret_keys::SecretKeys; use futures::future::BoxFuture; +use crate::management_store::secrets::{key_row_at_all, key_row_at_all_failed}; + type CassandraSession = Session< TransportTcp, TcpConnectionManager, @@ -45,12 +48,16 @@ pub struct CassandraCatalogStore { replication: Option, /// The release recorded in the ledger rows of a new account keyspace. release: String, - /// Cached encryption key (immutable after bootstrap). Avoids - /// per-request DB query on access key and assume-role operations. - encryption_key: Option>, + /// The key holder that encrypts the stored secrets, shared with the + /// credential store; `None` for a store opened without a key, which + /// writes no credential. + keys: Option>, /// TTL in seconds applied to every metrics row on insert. /// Cassandra expires rows natively; `prune_metrics` is a no-op. metrics_ttl_seconds: i32, + /// Read the key rows at `ALL`, as a store opened for the encryption-key + /// commands does ([`Self::reading_key_rows_at_all`]). + key_rows_at_all: bool, /// The crash-and-rerun tests' request budget, shared with the migration /// backend, which fails a policy write once it is spent. #[cfg(any(test, feature = "test-util"))] @@ -71,8 +78,9 @@ impl CassandraCatalogStore { keyspace_prefix, replication: Some(network_topology(&datacenter, replication_factor)), release: env!("CARGO_PKG_VERSION").to_owned(), - encryption_key: None, + keys: None, metrics_ttl_seconds: 86400, + key_rows_at_all: false, #[cfg(any(test, feature = "test-util"))] stop_after: None, } @@ -89,13 +97,24 @@ impl CassandraCatalogStore { keyspace_prefix, replication: None, release: env!("CARGO_PKG_VERSION").to_owned(), - encryption_key: None, + keys: None, metrics_ttl_seconds: 86400, + key_rows_at_all: false, #[cfg(any(test, feature = "test-util"))] stop_after: None, } } + /// Read the key rows (the key ring, the catalog key and `catalog_id`) + /// at `ALL`, as the encryption-key commands do: the stores of the + /// migration lock and the stores opened from a connection string. + /// The server's store reads them at `LOCAL_QUORUM` at startup. + #[must_use] + pub(crate) fn reading_key_rows_at_all(mut self) -> Self { + self.key_rows_at_all = true; + self + } + /// Share the crash-and-rerun tests' request budget: each policy write /// takes one request, and fails once the budget is spent. #[cfg(any(test, feature = "test-util"))] @@ -136,25 +155,12 @@ impl CassandraCatalogStore { self } - /// Create a new catalog store with a pre-loaded encryption key. + /// Hold the key holder the factory loaded, shared with the credential + /// store. Without one the store writes no credential. #[must_use] - pub fn with_encryption_key( - session: Arc, - keyspace_prefix: String, - datacenter: String, - replication_factor: u32, - encryption_key: String, - ) -> Self { - Self { - session, - keyspace_prefix, - replication: Some(network_topology(&datacenter, replication_factor)), - release: env!("CARGO_PKG_VERSION").to_owned(), - encryption_key: Some(Arc::from(encryption_key.as_str())), - metrics_ttl_seconds: 86400, - #[cfg(any(test, feature = "test-util"))] - stop_after: None, - } + pub fn with_secret_keys(mut self, keys: Option>) -> Self { + self.keys = keys; + self } /// Borrow the underlying session (escape hatch for callers not yet migrated). @@ -163,12 +169,6 @@ impl CassandraCatalogStore { &self.session } - /// Get the cached encryption key. Returns `None` if not loaded at startup. - #[must_use] - pub fn encryption_key(&self) -> Option<&Arc> { - self.encryption_key.as_ref() - } - /// Get the catalog keyspace name. pub(crate) fn catalog_keyspace(&self) -> String { format!("{}_catalog", self.keyspace_prefix) @@ -307,16 +307,27 @@ impl extenddb_storage::management_store::SettingsStore for CassandraCatalogStore let key = key.to_string(); let session = self.session.clone(); let catalog_keyspace = self.catalog_keyspace(); + let at_all = key_row_at_all(&key, false, self.key_rows_at_all); Box::pin(async move { let query = format!("SELECT value FROM {catalog_keyspace}.settings WHERE key = ?"); + let values = query_values!(key.as_str()); - let row = crate::cassandra_util::query_optional( - &session, - &query, - query_values!(key.as_str()), - "get_setting", - ) - .await?; + let row = if at_all { + let rows: Vec = + crate::cassandra_util::rows_at::( + &session, + &query, + Stmt::ReadAll, + values, + "get_setting", + ) + .await + .map_err(|e| key_row_at_all_failed("get_setting", &key, e.message()))?; + rows.into_iter().next() + } else { + crate::cassandra_util::query_optional(&session, &query, values, "get_setting") + .await? + }; if let Some(row) = row { let value: String = @@ -333,20 +344,38 @@ impl extenddb_storage::management_store::SettingsStore for CassandraCatalogStore let value = value.to_string(); let session = self.session.clone(); let catalog_keyspace = self.catalog_keyspace(); + let at_all = key_row_at_all(&key, true, self.key_rows_at_all); Box::pin(async move { let query = format!("INSERT INTO {catalog_keyspace}.settings (key, value) VALUES (?, ?)"); + let values = query_values!(key.as_str(), value.as_str()); - crate::cassandra_util::execute( - &session, - &query, - query_values!(key.as_str(), value.as_str()), - "set_setting", - ) - .await + if at_all { + crate::cassandra_util::execute_at::( + &session, + &query, + values, + Stmt::WriteAll, + "set_setting", + ) + .await + .map_err(|e| key_row_at_all_failed("set_setting", &key, e.message())) + } else { + crate::cassandra_util::execute(&session, &query, values, "set_setting").await + } }) } + fn replace_setting( + &self, + key: &str, + expected: &str, + value: &str, + ) -> BoxFuture<'_, OpResult> { + let (key, expected, value) = (key.to_owned(), expected.to_owned(), value.to_owned()); + Box::pin(async move { self.replace_setting_impl(&key, &expected, &value).await }) + } + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { let session = self.session.clone(); let catalog_keyspace = self.catalog_keyspace(); @@ -378,12 +407,6 @@ impl extenddb_storage::management_store::SettingsStore for CassandraCatalogStore Ok(settings) }) } - - fn cached_encryption_key(&self) -> Option { - self.encryption_key - .as_ref() - .map(std::string::ToString::to_string) - } } // ── DiagnosticsStore ─────────────────────────────────────────────────── @@ -457,6 +480,7 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for CassandraCatalogStore { fn test_data_database_connection( &self, + _key: &extenddb_storage::server_components::KeySource, ) -> BoxFuture<'_, extenddb_storage::diagnostics::DiagResult> { let session = self.session.clone(); let catalog_keyspace = self.catalog_keyspace(); @@ -811,9 +835,7 @@ impl MetricsStore for CassandraCatalogStore { } impl extenddb_storage::CatalogStore for CassandraCatalogStore { - fn cached_encryption_key(&self) -> Option { - self.encryption_key - .as_ref() - .map(std::string::ToString::to_string) + fn secret_keys(&self) -> Option<&SecretKeys> { + self.keys.as_deref() } } diff --git a/crates/storage-cassandra/src/credential_store.rs b/crates/storage-cassandra/src/credential_store.rs index 5468f844d..8314c2f4d 100644 --- a/crates/storage-cassandra/src/credential_store.rs +++ b/crates/storage-cassandra/src/credential_store.rs @@ -4,8 +4,9 @@ //! Database-backed credential store for SigV4 authentication. //! //! Implements `extenddb_auth::CredentialStore` by looking up access keys and -//! session credentials from Cassandra, decrypting secrets with AES-256-GCM -//! through `extenddb_storage::secret_cipher`, with the access key id as the AAD. +//! session credentials from Cassandra, decrypting secrets through the key +//! holder (`extenddb_storage::secret_keys`), which binds each secret to the +//! fields of its row. use crate::cassandra_util::PolicySession as _; use crate::cassandra_util::Stmt; @@ -19,8 +20,7 @@ use cdrs_tokio::transport::TransportTcp; use cdrs_tokio::types::IntoRustByName; use extenddb_auth::{CredentialStore, StoredCredential}; use extenddb_core::error::DynamoDbError; -use extenddb_storage::secret_cipher::decrypt_secret; -use zeroize::{Zeroize, ZeroizeOnDrop}; +use extenddb_storage::secret_keys::{SecretKeys, SecretRow, require_keys}; type CassandraSession = Session< TransportTcp, @@ -28,25 +28,24 @@ type CassandraSession = Session< RoundRobinLoadBalancingStrategy, >; -#[derive(Zeroize, ZeroizeOnDrop)] pub struct CassandraCredentialStore { - #[zeroize(skip)] session: Arc, - #[zeroize(skip)] keyspace_prefix: String, - encryption_key: String, + /// The key holder, shared with the catalog store; `None` for a store + /// opened without a key, which opens no stored secret. + keys: Option>, } impl CassandraCredentialStore { pub fn new( session: Arc, keyspace_prefix: String, - encryption_key: String, + keys: Option>, ) -> Self { Self { session, keyspace_prefix, - encryption_key, + keys, } } @@ -54,6 +53,14 @@ impl CassandraCredentialStore { format!("{}_catalog", self.keyspace_prefix) } + /// The key holder, or the refusal of a store opened without one. + fn keys(&self) -> Result<&SecretKeys, DynamoDbError> { + require_keys(self.keys.as_deref()).map_err(|e| { + tracing::error!("Credential lookup: {e:?}"); + DynamoDbError::InternalServerError("Internal error during authentication".to_owned()) + }) + } + /// Whether `account_id` has a row in `accounts`. Before account deletes /// removed them, a deleted account's access keys and role sessions stayed /// in the catalog; a credential of an account that no longer exists is @@ -150,8 +157,13 @@ impl CassandraCredentialStore { return Ok(None); } - let secret_key = - decrypt_secret(&encrypted, &self.encryption_key, access_key_id).map_err(|e| { + let mut secret_key = self + .keys()? + .decrypt( + &SecretRow::access_key(access_key_id, &account_id, &user_name), + &encrypted, + ) + .map_err(|e| { tracing::error!("Secret key decryption failed for access key {access_key_id}: {e}"); DynamoDbError::InternalServerError( "Internal error during authentication".to_owned(), @@ -159,7 +171,9 @@ impl CassandraCredentialStore { })?; Ok(Some(StoredCredential { - secret_key, + // Moved out, not copied: the plaintext has one allocation, wiped + // when the credential drops. + secret_key: std::mem::take(&mut *secret_key), account_id, principal_name: user_name, session_name: None, @@ -252,8 +266,19 @@ impl CassandraCredentialStore { )); } - let secret_key = - decrypt_secret(&encrypted, &self.encryption_key, access_key_id).map_err(|e| { + let mut secret_key = self + .keys()? + .decrypt( + &SecretRow::session( + access_key_id, + &account_id, + &role_name, + &session_name, + expires_at.unix_timestamp(), + ), + &encrypted, + ) + .map_err(|e| { tracing::error!( "Session secret key decryption failed for access key {access_key_id}: {e}" ); @@ -263,7 +288,9 @@ impl CassandraCredentialStore { })?; Ok(Some(StoredCredential { - secret_key, + // Moved out, not copied: the plaintext has one allocation, wiped + // when the credential drops. + secret_key: std::mem::take(&mut *secret_key), account_id, principal_name: role_name, session_name: Some(session_name), diff --git a/crates/storage-cassandra/src/lib.rs b/crates/storage-cassandra/src/lib.rs index db416494b..5d2c81b46 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -58,14 +58,12 @@ pub use backup_catalog::heartbeat_backup_row; pub use bootstrapper::CassandraBootstrapper; pub use catalog_store::CassandraCatalogStore; pub use config::CassandraStorageConfig; +pub use credential_store::CassandraCredentialStore; pub use engine::{CassandraEngine, CassandraSession}; pub use metadata_engine::TtlBackfillCursor; -use crate::cassandra_util::PolicySession as _; -use crate::cassandra_util::Stmt; -use cdrs_tokio::types::IntoRustByName; use extenddb_storage::hooks::{ServerRuntimeHooks, ServingRegistrar, WorkerContext}; -use extenddb_storage::server_components::{BackendError, ServerComponents}; +use extenddb_storage::server_components::{BackendError, ServerComponents, load_secret_keys}; use std::sync::Arc; // ============================================================================ @@ -287,10 +285,10 @@ async fn make_catalog_store_from_connection_string( ) .map_err(|e| e.to_string())?; let session = deployment.connect().await.map_err(|e| e.to_string())?; - Ok(CassandraCatalogStore::catalog_only( - session, - deployment.keyspace_prefix, - )) + Ok( + CassandraCatalogStore::catalog_only(session, deployment.keyspace_prefix) + .reading_key_rows_at_all(), + ) } /// The warnings for the deployment's keyspaces whose replication differs @@ -394,7 +392,7 @@ fn server_components_factory( region: &str, // `bootstrap_if_uninitialized` is not honored: an uninitialized catalog // fails with the explicit-`init` guidance, as on PostgreSQL. - options: extenddb_storage::server_components::ServerComponentsOptions, + mut options: extenddb_storage::server_components::ServerComponentsOptions, ) -> std::pin::Pin< Box> + Send>, > { @@ -471,45 +469,26 @@ fn server_components_factory( } } - // Load encryption key from catalog. - let catalog_keyspace = format!("{}_catalog", cassandra_config.keyspace_prefix); - let enc_key_query = - format!("SELECT value FROM {catalog_keyspace}.settings WHERE key = 'encryption_key'"); - let enc_key_result = engine - .session - .run( - Stmt::Read, - &enc_key_query, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ) - .await - .map_err(|e| { - BackendError::InitializationFailed(format!("Failed to load encryption key: {e}")) - })?; - let enc_key_body = enc_key_result.response_body().map_err(|e| { - BackendError::InitializationFailed(format!( - "Failed to parse encryption key response: {e}" - )) - })?; - let enc_key_rows = enc_key_body - .into_rows() - .ok_or(BackendError::MissingEncryptionKey)?; - let enc_key_row = enc_key_rows - .into_iter() - .next() - .ok_or(BackendError::MissingEncryptionKey)?; - let enc_key: String = enc_key_row.get_r_by_name("value").map_err(|e| { - BackendError::InitializationFailed(format!("Failed to parse encryption key: {e}")) - })?; + // Load the key the stores share (RFC-0000 section 7): the catalog + // key, or the DEK of the key ring unwrapped with the KEK `serve` + // read. The refusals of section 7's table come from the loader. + let keys = load_secret_keys( + &CassandraCatalogStore::catalog_only( + engine.session.clone(), + cassandra_config.keyspace_prefix.clone(), + ), + std::mem::take(&mut options.key_source), + ) + .await?; let catalog_store = Arc::new( - CassandraCatalogStore::with_encryption_key( + CassandraCatalogStore::new( engine.session.clone(), cassandra_config.keyspace_prefix.clone(), cassandra_config.datacenter.clone(), cassandra_config.replication_factor, - enc_key.clone(), ) + .with_secret_keys(keys.clone()) .recording_release(options.release), ); @@ -517,7 +496,7 @@ fn server_components_factory( Arc::new(credential_store::CassandraCredentialStore::new( engine.session.clone(), cassandra_config.keyspace_prefix.clone(), - enc_key, + keys, )); let runtime_hooks = Box::new(CassandraRuntimeHooks { diff --git a/crates/storage-cassandra/src/management_store/access_keys.rs b/crates/storage-cassandra/src/management_store/access_keys.rs index 1f2fc29f3..563f29942 100755 --- a/crates/storage-cassandra/src/management_store/access_keys.rs +++ b/crates/storage-cassandra/src/management_store/access_keys.rs @@ -8,8 +8,9 @@ use crate::cassandra_util::Stmt; use crate::catalog_store::CassandraCatalogStore; use cdrs_tokio::types::IntoRustByName; use cdrs_tokio::types::blob::Blob; +use extenddb_storage::CatalogStore; use extenddb_storage::management_store::{AccessKeyCreated, OpError, OpResult}; -use extenddb_storage::secret_cipher::encrypt_secret; +use extenddb_storage::secret_keys::{SecretRow, require_keys}; impl CassandraCatalogStore { // ── Access keys ──────────────────────────────────────────────── @@ -24,33 +25,18 @@ impl CassandraCatalogStore { return Err(OpError::NotFound("User not found".to_owned())); } - // P119: Use cached encryption key if available, fall back to DB query. - let enc_key: String = if let Some(cached) = self.encryption_key() { - cached.to_string() - } else { - let catalog_keyspace = self.catalog_keyspace(); - let query = format!( - "SELECT value FROM {catalog_keyspace}.settings WHERE key = 'encryption_key'" - ); - - let row = crate::cassandra_util::query_optional( - self.session(), - &query, - cdrs_tokio::query_values!(), - "create_access_key", - ) - .await? - .ok_or_else(|| OpError::Internal("Encryption key not configured".to_owned()))?; - - crate::cassandra_util::get_column(&row, "value", "create_access_key")? - }; - + let keys = require_keys(self.secret_keys())?; let access_key_id = generate_access_key_id(); let secret_key = generate_secret_key(); - let encrypted = encrypt_secret(&secret_key, &enc_key, &access_key_id).map_err(|e| { - tracing::error!("create_access_key encryption: {e}"); - OpError::Internal("Database error".to_owned()) - })?; + let encrypted = keys + .encrypt( + &SecretRow::access_key(&access_key_id, account_id, user_name), + &secret_key, + ) + .map_err(|e| { + tracing::error!("create_access_key encryption: {e}"); + OpError::Internal("Database error".to_owned()) + })?; let catalog_keyspace = self.catalog_keyspace(); let insert_query = format!( @@ -173,29 +159,13 @@ impl CassandraCatalogStore { return Err(OpError::NotFound("IAM user not found".to_owned())); } - // P119: Use cached encryption key if available, fall back to DB query. - let enc_key: String = if let Some(cached) = self.encryption_key() { - cached.to_string() - } else { - let catalog_keyspace = self.catalog_keyspace(); - let query = format!( - "SELECT value FROM {catalog_keyspace}.settings WHERE key = 'encryption_key'" - ); - - let row = crate::cassandra_util::query_optional( - self.session(), - &query, - cdrs_tokio::query_values!(), - "import_access_key", + let keys = require_keys(self.secret_keys())?; + let encrypted = keys + .encrypt( + &SecretRow::access_key(access_key_id, account_id, user_name), + secret_access_key, ) - .await? - .ok_or_else(|| OpError::Internal("Encryption key not configured".to_owned()))?; - - crate::cassandra_util::get_column(&row, "value", "import_access_key")? - }; - - let encrypted = - encrypt_secret(secret_access_key, &enc_key, access_key_id).map_err(|e| { + .map_err(|e| { tracing::error!("import_access_key encryption: {e}"); OpError::Internal("Database error".to_owned()) })?; @@ -252,7 +222,10 @@ impl CassandraCatalogStore { let session_policy_json = session_policy .as_ref() .map(std::string::ToString::to_string); - let expires_ms = expires_at.unix_timestamp() * 1000 + i64::from(expires_at.millisecond()); + // Whole seconds: the AAD of the session secret carries `expires_at` + // in whole Unix seconds, and the stored value must read back as the + // value that was encrypted. + let expires_ms = expires_at.unix_timestamp() * 1000; crate::cassandra_util::execute( self.session(), diff --git a/crates/storage-cassandra/src/management_store/mod.rs b/crates/storage-cassandra/src/management_store/mod.rs index d7ba82dcb..a62f512b2 100755 --- a/crates/storage-cassandra/src/management_store/mod.rs +++ b/crates/storage-cassandra/src/management_store/mod.rs @@ -7,8 +7,10 @@ //! file under the 500-line limit. use extenddb_storage::management_store::{ - AccessKeyCreated, AccountDetail, GroupDetail, OpResult, RoleDetail, StoredDocument, UserDetail, + AccessKeyCreated, AccountDetail, GroupDetail, OpResult, RoleDetail, SecretPage, SecretWrite, + StoredDocument, UserDetail, }; +use extenddb_storage::secret_keys::SecretTable; use futures::future::BoxFuture; use super::catalog_store::CassandraCatalogStore; @@ -19,6 +21,7 @@ mod dependents; mod groups; mod policies; mod roles; +pub(crate) mod secrets; mod users; impl extenddb_storage::management_store::ManagementStore for CassandraCatalogStore { @@ -643,4 +646,38 @@ impl extenddb_storage::management_store::ManagementStore for CassandraCatalogSto let resource = resource.to_string(); Box::pin(async move { self.fetch_caller_tags_impl(&account_id, &resource).await }) } + + // ── Encryption-key commands (RFC-0000 section 8.4) ───────────── + + fn read_secret_page( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> BoxFuture<'_, OpResult> { + let page = page.map(str::to_owned); + Box::pin(async move { + self.read_secret_page_impl(table, page.as_deref(), page_size) + .await + }) + } + + fn write_secrets( + &self, + table: SecretTable, + rows: &[SecretWrite], + ) -> BoxFuture<'_, OpResult<()>> { + let rows = rows.to_vec(); + Box::pin(async move { self.write_secrets_impl(table, &rows).await }) + } + + fn delete_secrets(&self, table: SecretTable, keys: &[String]) -> BoxFuture<'_, OpResult<()>> { + let keys = keys.to_vec(); + Box::pin(async move { self.delete_secrets_impl(table, &keys).await }) + } + + fn delete_setting(&self, key: &str) -> BoxFuture<'_, OpResult<()>> { + let key = key.to_string(); + Box::pin(async move { self.delete_setting_impl(&key).await }) + } } diff --git a/crates/storage-cassandra/src/management_store/secrets.rs b/crates/storage-cassandra/src/management_store/secrets.rs new file mode 100644 index 000000000..fec93ac5b --- /dev/null +++ b/crates/storage-cassandra/src/management_store/secrets.rs @@ -0,0 +1,495 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The stored-secret rows as the encryption-key commands read and write them +//! (RFC-0000 section 8.4), for `CassandraCatalogStore`. +//! +//! Every statement of the pass runs at `ALL`, and so does every write of the +//! key ring row and every read of the key rows from the commands' stores +//! ([`key_row_at_all`]), so every replica holds the new ciphertexts and the +//! new ring before the old key goes. Each page selects +//! `WRITETIME(secret_key_encrypted)`, and each write sets `USING TIMESTAMP` +//! above that value: CreateAccessKey and ImportAccessKey write with +//! `INSERT ... IF NOT EXISTS`, whose Paxos timestamp can be ahead of a later +//! plain update's clock, and Cassandra keeps the older value of an update +//! whose timestamp is not above the row's. Each delete reads the write time +//! of every non-key column of the row and stamps its tombstone at the +//! largest, or at this host's clock when that is later, because a tombstone +//! below a cell's timestamp leaves the cell in place. The writes +//! carry no condition, because a conditional update takes no timestamp of its +//! own. An update of a key that no row holds therefore writes a row with the +//! ciphertext alone; the pass writes only keys it read under the migration +//! lock, which keeps every server out, and session rows have no TTL here. + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as BASE64; +use cdrs_tokio::query::QueryValues; +use cdrs_tokio::types::IntoRustByIndex; +use cdrs_tokio::types::IntoRustByName; +use cdrs_tokio::types::blob::Blob; +use cdrs_tokio::types::rows::Row; +use extenddb_storage::key_ring::KEY_RING_SETTING; +use extenddb_storage::management_store::{ + OpError, OpResult, SecretPage, SecretWrite, StoredSecretRow, +}; +use extenddb_storage::secret_keys::{CATALOG_ID_SETTING, CATALOG_KEY_SETTING, SecretTable}; + +use crate::cassandra_util::{ + PolicySession as _, Stmt, execute_at, get_column, timestamp_to_datetime, +}; +use crate::catalog_store::CassandraCatalogStore; + +/// The settings rows that the encryption-key commands read before they +/// write: the key ring, the catalog key and `catalog_id`. +const KEY_ROWS: [&str; 3] = [KEY_RING_SETTING, CATALOG_KEY_SETTING, CATALOG_ID_SETTING]; + +/// Whether a statement on the settings row `key` runs at `ALL`. Every write +/// of the key ring does, from every store: the ring row is the one stored +/// copy of the wrapped DEK. A read of a key row does from a store opened for +/// the commands (`commands`), so a command run again after a ring write that +/// reached only some replicas reads the newest ring. Every other settings +/// statement, and the server's read of the key rows at startup, runs at +/// `LOCAL_QUORUM` ([`Stmt::Read`], [`Stmt::Write`]). +pub(crate) fn key_row_at_all(key: &str, write: bool, commands: bool) -> bool { + if write { + key == KEY_RING_SETTING + } else { + commands && KEY_ROWS.contains(&key) + } +} + +/// The error of a statement on the key row `key` at `ALL`, which fails +/// while any replica of the catalog keyspace does not answer. `cause` is the +/// driver's error, or where to find it. +pub(crate) fn key_row_at_all_failed(what: &str, key: &str, cause: &str) -> OpError { + OpError::Internal(format!( + "{what} of the {key} row at consistency ALL failed: {cause}. The encryption-key \ + commands read and write the key rows at ALL, so every replica of the catalog \ + keyspace must answer; check the nodes with `nodetool status`" + )) +} + +impl CassandraCatalogStore { + pub(crate) async fn read_secret_page_impl( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> OpResult { + use cdrs_tokio::frame::message_result::RowsMetadataFlags; + const WHAT: &str = "read_secret_page"; + let columns = match table { + SecretTable::AccessKeys => "access_key_id, account_id, user_name", + SecretTable::IamSessions => { + "session_token, access_key_id, account_id, role_name, session_name, expires_at" + } + }; + let query = format!( + "SELECT {columns}, created_at, secret_key_encrypted, \ + WRITETIME(secret_key_encrypted) AS write_time FROM {}.{}", + self.catalog_keyspace(), + table.name() + ); + let paging_state = page + .map(|page| { + BASE64 + .decode(page) + .map(cdrs_tokio::types::CBytes::new) + .map_err(|e| { + OpError::Internal(format!("{WHAT}: the page token does not decode: {e}")) + }) + }) + .transpose()?; + let failed = |e: &dyn std::fmt::Display| { + tracing::error!("{WHAT} query at ALL failed: {e}"); + OpError::Internal(format!("{WHAT}: {e}")) + }; + let body = self + .session() + .run_paged( + Stmt::ReadAll, + &query, + QueryValues::SimpleValues(vec![]), + i32::try_from(page_size).unwrap_or(i32::MAX), + paging_state, + ) + .await + .map_err(|e| failed(&e))? + .response_body() + .map_err(|e| failed(&e))?; + let next = body + .as_rows_metadata() + .filter(|metadata| metadata.flags.contains(RowsMetadataFlags::HAS_MORE_PAGES)) + .and_then(|metadata| metadata.paging_state.clone()) + .and_then(cdrs_tokio::types::CBytes::into_bytes) + .map(|state| BASE64.encode(state)); + let rows = body + .into_rows() + .unwrap_or_default() + .iter() + .map(|row| Self::stored_secret_row(table, row)) + .collect::>>()?; + Ok(SecretPage { rows, next }) + } + + /// One row of a page: the row's primary key, its AAD fields, its + /// ciphertext and the write time of the ciphertext. + fn stored_secret_row(table: SecretTable, row: &Row) -> OpResult { + const WHAT: &str = "read_secret_page"; + let optional = |column: &str| -> OpResult> { + row.get_by_name(column).map_err(|e| { + tracing::error!("{WHAT} parse column '{column}': {e}"); + OpError::Internal("Database error".to_owned()) + }) + }; + let access_key_id: String = get_column(row, "access_key_id", WHAT)?; + let account_id = get_column(row, "account_id", WHAT)?; + let (key, principal_name, session_name, expires_at) = match table { + SecretTable::AccessKeys => ( + access_key_id.clone(), + get_column(row, "user_name", WHAT)?, + None, + None, + ), + SecretTable::IamSessions => ( + get_column(row, "session_token", WHAT)?, + get_column(row, "role_name", WHAT)?, + Some(get_column(row, "session_name", WHAT)?), + optional("expires_at")? + .map(|millis| timestamp_to_datetime(millis, WHAT)) + .transpose()? + .map(|expires| expires.unix_timestamp()), + ), + }; + let created_at = optional("created_at")? + .map(|millis| timestamp_to_datetime(millis, WHAT)) + .transpose()?; + let secret_key_encrypted: Blob = get_column(row, "secret_key_encrypted", WHAT)?; + Ok(StoredSecretRow { + table, + key, + access_key_id, + account_id, + principal_name, + session_name, + expires_at, + created_at, + secret_key_encrypted: secret_key_encrypted.into_vec(), + write_timestamp: optional("write_time")?, + }) + } + + pub(crate) async fn write_secrets_impl( + &self, + table: SecretTable, + rows: &[SecretWrite], + ) -> OpResult<()> { + let query = format!( + "UPDATE {}.{} USING TIMESTAMP ? SET secret_key_encrypted = ? WHERE {} = ?", + self.catalog_keyspace(), + table.name(), + table.key_column() + ); + // Above the row's write time, and never behind the clock: a later + // plain write of the row keeps winning by time. + let now = crate::data::version::now_micros(); + let values = rows + .iter() + .map(|row| { + let stamp = row + .write_timestamp + .map_or(now, |written| now.max(written.saturating_add(1))); + cdrs_tokio::query_values!( + stamp, + Blob::new(row.secret_key_encrypted.clone()), + row.key.as_str() + ) + }) + .collect(); + self.execute_each_at_all(&query, values, "write_secrets") + .await + } + + pub(crate) async fn delete_secrets_impl( + &self, + table: SecretTable, + keys: &[String], + ) -> OpResult<()> { + // Each delete stamps itself at the row's own write time when that is + // ahead of this host's clock, and never further ahead than it must: + // a tombstone far in the future would also suppress a later import + // of the same access key ID, which is how section 11 recovers one. + // The read runs in the same stream as the delete it stamps, so a + // page of a thousand keys takes the rounds the deletes alone took + // and stays inside the store's request bound. + let columns = Self::write_time_columns(table); + let read = format!( + "SELECT {} FROM {}.{} WHERE {} = ?", + Self::write_time_selection(columns), + self.catalog_keyspace(), + table.name(), + table.key_column() + ); + let query = format!( + "DELETE FROM {}.{} USING TIMESTAMP ? WHERE {} = ?", + self.catalog_keyspace(), + table.name(), + table.key_column() + ); + self.stamp_and_delete_each(&read, &query, columns.len(), keys, "delete_secrets") + .await + } + + /// The non-key columns whose write time a row tombstone must cover: a + /// primary key column has no write time of its own in Cassandra, and a + /// tombstone below any remaining cell's timestamp leaves the row with + /// that cell and null key columns, which `stored_secret_row` then fails + /// to parse. Every non-key column of the table is listed, because a + /// column that one statement writes alone carries that statement's + /// timestamp: `update_session_policy_impl` writes `session_policy` with + /// a plain `UPDATE`, which the coordinator stamps with its own clock. + fn write_time_columns(table: SecretTable) -> &'static [&'static str] { + match table { + SecretTable::AccessKeys => &[ + "account_id", + "user_name", + "secret_key_encrypted", + "is_active", + "created_at", + ], + SecretTable::IamSessions => &[ + "account_id", + "role_name", + "session_name", + "access_key_id", + "secret_key_encrypted", + "session_tags", + "session_policy", + "expires_at", + "created_at", + ], + } + } + + /// `columns` as the select list of a write-time read. The reader takes + /// the values by position ([`Self::max_write_time`]), so none is named. + fn write_time_selection(columns: &[&str]) -> String { + columns + .iter() + .map(|column| format!("WRITETIME({column})")) + .collect::>() + .join(", ") + } + + /// Read the write time of each key in `keys` through `read` and delete + /// its row through `query` stamped at [`Self::tombstone_at`], a few keys + /// at a time. `count` is the number of write times `read` selects. + async fn stamp_and_delete_each( + &self, + read: &str, + query: &str, + count: usize, + keys: &[String], + context: &str, + ) -> OpResult<()> { + Self::each_at_all(keys.iter().cloned(), |key: String| async move { + let written = self.max_write_time(read, &key, count, context).await?; + execute_at( + self.session(), + query, + cdrs_tokio::query_values!(Self::tombstone_at(written), key.as_str()), + Stmt::WriteAll, + context, + ) + .await + }) + .await + } + + /// The largest of the `count` write times that `read` selects for the + /// row `key` names, read at `ALL`, or `None` when the row is gone or + /// holds no written cell. + async fn max_write_time( + &self, + read: &str, + key: &str, + count: usize, + context: &str, + ) -> OpResult> { + let rows: Vec = crate::cassandra_util::rows_at( + self.session(), + read, + Stmt::ReadAll, + cdrs_tokio::query_values!(key), + context, + ) + .await?; + let Some(row) = rows.first() else { + return Ok(None); + }; + let mut largest = None; + for index in 0..count { + let written: Option = row.get_by_index(index).map_err(|e| { + tracing::error!("{context} parse write time {index}: {e}"); + OpError::Internal("Database error".to_owned()) + })?; + largest = largest.max(written); + } + Ok(largest) + } + + /// The timestamp of a tombstone over a cell written at `written`: this + /// host's clock, or the cell's own write time when that is ahead of it. + /// A tombstone wins a tie, so the cell's own time is enough. + fn tombstone_at(written: Option) -> i64 { + let now = crate::data::version::now_micros(); + written.map_or(now, |written| now.max(written)) + } + + /// Run `query` once per element of `values` at `ALL`, a few at a time, + /// as a restore's writes run, so a page of a thousand rows completes + /// inside the request bound of the migration backend's store, which the + /// offline commands go through. + async fn execute_each_at_all( + &self, + query: &str, + values: Vec, + context: &str, + ) -> OpResult<()> { + Self::each_at_all(values, |values| { + execute_at(self.session(), query, values, Stmt::WriteAll, context) + }) + .await + } + + /// Await `run` over each element of `items`, a few at a time, and return + /// the first error. The concurrency is a restore's write concurrency, so + /// a page of a thousand items completes inside the request bound of the + /// migration backend's store, which the offline commands go through. A + /// per-item read belongs inside `run`, so that it takes the same rounds + /// as the write it belongs to. + async fn each_at_all(items: impl IntoIterator, run: F) -> OpResult<()> + where + F: Fn(T) -> Fut, + Fut: Future>, + { + use futures::StreamExt as _; + let mut statements = futures::stream::iter(items) + .map(run) + .buffer_unordered(crate::backup_engine::RESTORE_WRITE_CONCURRENCY); + while let Some(result) = statements.next().await { + result?; + } + Ok(()) + } + + pub(crate) async fn delete_setting_impl(&self, key: &str) -> OpResult<()> { + let read = format!( + "SELECT WRITETIME(value) FROM {}.settings WHERE key = ?", + self.catalog_keyspace() + ); + let query = format!( + "DELETE FROM {}.settings USING TIMESTAMP ? WHERE key = ?", + self.catalog_keyspace() + ); + self.stamp_and_delete_each(&read, &query, 1, &[key.to_owned()], "delete_setting") + .await + } + + /// `UPDATE ... IF value = ?` with its commit at `ALL` and its serial + /// phase at `LOCAL_SERIAL` ([`Stmt::LwtAll`]), then the row read back at + /// `ALL`, as every write of the key ring runs ([`key_row_at_all`]). A + /// conditional update takes no client timestamp, and a cell stamped above + /// the update's timestamp keeps its value, so an applied update whose row + /// does not hold `value` is an error, as a delete that leaves its row is + /// for the encryption-key commands. + pub(crate) async fn replace_setting_impl( + &self, + key: &str, + expected: &str, + value: &str, + ) -> OpResult { + const WHAT: &str = "replace_setting"; + let keyspace = self.catalog_keyspace(); + let update = format!("UPDATE {keyspace}.settings SET value = ? WHERE key = ? IF value = ?"); + let values = cdrs_tokio::query_values!(value, key, expected); + let session = self.session(); + let applied = crate::cassandra_util::apply_lwt_at::( + session, + &update, + values, + Stmt::LwtAll, + WHAT, + ) + .await + .map_err(|_| key_row_at_all_failed(WHAT, key, "the driver's error is in the log"))?; + if !applied { + return Ok(false); + } + let read = format!("SELECT value FROM {keyspace}.settings WHERE key = ?"); + let rows: Vec = crate::cassandra_util::rows_at::( + session, + &read, + Stmt::ReadAll, + cdrs_tokio::query_values!(key), + WHAT, + ) + .await + .map_err(|e| key_row_at_all_failed(WHAT, key, e.message()))?; + let held: Option = rows + .first() + .map(|row| get_column(row, "value", WHAT)) + .transpose()?; + if held.as_deref() != Some(value) { + return Err(OpError::Internal(format!( + "{WHAT}: the {key} row does not hold the new value after the applied update" + ))); + } + Ok(true) + } +} + +#[cfg(test)] +mod tests { + use super::{key_row_at_all, key_row_at_all_failed}; + + /// The settings statements that run at `ALL`: each write of the key + /// ring, and each read of a key row from the commands' stores. + #[test] + fn the_ring_writes_and_the_commands_key_row_reads_run_at_all() { + // (row, a write, from the commands' stores, at ALL) + for (key, write, commands, all) in [ + ("encryption_key_ring", true, false, true), + ("encryption_key_ring", true, true, true), + ("encryption_key_ring", false, true, true), + ("encryption_key", false, true, true), + ("catalog_id", false, true, true), + ("encryption_key_ring", false, false, false), + ("catalog_id", false, false, false), + ("encryption_key", true, true, false), + ("log_level", false, true, false), + ("log_level", true, true, false), + ] { + assert_eq!( + key_row_at_all(key, write, commands), + all, + "{key}: write {write}, commands {commands}" + ); + } + } + + /// A key row statement at `ALL` that fails names the consistency and + /// the check an operator runs, not only "Database error". + #[test] + fn a_failed_key_row_statement_names_all_and_the_node_check() { + let error = key_row_at_all_failed("get_setting", "encryption_key_ring", "unavailable"); + let message = error.message(); + for part in [ + "get_setting of the encryption_key_ring row at consistency ALL failed: unavailable", + "every replica of the catalog keyspace must answer", + "`nodetool status`", + ] { + assert!(message.contains(part), "{message}"); + } + } +} diff --git a/crates/storage-cassandra/src/migrations/backend.rs b/crates/storage-cassandra/src/migrations/backend.rs index d20916b25..053efd421 100644 --- a/crates/storage-cassandra/src/migrations/backend.rs +++ b/crates/storage-cassandra/src/migrations/backend.rs @@ -20,10 +20,11 @@ use std::sync::Arc; use async_trait::async_trait; use cdrs_tokio::consistency::Consistency; -use extenddb_storage::management_store::ManagementStore; +use extenddb_storage::management_store::{ManagementStore, SettingsStore}; use extenddb_storage::migrations::{ - CatalogTraces, Done, HasManagementStore, LedgerColumns, LedgerRow, Migration, MigrationBackend, - MigrationError, MigrationId, Released, Step, StoreKind, StoreRef, record_rows, + CatalogTraces, Done, HasManagementStore, LedgerColumns, LedgerRow, LockedStores, Migration, + MigrationBackend, MigrationError, MigrationId, Released, Step, StoreKind, StoreRef, + record_rows, }; use super::agreement::{AGREEMENT_TIMEOUT, wait_for_agreement_with}; @@ -62,14 +63,15 @@ fn stopped_by_hook() -> MigrationError { } impl CassandraStores { - fn new( + pub(super) fn new( session: Arc, keyspace_prefix: &str, lease: Option, ) -> Self { Self { management: LeasedManagementStore::new( - CassandraCatalogStore::catalog_only(session.clone(), keyspace_prefix.to_owned()), + CassandraCatalogStore::catalog_only(session.clone(), keyspace_prefix.to_owned()) + .reading_key_rows_at_all(), lease.clone(), ), session, @@ -160,6 +162,19 @@ impl HasManagementStore for CassandraStores { } } +/// The catalog's stores for the encryption-key commands, which open them +/// under the lock they hold as a migration does: every call checks the +/// lease first and is bounded by the request timeout. +impl LockedStores for CassandraStores { + fn management(&self) -> &dyn ManagementStore { + &self.management + } + + fn settings(&self) -> &dyn SettingsStore { + &self.management + } +} + /// The account keyspaces a run works on. #[derive(Debug, Clone, PartialEq, Eq)] enum Accounts { diff --git a/crates/storage-cassandra/src/migrations/commands.rs b/crates/storage-cassandra/src/migrations/commands.rs index f78dc4441..7943b87be 100644 --- a/crates/storage-cassandra/src/migrations/commands.rs +++ b/crates/storage-cassandra/src/migrations/commands.rs @@ -13,11 +13,11 @@ use std::time::Duration; use async_trait::async_trait; use extenddb_storage::migrations::{ - CatalogMigrations, CatalogStatus, HeldLock, LedgerRow, Listed, MigrationError, MigrationId, - RunKind, RunReport, Runner, Target, + CatalogMigrations, CatalogStatus, HeldLock, LedgerRow, Listed, LockedStores, MigrationError, + MigrationId, RunKind, RunReport, Runner, Target, }; -use super::backend::CassandraMigrations; +use super::backend::{CassandraMigrations, CassandraStores}; use super::connect::{Deployment, has_columns}; use super::locks::{LeaseHandle, LeaseTimes, MigrationLock}; use super::registrations::wait_for_no_servers; @@ -192,6 +192,22 @@ impl CatalogMigrations for CassandraCatalogMigrations { Runner::new(&migrations, "").forget(id).await } + /// The catalog keyspace's stores on the lock's session, under its lease. + /// A Cassandra catalog holds no data connection string row, so + /// `data_connection` is not read. + async fn locked_stores( + &self, + lock: &HeldLock, + _data_connection: Option<&str>, + ) -> Result, MigrationError> { + let held = held(lock)?; + Ok(Box::new(CassandraStores::new( + held.lock.session().clone(), + &held.keyspace_prefix, + Some(held.lock.handle()), + ))) + } + async fn release(&self, lock: HeldLock) { if let Ok(held) = held(&lock) { held.lock.release().await; diff --git a/crates/storage-cassandra/src/migrations/guarded.rs b/crates/storage-cassandra/src/migrations/guarded.rs index e83d67a83..886c3a81a 100644 --- a/crates/storage-cassandra/src/migrations/guarded.rs +++ b/crates/storage-cassandra/src/migrations/guarded.rs @@ -20,9 +20,10 @@ use std::time::Duration; use extenddb_storage::management_store::{ AccessKeyCreated, AccountDetail, GroupDetail, GroupListEntry, ManagementStore, OpError, - OpResult, RoleDetail, RoleListEntry, SessionPolicyEntry, StoredDocument, UserDetail, - UserListEntry, + OpResult, RoleDetail, RoleListEntry, SecretPage, SecretWrite, SessionPolicyEntry, + SettingsStore, StoredDocument, UserDetail, UserListEntry, }; +use extenddb_storage::secret_keys::SecretTable; use futures::future::BoxFuture; use super::connect::REQUEST_TIMEOUT; @@ -152,5 +153,21 @@ impl ManagementStore for LeasedManagementStore { fn list_session_policies(&self) -> BoxFuture<'_, OpResult>>; fn update_session_policy(&self, session_token: &str, document: &serde_json::Value) -> BoxFuture<'_, OpResult<()>>; fn fetch_caller_tags(&self, account_id: &str, resource: &str) -> BoxFuture<'_, OpResult>>; + fn read_secret_page(&self, table: SecretTable, page: Option<&str>, page_size: usize) -> BoxFuture<'_, OpResult>; + fn write_secrets(&self, table: SecretTable, rows: &[SecretWrite]) -> BoxFuture<'_, OpResult<()>>; + fn delete_secrets(&self, table: SecretTable, keys: &[String]) -> BoxFuture<'_, OpResult<()>>; + fn delete_setting(&self, key: &str) -> BoxFuture<'_, OpResult<()>>; + } +} + +/// The settings rows under the same lease check and bound: the encryption-key +/// commands read and write the key rows through the stores of the lock they +/// hold (RFC-0000 section 8, common rules). +impl SettingsStore for LeasedManagementStore { + checked! { + fn get_setting(&self, key: &str) -> BoxFuture<'_, OpResult>>; + fn set_setting(&self, key: &str, value: &str) -> BoxFuture<'_, OpResult<()>>; + fn replace_setting(&self, key: &str, expected: &str, value: &str) -> BoxFuture<'_, OpResult>; + fn list_settings(&self) -> BoxFuture<'_, OpResult>>; } } diff --git a/crates/storage-cassandra/tests/common/mod.rs b/crates/storage-cassandra/tests/common/mod.rs index b3f2c164f..f5f028df6 100644 --- a/crates/storage-cassandra/tests/common/mod.rs +++ b/crates/storage-cassandra/tests/common/mod.rs @@ -883,6 +883,17 @@ pub fn create_catalog_store( ) } +/// [`create_catalog_store`] with a new catalog key, for the tests that +/// create access keys or store sessions. +pub fn create_keyed_catalog_store( + engine: &CassandraEngine, + config: &CassandraStorageConfig, +) -> CassandraCatalogStore { + let key = extenddb_storage::bootstrapper::helpers::generate_encryption_key().expect("a key"); + let keys = extenddb_storage::secret_keys::SecretKeys::catalog_key(&key).expect("a key holder"); + create_catalog_store(engine, config).with_secret_keys(Some(Arc::new(keys))) +} + /// Whether the cluster has one node. `system.paxos` is local to each node, /// so a test that reads it needs a cluster of one node. pub async fn is_one_node_cluster(engine: &CassandraEngine) -> bool { diff --git a/crates/storage-cassandra/tests/direct/access_keys.rs b/crates/storage-cassandra/tests/direct/access_keys.rs index 1484411a7..8d1867519 100644 --- a/crates/storage-cassandra/tests/direct/access_keys.rs +++ b/crates/storage-cassandra/tests/direct/access_keys.rs @@ -16,16 +16,7 @@ mod tests { let engine = setup_engine().await; let config = test_config(); - // Need encryption key for access key creation - use extenddb_storage::bootstrapper::helpers::generate_encryption_key; - let enc_key = generate_encryption_key().expect("generate key"); - let catalog_store = extenddb_storage_cassandra::CassandraCatalogStore::with_encryption_key( - engine.session_arc(), - config.keyspace_prefix.clone(), - config.datacenter.clone(), - config.replication_factor, - enc_key, - ); + let catalog_store = crate::helpers::create_keyed_catalog_store(&engine, &config); let account_id = unique_test_account(); let account_name = format!("TestAccount_{}", unique_test_id()); @@ -57,16 +48,7 @@ mod tests { let engine = setup_engine().await; let config = test_config(); - // Need encryption key for session storage - use extenddb_storage::bootstrapper::helpers::generate_encryption_key; - let enc_key = generate_encryption_key().expect("generate key"); - let catalog_store = extenddb_storage_cassandra::CassandraCatalogStore::with_encryption_key( - engine.session_arc(), - config.keyspace_prefix.clone(), - config.datacenter.clone(), - config.replication_factor, - enc_key.clone(), - ); + let catalog_store = crate::helpers::create_keyed_catalog_store(&engine, &config); let account_id = unique_test_account(); let account_name = format!("TestAccount_{}", unique_test_id()); diff --git a/crates/storage-cassandra/tests/direct/consistency_levels.rs b/crates/storage-cassandra/tests/direct/consistency_levels.rs index 5eeb0df03..ffca69042 100644 --- a/crates/storage-cassandra/tests/direct/consistency_levels.rs +++ b/crates/storage-cassandra/tests/direct/consistency_levels.rs @@ -92,16 +92,36 @@ mod tests { keyspace: String, } + /// The replication factor whose quorum is one more than the cluster's + /// node count: 2N + 1 on N nodes. + async fn no_quorum_replicas(session: &Arc) -> usize { + let peers = cassandra_util::system_read::( + session, + "SELECT peer FROM system.peers", + none(), + "count the peers", + ) + .await + .expect("read system.peers"); + 2 * (peers.len() + 1) + 1 + } + + /// The replication map of a keyspace with `replicas` replicas in the + /// test datacenter. + fn replication(replicas: usize) -> String { + let datacenter = crate::helpers::test_config().datacenter; + format!("{{'class': 'NetworkTopologyStrategy', '{datacenter}': {replicas}}}") + } + impl TestKeyspace { /// A keyspace with `replicas` replicas in the test datacenter. async fn with_replicas(replicas: usize) -> Self { let session = session_without_retries().await; let keyspace = format!("consistency_{}", crate::helpers::unique_test_id()); - let datacenter = crate::helpers::test_config().datacenter; for cql in [ format!( - "CREATE KEYSPACE {keyspace} WITH replication = \ - {{'class': 'NetworkTopologyStrategy', '{datacenter}': {replicas}}}" + "CREATE KEYSPACE {keyspace} WITH replication = {}", + replication(replicas) ), format!("CREATE TABLE {keyspace}.t (pk text PRIMARY KEY, v int)"), ] { @@ -115,15 +135,7 @@ mod tests { /// A keyspace whose quorum is one more than the cluster's node count. async fn under_replicated() -> Self { let session = session_without_retries().await; - let peers = cassandra_util::system_read::( - &session, - "SELECT peer FROM system.peers", - none(), - "count the peers", - ) - .await - .expect("read system.peers"); - Self::with_replicas(2 * (peers.len() + 1) + 1).await + Self::with_replicas(no_quorum_replicas(&session).await).await } fn session(&self) -> Arc { @@ -262,6 +274,7 @@ mod tests { for (name, level) in [ ("cl: LocalQuorum", Consistency::LocalQuorum), ("cl: Quorum", Consistency::Quorum), + ("cl: All", Consistency::All), ("cl: One", Consistency::One), ] { if error.contains("Unavailable") && error.contains(name) { @@ -286,6 +299,9 @@ mod tests { (Stmt::SerialRead, keyspace.select("a")), (Stmt::Write, insert.clone()), (Stmt::Lwt, format!("{insert} IF NOT EXISTS")), + // The Paxos round of `LwtAll` runs at `LOCAL_SERIAL` and fails + // before its commit at `ALL`. + (Stmt::LwtAll, format!("{insert} IF NOT EXISTS")), ] { let result = session.run(kind, &cql, none()).await; assert_eq!( @@ -295,7 +311,8 @@ mod tests { ); } - // `ReadAll` needs every replica, so Cassandra names `ALL`. + // `ReadAll` and `WriteAll` need every replica, so Cassandra names + // `ALL`. assert_eq!( unavailable_level( session @@ -305,6 +322,11 @@ mod tests { Consistency::All, "ReadAll" ); + assert_eq!( + unavailable_level(session.run(Stmt::WriteAll, &insert, none()).await), + Consistency::All, + "WriteAll" + ); // A page of a read has the level of its kind. For `SerialRead`, // Cassandra names `LOCAL_QUORUM`, as it does for `run`. @@ -520,4 +542,74 @@ mod tests { keyspace.drop().await; } + + /// Three statements of the secret store run at `ALL` (RFC-0000 section + /// 8.4): the page read, the rewrite and the write-time read of a delete. + /// The test gives a migrated catalog keyspace the replication of + /// [`TestKeyspace::under_replicated`] and calls four store methods. Each + /// call fails at its first statement. The Unavailable error names `ALL`. + /// Not checked here: `replace_setting`, the settings store's key row + /// statements, and the tombstone write of a delete, which runs only after + /// its read. + #[tokio::test] + async fn the_secret_store_sends_at_all() { + use extenddb_storage::management_store::{ManagementStore as _, SecretWrite}; + use extenddb_storage::secret_keys::SecretTable; + + if crate::helpers::skip_without_cassandra() { + return; + } + let isolated = crate::helpers::isolated_engine("levels").await; + let catalog = isolated.engine.catalog_keyspace(); + let session = session_without_retries().await; + let replicas = no_quorum_replicas(&session).await; + cassandra_util::ddl::( + &session, + &format!( + "ALTER KEYSPACE {catalog} WITH replication = {}", + replication(replicas) + ), + "raise the replication", + ) + .await + .expect("raise the catalog's replication"); + let store = extenddb_storage_cassandra::CassandraCatalogStore::catalog_only( + Arc::clone(&session), + isolated.config.keyspace_prefix.clone(), + ); + let key = "AKIAEXTENDDBLEVELS01".to_owned(); + let write = SecretWrite { + key: key.clone(), + secret_key_encrypted: vec![1], + write_timestamp: None, + }; + + for (method, result) in [ + ( + "read_secret_page", + store + .read_secret_page(SecretTable::IamSessions, None, 10) + .await + .map(drop), + ), + ( + "write_secrets", + store.write_secrets(SecretTable::AccessKeys, &[write]).await, + ), + ( + "delete_secrets", + store.delete_secrets(SecretTable::AccessKeys, &[key]).await, + ), + ( + "delete_setting", + store.delete_setting("encryption_key").await, + ), + ] { + let error = result.expect_err(method); + assert_eq!(level_in(error.message()), Consistency::All, "{method}"); + } + + drop(isolated); + crate::helpers::flush_pending_drops(&session).await; + } } diff --git a/crates/storage-cassandra/tests/direct/secret_rows.rs b/crates/storage-cassandra/tests/direct/secret_rows.rs new file mode 100644 index 000000000..fffa19b99 --- /dev/null +++ b/crates/storage-cassandra/tests/direct/secret_rows.rs @@ -0,0 +1,477 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The stored-secret rows as the encryption-key commands read and write them +//! (RFC-0000 section 8.4), and the credential lookups through the key holder. + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use extenddb_auth::CredentialStore; + use extenddb_storage::management_store::{ + ManagementStore, SecretWrite, SettingsStore, StoredSecretRow, + }; + use extenddb_storage::secret_keys::{SecretKeys, SecretRow, SecretTable}; + use extenddb_storage_cassandra::{CassandraCatalogStore, CassandraCredentialStore}; + + use crate::helpers::{isolated_engine, unique_test_id}; + + const ACCOUNT: &str = "123456789012"; + const PAGE: usize = 1000; + + /// A catalog key holder and a DEK holder: the two keys a switch holds. + fn two_keys() -> (Arc, Arc) { + let key = extenddb_storage::bootstrapper::helpers::generate_encryption_key().unwrap(); + let catalog_key = Arc::new(SecretKeys::catalog_key(&key).unwrap()); + let dek = Arc::new(SecretKeys::dek_for_tests( + [7; 32], + 1, + "catalog-id-for-tests", + )); + (catalog_key, dek) + } + + /// Every row of `table`, read page by page. + async fn all_rows( + store: &dyn ManagementStore, + table: SecretTable, + page_size: usize, + ) -> Vec { + let mut rows = Vec::new(); + let mut page = None; + loop { + let read = store + .read_secret_page(table, page.as_deref(), page_size) + .await + .unwrap(); + rows.extend(read.rows); + page = read.next; + if page.is_none() { + return rows; + } + } + } + + /// The row of the access key `access_key_id`, read alone. + async fn row_of( + store: &dyn ManagementStore, + table: SecretTable, + access_key_id: &str, + ) -> StoredSecretRow { + all_rows(store, table, PAGE) + .await + .into_iter() + .find(|row| row.access_key_id == access_key_id) + .expect("the row is read") + } + + /// The re-encryption of `row` under `target`, as the pass writes it. + fn rewrite(row: &StoredSecretRow, from: &SecretKeys, target: &SecretKeys) -> SecretWrite { + let secret = from + .decrypt(&row.aad_row(), &row.secret_key_encrypted) + .unwrap(); + SecretWrite { + key: row.key.clone(), + secret_key_encrypted: target.encrypt(&row.aad_row(), &secret).unwrap(), + write_timestamp: row.write_timestamp, + } + } + + /// The encryption-key command and startup cases of RFC-0000 section 15, + /// on a catalog as `init` leaves it: a catalog key, a catalog id and no + /// ring, behind a store that holds the catalog key as the server does. + #[tokio::test] + async fn the_encryption_key_commands_run_on_a_cassandra_catalog() { + if crate::helpers::skip_without_cassandra() { + return; + } + let isolated = isolated_engine("keycmds").await; + let settings = isolated.settings(); + let key = extenddb_storage::bootstrapper::helpers::generate_encryption_key().unwrap(); + settings + .set_setting(extenddb_storage::secret_keys::CATALOG_KEY_SETTING, &key) + .await + .unwrap(); + let keys = extenddb_storage::server_components::load_secret_keys( + &settings, + extenddb_storage::server_components::KeySource::CatalogKey, + ) + .await + .unwrap(); + let store = settings.with_secret_keys(keys); + extenddb_storage::key_conformance::run( + &store, + &store, + extenddb_storage::key_conformance::Expectations { + write_timestamps: true, + data_connection: false, + }, + ) + .await; + } + + #[tokio::test] + async fn the_pass_reads_rewrites_and_deletes_stored_secrets() { + if crate::helpers::skip_without_cassandra() { + return; + } + let isolated = isolated_engine("secrets").await; + let (catalog_key, dek) = two_keys(); + let store: CassandraCatalogStore = isolated + .settings() + .with_secret_keys(Some(Arc::clone(&catalog_key))); + store.create_account(ACCOUNT, "acct").await.unwrap(); + store.create_user(ACCOUNT, "alice", None).await.unwrap(); + let trust = serde_json::json!({"Version": "2012-10-17", "Statement": []}); + store.create_role(ACCOUNT, "app", &trust).await.unwrap(); + + // Three access keys and one session, written as the server writes + // them: the store encrypts the access keys, AssumeRole the session, + // with its expiry in whole seconds. + let mut created = Vec::new(); + for _ in 0..3 { + created.push(store.create_access_key(ACCOUNT, "alice").await.unwrap()); + } + let session_key_id = format!("ASIA{}", unique_test_id()[..16].to_uppercase()); + let expires_at = (time::OffsetDateTime::now_utc() + time::Duration::hours(1)) + .replace_nanosecond(0) + .unwrap(); + let session_secret = "session-secret-for-the-test"; + let session_row = SecretRow::session( + &session_key_id, + ACCOUNT, + "app", + "run", + expires_at.unix_timestamp(), + ); + store + .store_session( + "token-for-the-test", + &session_key_id, + &catalog_key.encrypt(&session_row, session_secret).unwrap(), + ACCOUNT, + "app", + "run", + &None, + &None, + expires_at, + ) + .await + .unwrap(); + + // Read: every row with its AAD fields, its write time, and a + // ciphertext the catalog key opens, in pages of one. + let keys = all_rows(&store, SecretTable::AccessKeys, 1).await; + assert_eq!(keys.len(), 3, "{keys:?}"); + for row in &keys { + assert_eq!(row.key, row.access_key_id); + assert_eq!( + (row.account_id.as_str(), row.principal_name.as_str()), + (ACCOUNT, "alice") + ); + assert_eq!((row.session_name.as_deref(), row.expires_at), (None, None)); + assert!( + row.created_at.is_some() && row.write_timestamp.is_some(), + "{row:?}" + ); + let plaintext = catalog_key + .decrypt(&row.aad_row(), &row.secret_key_encrypted) + .unwrap(); + let made = created + .iter() + .find(|k| k.access_key_id == row.access_key_id) + .unwrap(); + assert_eq!(*plaintext, made.secret_access_key); + } + let sessions = all_rows(&store, SecretTable::IamSessions, PAGE).await; + assert_eq!(sessions.len(), 1, "{sessions:?}"); + let session = &sessions[0]; + assert_eq!(session.key, "token-for-the-test"); + assert_eq!(session.aad_row(), session_row); + assert_eq!( + *catalog_key + .decrypt(&session.aad_row(), &session.secret_key_encrypted) + .unwrap(), + session_secret + ); + + // Write: each secret under the DEK, by primary key. The DEK opens + // the rows read again, and the catalog key no longer does. + let writes: Vec = keys + .iter() + .map(|row| rewrite(row, &catalog_key, &dek)) + .collect(); + store + .write_secrets(SecretTable::AccessKeys, &writes) + .await + .unwrap(); + store + .write_secrets( + SecretTable::IamSessions, + &[rewrite(session, &catalog_key, &dek)], + ) + .await + .unwrap(); + for table in SecretTable::ALL { + for row in all_rows(&store, table, PAGE).await { + assert!( + dek.decrypt(&row.aad_row(), &row.secret_key_encrypted) + .is_ok(), + "{row:?}" + ); + assert!( + catalog_key + .decrypt(&row.aad_row(), &row.secret_key_encrypted) + .is_err() + ); + } + } + // The credential store shares the DEK and opens both rows; one built + // with no key opens neither. + let credentials = CassandraCredentialStore::new( + isolated.engine.session_arc(), + isolated.config.keyspace_prefix.clone(), + Some(Arc::clone(&dek)), + ); + let found = credentials + .lookup_credential(&created[0].access_key_id) + .await + .unwrap() + .unwrap(); + assert_eq!(found.secret_key, created[0].secret_access_key); + let found = credentials + .lookup_credential(&session_key_id) + .await + .unwrap() + .unwrap(); + assert_eq!( + (found.secret_key.as_str(), found.expires_at), + (session_secret, Some(expires_at)) + ); + let keyless = CassandraCredentialStore::new( + isolated.engine.session_arc(), + isolated.config.keyspace_prefix.clone(), + None, + ); + assert!( + keyless + .lookup_credential(&created[0].access_key_id) + .await + .is_err() + ); + let keyless_store = isolated.settings(); + assert!( + keyless_store + .create_access_key(ACCOUNT, "alice") + .await + .is_err() + ); + + // Delete: the rows reset removes, and a settings row. + store + .delete_secrets( + SecretTable::AccessKeys, + &[keys[0].key.clone(), keys[1].key.clone()], + ) + .await + .unwrap(); + assert_eq!( + all_rows(&store, SecretTable::AccessKeys, PAGE).await.len(), + 1 + ); + store.set_setting("row_to_delete", "value").await.unwrap(); + store.delete_setting("row_to_delete").await.unwrap(); + store.delete_setting("row_to_delete").await.unwrap(); + assert_eq!(store.get_setting("row_to_delete").await.unwrap(), None); + } + + /// CreateAccessKey writes with `INSERT ... IF NOT EXISTS`, whose Paxos + /// timestamp can be ahead of a later plain update's clock. The pass's + /// update sets `USING TIMESTAMP` above the row's write time, so it lands + /// on a row written an hour ahead of the clock. + #[tokio::test] + async fn a_rewrite_lands_on_a_row_whose_write_time_is_ahead_of_the_clock() { + if crate::helpers::skip_without_cassandra() { + return; + } + let isolated = isolated_engine("secretsahead").await; + let (catalog_key, dek) = two_keys(); + let store = isolated + .settings() + .with_secret_keys(Some(Arc::clone(&catalog_key))); + let access_key_id = "AKIAEXTENDDBAHEAD001"; + let row = SecretRow::access_key(access_key_id, ACCOUNT, "alice"); + let ahead = chrono::Utc::now().timestamp_micros() + 3_600_000_000; + isolated + .engine + .session_arc() + .query_with_values( + format!( + "INSERT INTO {}_catalog.access_keys (access_key_id, account_id, user_name, \ + secret_key_encrypted, is_active, created_at) VALUES (?, ?, ?, ?, true, \ + toTimestamp(now())) USING TIMESTAMP {ahead}", + isolated.config.keyspace_prefix + ), + cdrs_tokio::query_values!( + access_key_id, + ACCOUNT, + "alice", + cdrs_tokio::types::blob::Blob::new( + catalog_key.encrypt(&row, "secret").unwrap() + ) + ), + ) + .await + .unwrap(); + + let read = row_of(&store, SecretTable::AccessKeys, access_key_id).await; + assert_eq!(read.write_timestamp, Some(ahead)); + store + .write_secrets( + SecretTable::AccessKeys, + &[rewrite(&read, &catalog_key, &dek)], + ) + .await + .unwrap(); + let again = row_of(&store, SecretTable::AccessKeys, access_key_id).await; + assert_eq!(again.write_timestamp, Some(ahead + 1)); + assert_eq!( + *dek.decrypt(&again.aad_row(), &again.secret_key_encrypted) + .unwrap(), + "secret" + ); + } + + /// A row tombstone below a cell's timestamp leaves the cell in place, so + /// `delete_secrets` and `delete_setting` stamp themselves at the largest + /// write time the row holds when that is ahead of the clock. `reset` + /// reports the rows it deleted, and a switch reports the catalog key row + /// gone, so a lost delete would be a wrong report. + /// + /// The session row's `session_policy` carries a later timestamp than its + /// other columns, as the policy migration's plain `UPDATE` leaves it. A + /// tombstone that covered only the column the page read selects would + /// leave that cell, and with it a row whose key columns are null, which + /// no later command can parse. + #[tokio::test] + async fn a_delete_lands_on_a_row_whose_write_time_is_ahead_of_the_clock() { + if crate::helpers::skip_without_cassandra() { + return; + } + let isolated = isolated_engine("secretsdelahead").await; + let (catalog_key, _) = two_keys(); + let store = isolated + .settings() + .with_secret_keys(Some(Arc::clone(&catalog_key))); + let access_key_id = "AKIAEXTENDDBAHEAD002"; + let row = SecretRow::access_key(access_key_id, ACCOUNT, "alice"); + let ahead = chrono::Utc::now().timestamp_micros() + 3_600_000_000; + let prefix = &isolated.config.keyspace_prefix; + let session = isolated.engine.session_arc(); + session + .query_with_values( + format!( + "INSERT INTO {prefix}_catalog.access_keys (access_key_id, account_id, \ + user_name, secret_key_encrypted, is_active, created_at) VALUES (?, ?, ?, \ + ?, true, toTimestamp(now())) USING TIMESTAMP {ahead}" + ), + cdrs_tokio::query_values!( + access_key_id, + ACCOUNT, + "alice", + cdrs_tokio::types::blob::Blob::new( + catalog_key.encrypt(&row, "secret").unwrap() + ) + ), + ) + .await + .unwrap(); + session + .query_with_values( + format!( + "INSERT INTO {prefix}_catalog.settings (key, value) VALUES (?, ?) \ + USING TIMESTAMP {ahead}" + ), + cdrs_tokio::query_values!("encryption_key", "a-value"), + ) + .await + .unwrap(); + + // The session row: every column at `ahead`, then its policy an hour + // later again, which only that column carries. + let session_token = "token-written-ahead-of-the-clock"; + let session_key_id = "ASIAEXTENDDBAHEAD002"; + let expires_at = (time::OffsetDateTime::now_utc() + time::Duration::hours(1)) + .replace_nanosecond(0) + .unwrap(); + let session_row = SecretRow::session( + session_key_id, + ACCOUNT, + "app", + "run", + expires_at.unix_timestamp(), + ); + session + .query_with_values( + format!( + "INSERT INTO {prefix}_catalog.iam_sessions (session_token, access_key_id, \ + account_id, role_name, session_name, secret_key_encrypted, expires_at, \ + created_at) VALUES (?, ?, ?, 'app', 'run', ?, ?, toTimestamp(now())) \ + USING TIMESTAMP {ahead}" + ), + cdrs_tokio::query_values!( + session_token, + session_key_id, + ACCOUNT, + cdrs_tokio::types::blob::Blob::new( + catalog_key.encrypt(&session_row, "session-secret").unwrap() + ), + expires_at.unix_timestamp() * 1000 + ), + ) + .await + .unwrap(); + let policy_ahead = ahead + 3_600_000_000; + session + .query_with_values( + format!( + "UPDATE {prefix}_catalog.iam_sessions USING TIMESTAMP {policy_ahead} \ + SET session_policy = ? WHERE session_token = ?" + ), + cdrs_tokio::query_values!("{\"Version\":\"2012-10-17\"}", session_token), + ) + .await + .unwrap(); + + store + .delete_secrets(SecretTable::AccessKeys, &[access_key_id.to_owned()]) + .await + .unwrap(); + store + .delete_secrets(SecretTable::IamSessions, &[session_token.to_owned()]) + .await + .unwrap(); + store.delete_setting("encryption_key").await.unwrap(); + + let keys = store + .read_secret_page(SecretTable::AccessKeys, None, 10) + .await + .unwrap(); + assert!( + !keys.rows.iter().any(|row| row.key == access_key_id), + "the access key row written an hour ahead of the clock is gone" + ); + // A page read that parses at all proves no cell of the session row + // survived: `stored_secret_row` fails on a row with null key columns. + let sessions = store + .read_secret_page(SecretTable::IamSessions, None, 10) + .await + .expect("the sessions page parses, so no cell of the row is left"); + assert!( + sessions.rows.is_empty(), + "the session row whose policy was written two hours ahead is gone" + ); + assert_eq!(store.get_setting("encryption_key").await.unwrap(), None); + } +} diff --git a/crates/storage-cassandra/tests/direct/users.rs b/crates/storage-cassandra/tests/direct/users.rs index 3214f5049..710a06581 100644 --- a/crates/storage-cassandra/tests/direct/users.rs +++ b/crates/storage-cassandra/tests/direct/users.rs @@ -174,16 +174,7 @@ mod tests { let engine = setup_engine().await; let config = test_config(); - // Need encryption key for access keys - use extenddb_storage::bootstrapper::helpers::generate_encryption_key; - let enc_key = generate_encryption_key().expect("generate key"); - let catalog_store = extenddb_storage_cassandra::CassandraCatalogStore::with_encryption_key( - engine.session_arc(), - config.keyspace_prefix.clone(), - config.datacenter.clone(), - config.replication_factor, - enc_key, - ); + let catalog_store = crate::helpers::create_keyed_catalog_store(&engine, &config); let account_id = unique_test_account(); let account_name = format!("TestAccount_{}", unique_test_id()); diff --git a/crates/storage-cassandra/tests/direct_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index 135baf2f4..1971d1317 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -64,6 +64,8 @@ mod query; mod roles; #[path = "direct/scan.rs"] mod scan; +#[path = "direct/secret_rows.rs"] +mod secret_rows; #[path = "direct/settings_store.rs"] mod settings_store; #[path = "direct/snapshot_engine.rs"] diff --git a/crates/storage-cassandra/tests/migrations.rs b/crates/storage-cassandra/tests/migrations.rs index 577419581..387d29cae 100644 --- a/crates/storage-cassandra/tests/migrations.rs +++ b/crates/storage-cassandra/tests/migrations.rs @@ -1661,3 +1661,65 @@ async fn init_finishes_a_catalog_stopped_before_its_admin_user() { drop(drops); helpers::flush_pending_drops(&session).await; } + +/// The stores that `CatalogMigrations::locked_stores` opens for the +/// encryption-key commands work while the lock is held, and refuse once it +/// is released. +#[tokio::test] +async fn the_stores_under_the_migration_lock_check_its_lease() { + use extenddb_storage::secret_keys::SecretTable; + + if helpers::skip_without_cassandra() { + return; + } + let session = session().await; + let (prefix, _drops) = new_prefix("locked"); + keyspace(&session, &format!("{prefix}_catalog")).await; + migrate_catalog_keyspace(session.clone(), &prefix, "test", TIMEOUT) + .await + .expect("migrate the catalog"); + let migrations = CassandraCatalogMigrations; + let lock = migrations + .lock(&target_of(&prefix), TIMEOUT) + .await + .expect("lock"); + let stores = migrations + .locked_stores(&lock, None) + .await + .expect("the stores under the lock"); + stores + .settings() + .set_setting("row_under_lock", "value") + .await + .expect("write"); + assert_eq!( + stores + .settings() + .get_setting("row_under_lock") + .await + .expect("read") + .as_deref(), + Some("value") + ); + assert!( + stores + .settings() + .replace_setting("row_under_lock", "value", "replaced") + .await + .expect("replace") + ); + let page = stores + .management() + .read_secret_page(SecretTable::AccessKeys, None, 1000) + .await + .expect("page"); + assert!(page.rows.is_empty() && page.next.is_none()); + stores + .management() + .delete_setting("row_under_lock") + .await + .expect("delete"); + + migrations.release(lock).await; + assert!(stores.settings().get_setting("catalog_id").await.is_err()); +} diff --git a/crates/storage-mongodb/src/catalog_store.rs b/crates/storage-mongodb/src/catalog_store.rs index 9439ced9e..4ae32fafa 100644 --- a/crates/storage-mongodb/src/catalog_store.rs +++ b/crates/storage-mongodb/src/catalog_store.rs @@ -3,6 +3,9 @@ //! Catalog store implementation for `MongoDB`. +use std::sync::Arc; + +use extenddb_storage::secret_keys::SecretKeys; use futures::future::BoxFuture; use mongodb::bson::doc; @@ -10,7 +13,10 @@ use mongodb::bson::doc; pub struct MongoCatalogStore { client: mongodb::Client, catalog_db: mongodb::Database, - pub(crate) encryption_key: Option, + /// The key holder that encrypts the stored secrets, shared with the + /// credential store; `None` for a store opened without a key, which + /// writes no credential. + pub(crate) keys: Option>, } impl MongoCatalogStore { @@ -20,18 +26,16 @@ impl MongoCatalogStore { Self { client, catalog_db, - encryption_key: None, + keys: None, } } + /// Hold the key holder the factory loaded, shared with the credential + /// store. Without one the store writes no credential. #[must_use] - pub fn with_encryption_key(client: mongodb::Client, encryption_key: String) -> Self { - let catalog_db = client.database("extenddb_catalog"); - Self { - client, - catalog_db, - encryption_key: Some(encryption_key), - } + pub fn with_secret_keys(mut self, keys: Option>) -> Self { + self.keys = keys; + self } /// A store on `catalog_db`, a handle the caller opened with its own @@ -41,7 +45,7 @@ impl MongoCatalogStore { Self { client, catalog_db, - encryption_key: None, + keys: None, } } @@ -62,8 +66,8 @@ impl MongoCatalogStore { // Implement CatalogStore supertrait impl extenddb_storage::CatalogStore for MongoCatalogStore { - fn cached_encryption_key(&self) -> Option { - self.encryption_key.clone() + fn secret_keys(&self) -> Option<&SecretKeys> { + self.keys.as_deref() } } @@ -112,6 +116,7 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for MongoCatalogStore { fn test_data_database_connection( &self, + _key: &extenddb_storage::server_components::KeySource, ) -> BoxFuture<'_, extenddb_storage::diagnostics::DiagResult> { Box::pin(async { // Ping the data database to verify connectivity diff --git a/crates/storage-mongodb/src/credential_store.rs b/crates/storage-mongodb/src/credential_store.rs index 74d318b46..e0ed0c7c6 100644 --- a/crates/storage-mongodb/src/credential_store.rs +++ b/crates/storage-mongodb/src/credential_store.rs @@ -3,37 +3,56 @@ //! Credential store implementation for `MongoDB`. //! -//! Secrets are decrypted with AES-256-GCM through -//! `extenddb_storage::secret_cipher`, with the access key id as the AAD. +//! Secrets are decrypted through the key holder +//! (`extenddb_storage::secret_keys`), which binds each secret to the fields +//! of its row. + +use std::sync::Arc; use mongodb::bson::{Document, doc}; -use zeroize::{Zeroize, ZeroizeOnDrop}; use extenddb_auth::{CredentialStore, StoredCredential}; use extenddb_core::error::DynamoDbError; -use extenddb_storage::secret_cipher::decrypt_secret; +use extenddb_storage::secret_keys::{SecretKeys, SecretRow, require_keys}; /// `MongoDB` credential store for authentication. -/// -/// The `encryption_key` is zeroed from memory on drop. -#[derive(Zeroize, ZeroizeOnDrop)] pub struct MongoCredentialStore { - #[zeroize(skip)] - client: mongodb::Client, - encryption_key: String, + catalog_db: mongodb::Database, + /// The key holder, shared with the catalog store; `None` for a store + /// opened without a key, which opens no stored secret. + keys: Option>, } impl MongoCredentialStore { #[must_use] - pub fn new(client: mongodb::Client, encryption_key: String) -> Self { + pub fn new(client: mongodb::Client, keys: Option>) -> Self { Self { - client, - encryption_key, + catalog_db: client.database("extenddb_catalog"), + keys, } } - fn catalog_db(&self) -> mongodb::Database { - self.client.database("extenddb_catalog") + /// A store on `catalog_db`, for the crate's integration tests, which + /// work in scratch databases of their own. + #[cfg(feature = "test-util")] + #[must_use] + pub fn on_database_for_tests( + catalog_db: mongodb::Database, + keys: Option>, + ) -> Self { + Self { catalog_db, keys } + } + + fn catalog_db(&self) -> &mongodb::Database { + &self.catalog_db + } + + /// The key holder, or the refusal of a store opened without one. + fn keys(&self) -> Result<&SecretKeys, DynamoDbError> { + require_keys(self.keys.as_deref()).map_err(|e| { + tracing::error!("Credential lookup: {e:?}"); + DynamoDbError::InternalServerError("Internal error during authentication".to_owned()) + }) } /// Whether `account_id` has a document in `accounts`. Before account @@ -87,8 +106,13 @@ impl MongoCredentialStore { return Ok(None); } - let secret_key = - decrypt_secret(&encrypted, &self.encryption_key, access_key_id).map_err(|e| { + let mut secret_key = self + .keys()? + .decrypt( + &SecretRow::access_key(access_key_id, &account_id, &user_name), + &encrypted, + ) + .map_err(|e| { tracing::error!("Secret key decryption failed for access key {access_key_id}: {e}"); DynamoDbError::InternalServerError( "Internal error during authentication".to_owned(), @@ -96,7 +120,9 @@ impl MongoCredentialStore { })?; Ok(Some(StoredCredential { - secret_key, + // Moved out, not copied: the plaintext has one allocation, wiped + // when the credential drops. + secret_key: std::mem::take(&mut *secret_key), account_id, principal_name: user_name, session_name: None, @@ -167,8 +193,19 @@ impl MongoCredentialStore { )); } - let secret_key = - decrypt_secret(&encrypted, &self.encryption_key, access_key_id).map_err(|e| { + let mut secret_key = self + .keys()? + .decrypt( + &SecretRow::session( + access_key_id, + &account_id, + &role_name, + &session_name, + expires_ts.unix_timestamp(), + ), + &encrypted, + ) + .map_err(|e| { tracing::error!( "Session secret key decryption failed for access key {access_key_id}: {e}" ); @@ -178,7 +215,9 @@ impl MongoCredentialStore { })?; Ok(Some(StoredCredential { - secret_key, + // Moved out, not copied: the plaintext has one allocation, wiped + // when the credential drops. + secret_key: std::mem::take(&mut *secret_key), account_id, principal_name: role_name, session_name: Some(session_name), diff --git a/crates/storage-mongodb/src/lib.rs b/crates/storage-mongodb/src/lib.rs index 08e377b22..24c08b6c1 100644 --- a/crates/storage-mongodb/src/lib.rs +++ b/crates/storage-mongodb/src/lib.rs @@ -18,6 +18,7 @@ mod credential_store; mod data; mod data_engine; mod management_store; +mod management_store_secrets; mod metadata_engine; pub mod migrations; mod operations; @@ -47,7 +48,7 @@ use extenddb_storage::error::StorageError; // ============================================================================ use extenddb_storage::hooks::{ServerRuntimeHooks, ServingRegistrar, WorkerContext}; -use extenddb_storage::server_components::{BackendError, ServerComponents}; +use extenddb_storage::server_components::{BackendError, ServerComponents, load_secret_keys}; /// Backend-specific runtime hooks for `MongoDB`. struct MongoRuntimeHooks { @@ -107,7 +108,7 @@ fn server_components_factory( // MongoDB bootstrap needs operator input (databases, admin credentials), so // `bootstrap_if_uninitialized` is not honored here: an uninitialized catalog // fails with the explicit-`init` guidance, matching the PostgreSQL backend. - options: extenddb_storage::server_components::ServerComponentsOptions, + mut options: extenddb_storage::server_components::ServerComponentsOptions, ) -> std::pin::Pin< Box> + Send>, > { @@ -155,7 +156,7 @@ fn server_components_factory( max_catalog_connections, tx_read_concern, Arc::clone(®istration), - &options, + &mut options, ) .await; if built.is_err() { @@ -201,7 +202,7 @@ async fn build_components( max_catalog_connections: Option, tx_read_concern: mongodb::options::ReadConcern, registration: Arc, - options: &extenddb_storage::server_components::ServerComponentsOptions, + options: &mut extenddb_storage::server_components::ServerComponentsOptions, ) -> Result { // Create MongoEngine let engine = MongoEngine::new(connection_string, region, max_connections, tx_read_concern) @@ -226,31 +227,22 @@ async fn build_components( details: format!("Failed to create catalog client: {e}"), })?; - // Load encryption key from settings collection. A missing key must be - // a hard failure: an empty key would base64-decode to zero bytes, and - // the secret cipher refuses any key that is not 32 bytes, so every - // credential lookup would fail. Refuse to start instead, matching the - // postgres backend. - let catalog_db = catalog_client.database("extenddb_catalog"); - let settings_coll = catalog_db.collection::("settings"); - let enc_key = settings_coll - .find_one(mongodb::bson::doc! { "_id": "encryption_key" }) - .await - .map_err(|e| BackendError::InitializationFailed(format!("Load encryption key: {e}")))? - .and_then(|d| d.get_str("value").ok().map(std::borrow::ToOwned::to_owned)) - .ok_or(BackendError::MissingEncryptionKey)?; - + // Load the key the stores share (RFC-0000 section 7): the catalog key, + // or the DEK of the key ring unwrapped with the KEK `serve` read. The + // refusals of section 7's table come from the loader, so a catalog with + // no key, or one the cipher refuses, stops the server here instead of + // failing every credential lookup with a 500. let auth_client = catalog_client.clone(); - let catalog_store = Arc::new(MongoCatalogStore::with_encryption_key( - catalog_client, - enc_key.clone(), - )) as Arc; + let catalog_store = MongoCatalogStore::new(catalog_client); + let keys = load_secret_keys(&catalog_store, std::mem::take(&mut options.key_source)).await?; + let catalog_store = Arc::new(catalog_store.with_secret_keys(keys.clone())) + as Arc; // Create credential store. The bin layer wraps this in // CachedCredentialStore using the operator-configured TTL // before constructing the auth provider. let cred_store: Arc = - Arc::new(MongoCredentialStore::new(auth_client, enc_key)); + Arc::new(MongoCredentialStore::new(auth_client, keys)); // Create runtime hooks let runtime_hooks = Box::new(MongoRuntimeHooks { diff --git a/crates/storage-mongodb/src/management_store.rs b/crates/storage-mongodb/src/management_store.rs index 87bbb9ac9..c51d20fc1 100644 --- a/crates/storage-mongodb/src/management_store.rs +++ b/crates/storage-mongodb/src/management_store.rs @@ -10,10 +10,10 @@ use mongodb::options::{FindOptions, UpdateOptions}; use extenddb_storage::management_store::{ AccessKeyCreated, AccountDetail, AdminEntry, GroupDetail, GroupListEntry, ManagementStore, - MetricsRow, OpError, OpResult, RoleDetail, RoleListEntry, SessionPolicyEntry, StoredDocument, - UserDetail, UserListEntry, + MetricsRow, OpError, OpResult, RoleDetail, RoleListEntry, SecretPage, SecretWrite, + SessionPolicyEntry, StoredDocument, UserDetail, UserListEntry, }; -use extenddb_storage::secret_cipher::encrypt_secret; +use extenddb_storage::secret_keys::{SecretRow, SecretTable, require_keys}; use crate::catalog_store::MongoCatalogStore; @@ -26,7 +26,7 @@ fn is_duplicate_key(e: &mongodb::error::Error) -> bool { ) } -fn to_offset_dt(dt: BsonDateTime) -> time::OffsetDateTime { +pub(crate) fn to_offset_dt(dt: BsonDateTime) -> time::OffsetDateTime { time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(dt.timestamp_millis()) * 1_000_000) .unwrap_or(time::OffsetDateTime::UNIX_EPOCH) } @@ -1966,14 +1966,18 @@ impl ManagementStore for MongoCatalogStore { return Err(OpError::NotFound("User not found".to_owned())); } - let enc_key = self.get_encryption_key().await?; - + let keys = require_keys(self.keys.as_deref())?; let access_key_id = generate_access_key_id(); let secret_key = generate_secret_key(); - let encrypted = encrypt_secret(&secret_key, &enc_key, &access_key_id).map_err(|e| { - tracing::error!("create_access_key encryption: {e}"); - OpError::Internal("Database error".to_owned()) - })?; + let encrypted = keys + .encrypt( + &SecretRow::access_key(&access_key_id, &account_id, &user_name), + &secret_key, + ) + .map_err(|e| { + tracing::error!("create_access_key encryption: {e}"); + OpError::Internal("Database error".to_owned()) + })?; let coll = self.catalog_db().collection::("access_keys"); coll.insert_one(doc! { @@ -2084,10 +2088,13 @@ impl ManagementStore for MongoCatalogStore { let access_key_id = access_key_id.to_owned(); let secret_access_key = secret_access_key.to_owned(); Box::pin(async move { - let enc_key = self.get_encryption_key().await?; - - let encrypted = - encrypt_secret(&secret_access_key, &enc_key, &access_key_id).map_err(|e| { + let keys = require_keys(self.keys.as_deref())?; + let encrypted = keys + .encrypt( + &SecretRow::access_key(&access_key_id, &account_id, &user_name), + &secret_access_key, + ) + .map_err(|e| { tracing::error!("import_access_key encryption: {e}"); OpError::Internal("Database error".to_owned()) })?; @@ -2321,6 +2328,40 @@ impl ManagementStore for MongoCatalogStore { } }) } + + // ── Encryption-key commands (RFC-0000 section 8.4) ───────────── + + fn read_secret_page( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> BoxFuture<'_, OpResult> { + let page = page.map(str::to_owned); + Box::pin(async move { + self.read_secret_page_impl(table, page.as_deref(), page_size) + .await + }) + } + + fn write_secrets( + &self, + table: SecretTable, + rows: &[SecretWrite], + ) -> BoxFuture<'_, OpResult<()>> { + let rows = rows.to_vec(); + Box::pin(async move { self.write_secrets_impl(table, &rows).await }) + } + + fn delete_secrets(&self, table: SecretTable, keys: &[String]) -> BoxFuture<'_, OpResult<()>> { + let keys = keys.to_vec(); + Box::pin(async move { self.delete_secrets_impl(table, &keys).await }) + } + + fn delete_setting(&self, key: &str) -> BoxFuture<'_, OpResult<()>> { + let key = key.to_owned(); + Box::pin(async move { self.delete_setting_impl(&key).await }) + } } // ── SettingsStore ─────────────────────────────────────────────────────── @@ -2357,6 +2398,16 @@ impl extenddb_storage::management_store::SettingsStore for MongoCatalogStore { }) } + fn replace_setting( + &self, + key: &str, + expected: &str, + value: &str, + ) -> BoxFuture<'_, OpResult> { + let (key, expected, value) = (key.to_owned(), expected.to_owned(), value.to_owned()); + Box::pin(async move { self.replace_setting_impl(&key, &expected, &value).await }) + } + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { Box::pin(async { let coll = self.catalog_db().collection::("settings"); @@ -2380,10 +2431,6 @@ impl extenddb_storage::management_store::SettingsStore for MongoCatalogStore { .collect()) }) } - - fn cached_encryption_key(&self) -> Option { - self.encryption_key.clone() - } } // ── MetricsStore ──────────────────────────────────────────────────────── @@ -2724,26 +2771,6 @@ impl extenddb_storage::management_store::AdminStore for MongoCatalogStore { } } -// ── Helper: encryption key retrieval ──────────────────────────────────── - -impl MongoCatalogStore { - async fn get_encryption_key(&self) -> OpResult { - if let Some(ref cached) = self.encryption_key { - return Ok(cached.clone()); - } - let coll = self.catalog_db().collection::("settings"); - let doc = coll - .find_one(doc! { "_id": "encryption_key" }) - .await - .map_err(|e| { - tracing::error!("get_encryption_key: {e}"); - OpError::Internal("Database error".to_owned()) - })?; - doc.and_then(|d| d.get_str("value").ok().map(std::borrow::ToOwned::to_owned)) - .ok_or_else(|| OpError::Internal("Encryption key not configured".to_owned())) - } -} - // ── Crypto helpers ────────────────────────────────────────────────────── fn generate_access_key_id() -> String { diff --git a/crates/storage-mongodb/src/management_store_secrets.rs b/crates/storage-mongodb/src/management_store_secrets.rs new file mode 100644 index 000000000..9d0811340 --- /dev/null +++ b/crates/storage-mongodb/src/management_store_secrets.rs @@ -0,0 +1,224 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The stored-secret documents as the encryption-key commands read and write +//! them (RFC-0000 section 8.4), for `MongoCatalogStore`. +//! +//! A page is a `find` in `_id` order with the last `_id` as the page token, +//! and the `_id` hex is the row key the writes take back: nothing makes +//! `access_key_id` unique before migration 12, and a session's `_id` is not +//! its token. Each write is one `update_one` on the `_id` with no upsert, +//! under write concern `majority`, so a document the TTL index on +//! `iam_sessions.expires_at` deleted during the pass stays deleted. + +use futures::TryStreamExt; +use mongodb::bson::oid::ObjectId; +use mongodb::bson::{Binary, Document, doc}; + +use extenddb_storage::management_store::{ + OpError, OpResult, SecretPage, SecretWrite, StoredSecretRow, +}; +use extenddb_storage::secret_keys::SecretTable; + +use crate::catalog_store::MongoCatalogStore; +use crate::management_store::to_offset_dt; + +/// The updates of one page in flight at once. Each waits for a majority of +/// the replica set, and the migration backend's store, which the offline +/// commands go through, bounds the whole page by its request timeout. +const WRITE_CONCURRENCY: usize = 8; + +/// A driver error, logged with its context and answered as a database error. +fn database_error(context: &str, e: &dyn std::fmt::Display) -> OpError { + tracing::error!("{context}: {e}"); + OpError::Internal("Database error".to_owned()) +} + +/// The `_id` of a stored-secret document as its row key: the hex of the +/// `ObjectId` the driver gave the document on insert. Refused for an `_id` +/// of another type, which no writer of these collections produces. +fn row_key(d: &Document, context: &str) -> OpResult { + d.get_object_id("_id").map(|id| id.to_hex()).map_err(|e| { + database_error( + context, + &format!("the document _id is not an ObjectId: {e}"), + ) + }) +} + +/// The `_id` a row key names. +fn object_id(key: &str, context: &str) -> OpResult { + ObjectId::parse_str(key) + .map_err(|e| database_error(context, &format!("the row key is not an ObjectId: {e}"))) +} + +/// A required string field of a stored-secret document. +fn field(d: &Document, name: &str, context: &str) -> OpResult { + d.get_str(name) + .map(str::to_owned) + .map_err(|e| database_error(context, &format!("field {name}: {e}"))) +} + +/// One document of a page as a [`StoredSecretRow`]. +fn stored_secret_row(table: SecretTable, d: &Document) -> OpResult { + const WHAT: &str = "read_secret_page"; + let (principal_name, session_name, expires_at) = match table { + SecretTable::AccessKeys => (field(d, "user_name", WHAT)?, None, None), + SecretTable::IamSessions => ( + field(d, "role_name", WHAT)?, + Some(field(d, "session_name", WHAT)?), + d.get_datetime("expires_at") + .ok() + .map(|expires| to_offset_dt(*expires).unix_timestamp()), + ), + }; + let secret_key_encrypted = d + .get_binary_generic("secret_key_encrypted") + .map_err(|e| database_error(WHAT, &format!("field secret_key_encrypted: {e}")))? + .clone(); + Ok(StoredSecretRow { + table, + key: row_key(d, WHAT)?, + access_key_id: field(d, "access_key_id", WHAT)?, + account_id: field(d, "account_id", WHAT)?, + principal_name, + session_name, + expires_at, + created_at: d + .get_datetime("created_at") + .ok() + .map(|created| to_offset_dt(*created)), + secret_key_encrypted, + write_timestamp: None, + }) +} + +impl MongoCatalogStore { + /// The collection of `table` on the catalog database. + fn secrets(&self, table: SecretTable) -> mongodb::Collection { + self.catalog_db().collection::(table.name()) + } + + /// `w: majority` for the writes of the pass, keeping the client's + /// `wtimeout` and `journal`. + fn majority(&self) -> mongodb::options::WriteConcern { + crate::majority_write_concern(self.catalog_db().write_concern()) + } + + pub(crate) async fn read_secret_page_impl( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> OpResult { + const WHAT: &str = "read_secret_page"; + let filter = match page { + Some(last) => doc! { "_id": { "$gt": object_id(last, WHAT)? } }, + None => doc! {}, + }; + let docs: Vec = self + .secrets(table) + .find(filter) + .sort(doc! { "_id": 1 }) + .limit(i64::try_from(page_size).unwrap_or(i64::MAX)) + .await + .map_err(|e| database_error(WHAT, &e))? + .try_collect() + .await + .map_err(|e| database_error(WHAT, &e))?; + let rows = docs + .iter() + .map(|d| stored_secret_row(table, d)) + .collect::>>()?; + // A full page may be the last one; the next read then finds nothing. + let next = (rows.len() == page_size) + .then(|| rows.last().map(|row| row.key.clone())) + .flatten(); + Ok(SecretPage { rows, next }) + } + + pub(crate) async fn write_secrets_impl( + &self, + table: SecretTable, + rows: &[SecretWrite], + ) -> OpResult<()> { + use futures::StreamExt as _; + const WHAT: &str = "write_secrets"; + let coll = &self.secrets(table); + let majority = &self.majority(); + let updates = rows + .iter() + .map(|row| Ok((object_id(&row.key, WHAT)?, row.secret_key_encrypted.clone()))) + .collect::>>()?; + // A document that is gone matches nothing, which is not an error. + let mut writes = futures::stream::iter(updates) + .map(|(id, bytes)| async move { + let ciphertext = Binary { + subtype: mongodb::bson::spec::BinarySubtype::Generic, + bytes, + }; + coll.update_one( + doc! { "_id": id }, + doc! { "$set": { "secret_key_encrypted": ciphertext } }, + ) + .write_concern(majority.clone()) + .await + }) + .buffer_unordered(WRITE_CONCURRENCY); + while let Some(result) = writes.next().await { + result.map_err(|e| database_error(WHAT, &e))?; + } + Ok(()) + } + + pub(crate) async fn delete_secrets_impl( + &self, + table: SecretTable, + keys: &[String], + ) -> OpResult<()> { + const WHAT: &str = "delete_secrets"; + if keys.is_empty() { + return Ok(()); + } + let ids = keys + .iter() + .map(|key| object_id(key, WHAT)) + .collect::>>()?; + self.secrets(table) + .delete_many(doc! { "_id": { "$in": ids } }) + .write_concern(self.majority()) + .await + .map_err(|e| database_error(WHAT, &e))?; + Ok(()) + } + + pub(crate) async fn delete_setting_impl(&self, key: &str) -> OpResult<()> { + self.catalog_db() + .collection::("settings") + .delete_one(doc! { "_id": key }) + .write_concern(self.majority()) + .await + .map_err(|e| database_error("delete_setting", &e))?; + Ok(()) + } + + /// One `update_one` whose filter carries `expected`, with no upsert. + pub(crate) async fn replace_setting_impl( + &self, + key: &str, + expected: &str, + value: &str, + ) -> OpResult { + let done = self + .catalog_db() + .collection::("settings") + .update_one( + doc! { "_id": key, "value": expected }, + doc! { "$set": { "value": value } }, + ) + .write_concern(self.majority()) + .await + .map_err(|e| database_error("replace_setting", &e))?; + Ok(done.matched_count == 1) + } +} diff --git a/crates/storage-mongodb/src/migrations/backend.rs b/crates/storage-mongodb/src/migrations/backend.rs index 6e0dee393..66c99f11d 100644 --- a/crates/storage-mongodb/src/migrations/backend.rs +++ b/crates/storage-mongodb/src/migrations/backend.rs @@ -15,10 +15,10 @@ use std::sync::Arc; use async_trait::async_trait; use bson::{Bson, Document, doc}; -use extenddb_storage::management_store::ManagementStore; +use extenddb_storage::management_store::{ManagementStore, SettingsStore}; use extenddb_storage::migrations::{ - CatalogTraces, Done, HasManagementStore, LedgerColumns, LedgerRow, LedgerWrites, Migration, - MigrationBackend, MigrationError, MigrationId, Released, Step, StoreKind, StoreRef, + CatalogTraces, Done, HasManagementStore, LedgerColumns, LedgerRow, LedgerWrites, LockedStores, + Migration, MigrationBackend, MigrationError, MigrationId, Released, Step, StoreKind, StoreRef, in_transaction, record_rows, }; use futures::TryStreamExt; @@ -106,6 +106,21 @@ impl HasManagementStore for MongoStores { } } +/// The catalog's stores for the encryption-key commands, which open them +/// under the lock they hold as a migration does: every call checks the +/// lease first and waits at most the request timeout. The client closes +/// when the value drops, without the graceful shutdown of +/// [`MongoMigrations::close`], which a boxed store cannot await. +impl LockedStores for MongoMigrations { + fn management(&self) -> &dyn ManagementStore { + &self.stores.management + } + + fn settings(&self) -> &dyn SettingsStore { + &self.stores.management + } +} + /// The runner's view of one MongoDB deployment. pub struct MongoMigrations { client: mongodb::Client, diff --git a/crates/storage-mongodb/src/migrations/commands.rs b/crates/storage-mongodb/src/migrations/commands.rs index 8344b8cb7..8820d1029 100644 --- a/crates/storage-mongodb/src/migrations/commands.rs +++ b/crates/storage-mongodb/src/migrations/commands.rs @@ -18,8 +18,8 @@ use std::time::{Duration, Instant}; use async_trait::async_trait; use extenddb_storage::migrations::{ - CatalogMigrations, CatalogStatus, HeldLock, LedgerRow, Listed, MigrationError, MigrationId, - RunKind, RunReport, Runner, Target, + CatalogMigrations, CatalogStatus, HeldLock, LedgerRow, Listed, LockedStores, MigrationError, + MigrationId, RunKind, RunReport, Runner, Target, }; use super::foreign::foreign_unless_a_catalog; @@ -44,6 +44,15 @@ fn held(lock: &HeldLock) -> Result<&Held, MigrationError> { }) } +/// A [`HeldLock`] over a lock that [`lock`] took on `target`, for the +/// crate's integration tests, whose deployments use databases of their own +/// names, which [`CatalogMigrations::lock`] does not take. +#[cfg(feature = "test-util")] +#[must_use] +pub fn held_lock_for_tests(lock: MigrationLock, target: MongoTarget) -> HeldLock { + HeldLock::new(target.connection_string.clone(), Held { lock, target }) +} + /// The lease of a lock this backend took, which `init`'s bootstrapper checks /// before each row it writes; `None` for another backend's lock. pub(crate) fn lease_of(lock: &HeldLock) -> Option> { @@ -122,6 +131,20 @@ impl CatalogMigrations for MongoCatalogMigrations { migrations.close().await; result } + + /// The catalog database's stores on a client of their own, under the + /// lock's lease. A MongoDB catalog stores its data connection string + /// with the password redacted, so `data_connection` is not read. + async fn locked_stores( + &self, + lock: &HeldLock, + _data_connection: Option<&str>, + ) -> Result, MigrationError> { + let held = held(lock)?; + Ok(Box::new( + MongoMigrations::open(&held.target, Some(&held.lock)).await?, + )) + } } /// Take the migration lock on `target`, waiting up to `timeout` for another diff --git a/crates/storage-mongodb/src/migrations/guarded.rs b/crates/storage-mongodb/src/migrations/guarded.rs index 17d4aec91..c9f65735a 100644 --- a/crates/storage-mongodb/src/migrations/guarded.rs +++ b/crates/storage-mongodb/src/migrations/guarded.rs @@ -21,9 +21,10 @@ use std::sync::Arc; use bson::{Document, doc}; use extenddb_storage::management_store::{ AccessKeyCreated, AccountDetail, GroupDetail, GroupListEntry, ManagementStore, OpError, - OpResult, RoleDetail, RoleListEntry, SessionPolicyEntry, StoredDocument, UserDetail, - UserListEntry, + OpResult, RoleDetail, RoleListEntry, SecretPage, SecretWrite, SessionPolicyEntry, + SettingsStore, StoredDocument, UserDetail, UserListEntry, }; +use extenddb_storage::secret_keys::SecretTable; use futures::future::BoxFuture; use super::REQUEST_TIMEOUT; @@ -206,6 +207,22 @@ impl ManagementStore for LeasedManagementStore { fn list_session_policies(&self) -> BoxFuture<'_, OpResult>>; fn update_session_policy(&self, session_token: &str, document: &serde_json::Value) -> BoxFuture<'_, OpResult<()>>; fn fetch_caller_tags(&self, account_id: &str, resource: &str) -> BoxFuture<'_, OpResult>>; + fn read_secret_page(&self, table: SecretTable, page: Option<&str>, page_size: usize) -> BoxFuture<'_, OpResult>; + fn write_secrets(&self, table: SecretTable, rows: &[SecretWrite]) -> BoxFuture<'_, OpResult<()>>; + fn delete_secrets(&self, table: SecretTable, keys: &[String]) -> BoxFuture<'_, OpResult<()>>; + fn delete_setting(&self, key: &str) -> BoxFuture<'_, OpResult<()>>; + } +} + +/// The settings documents under the same lease check and timeout: the +/// encryption-key commands read and write the key rows through the stores of +/// the lock they hold (RFC-0000 section 8, common rules). +impl SettingsStore for LeasedManagementStore { + checked! { + fn get_setting(&self, key: &str) -> BoxFuture<'_, OpResult>>; + fn set_setting(&self, key: &str, value: &str) -> BoxFuture<'_, OpResult<()>>; + fn replace_setting(&self, key: &str, expected: &str, value: &str) -> BoxFuture<'_, OpResult>; + fn list_settings(&self) -> BoxFuture<'_, OpResult>>; } } diff --git a/crates/storage-mongodb/src/migrations/mod.rs b/crates/storage-mongodb/src/migrations/mod.rs index 0578bdb7d..238e43da6 100644 --- a/crates/storage-mongodb/src/migrations/mod.rs +++ b/crates/storage-mongodb/src/migrations/mod.rs @@ -60,6 +60,8 @@ use extenddb_storage::migrations::{ }; pub use backend::{MongoMigrations, MongoStores}; +#[cfg(feature = "test-util")] +pub use commands::held_lock_for_tests; pub(crate) use commands::lease_of; pub use commands::{MongoCatalogMigrations, lock}; pub use foreign::foreign_contents; diff --git a/crates/storage-mongodb/tests/secret_rows.rs b/crates/storage-mongodb/tests/secret_rows.rs new file mode 100644 index 000000000..7cc82e16f --- /dev/null +++ b/crates/storage-mongodb/tests/secret_rows.rs @@ -0,0 +1,356 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The stored-secret documents as the encryption-key commands read and write +//! them (RFC-0000 section 8.4), and the credential lookups through the key +//! holder, against a live replica set named by `EXTENDDB_TEST_MONGODB_URI`. + +mod migrations_support; + +use std::sync::Arc; + +use bson::Document; +use extenddb_auth::CredentialStore; +use extenddb_storage::management_store::{ + ManagementStore, SecretWrite, SettingsStore, StoredSecretRow, +}; +use extenddb_storage::migrations::CatalogMigrations; +use extenddb_storage::secret_keys::{SecretKeys, SecretRow, SecretTable}; +use extenddb_storage_mongodb::migrations::{ + MongoCatalogMigrations, Timing, held_lock_for_tests, lock, +}; +use extenddb_storage_mongodb::{MongoCatalogStore, MongoCredentialStore}; +use migrations_support::{Deployment, server}; + +const ACCOUNT: &str = "123456789012"; +const PAGE: usize = 1000; + +/// Every row of `table`, read page by page. +async fn all_rows( + store: &dyn ManagementStore, + table: SecretTable, + page_size: usize, +) -> Vec { + let mut rows = Vec::new(); + let mut page = None; + loop { + let read = store + .read_secret_page(table, page.as_deref(), page_size) + .await + .unwrap(); + rows.extend(read.rows); + page = read.next; + if page.is_none() { + return rows; + } + } +} + +/// The re-encryption of `row` under `target`, as the pass writes it. +fn rewrite(row: &StoredSecretRow, from: &SecretKeys, target: &SecretKeys) -> SecretWrite { + let secret = from + .decrypt(&row.aad_row(), &row.secret_key_encrypted) + .unwrap(); + SecretWrite { + key: row.key.clone(), + secret_key_encrypted: target.encrypt(&row.aad_row(), &secret).unwrap(), + write_timestamp: row.write_timestamp, + } +} + +/// The encryption-key command and startup cases of RFC-0000 section 15, on +/// a catalog as `init` leaves it: a catalog key, a catalog id and no ring, +/// behind a store that holds the catalog key as the server does. +#[tokio::test] +async fn the_encryption_key_commands_run_on_a_mongodb_catalog() { + let Some(uri) = server() else { + return; + }; + let deployment = Deployment::new(&uri, "keycmds").await; + deployment.create().await; + let settings = + MongoCatalogStore::on_database_for_tests(deployment.client.clone(), deployment.catalog()); + let key = extenddb_storage::bootstrapper::helpers::generate_encryption_key().unwrap(); + settings + .set_setting(extenddb_storage::secret_keys::CATALOG_KEY_SETTING, &key) + .await + .unwrap(); + let keys = extenddb_storage::server_components::load_secret_keys( + &settings, + extenddb_storage::server_components::KeySource::CatalogKey, + ) + .await + .unwrap(); + let store = settings.with_secret_keys(keys); + extenddb_storage::key_conformance::run( + &store, + &store, + extenddb_storage::key_conformance::Expectations::default(), + ) + .await; + deployment.drop_databases().await; +} + +#[tokio::test] +async fn the_pass_reads_rewrites_and_deletes_stored_secrets() { + let Some(uri) = server() else { + return; + }; + let deployment = Deployment::new(&uri, "secrets").await; + deployment.create().await; + let key = extenddb_storage::bootstrapper::helpers::generate_encryption_key().unwrap(); + let catalog_key = Arc::new(SecretKeys::catalog_key(&key).unwrap()); + let dek = Arc::new(SecretKeys::dek_for_tests( + [7; 32], + 1, + "catalog-id-for-tests", + )); + let store = + MongoCatalogStore::on_database_for_tests(deployment.client.clone(), deployment.catalog()) + .with_secret_keys(Some(Arc::clone(&catalog_key))); + store.create_account(ACCOUNT, "acct").await.unwrap(); + store.create_user(ACCOUNT, "alice", None).await.unwrap(); + let trust = serde_json::json!({"Version": "2012-10-17", "Statement": []}); + store.create_role(ACCOUNT, "app", &trust).await.unwrap(); + + // Three access keys and one session, written as the server writes them: + // the store encrypts the access keys, AssumeRole the session, with its + // expiry in whole seconds. + let mut created = Vec::new(); + for _ in 0..3 { + created.push(store.create_access_key(ACCOUNT, "alice").await.unwrap()); + } + let session_key_id = "ASIAEXTENDDBSESSION1"; + let expires_at = (time::OffsetDateTime::now_utc() + time::Duration::hours(1)) + .replace_nanosecond(0) + .unwrap(); + let session_secret = "session-secret-for-the-test"; + let session_row = SecretRow::session( + session_key_id, + ACCOUNT, + "app", + "run", + expires_at.unix_timestamp(), + ); + store + .store_session( + "token-for-the-test", + session_key_id, + &catalog_key.encrypt(&session_row, session_secret).unwrap(), + ACCOUNT, + "app", + "run", + &None, + &None, + expires_at, + ) + .await + .unwrap(); + + // Read: every document with its AAD fields and a ciphertext the catalog + // key opens, in pages of one; the key is the document's _id. + let keys = all_rows(&store, SecretTable::AccessKeys, 1).await; + assert_eq!(keys.len(), 3, "{keys:?}"); + for row in &keys { + assert_eq!(row.key.len(), 24, "{row:?}"); + assert_eq!( + (row.account_id.as_str(), row.principal_name.as_str()), + (ACCOUNT, "alice") + ); + assert_eq!((row.session_name.as_deref(), row.expires_at), (None, None)); + assert!(row.created_at.is_some() && row.write_timestamp.is_none()); + let plaintext = catalog_key + .decrypt(&row.aad_row(), &row.secret_key_encrypted) + .unwrap(); + let made = created + .iter() + .find(|k| k.access_key_id == row.access_key_id) + .unwrap(); + assert_eq!(*plaintext, made.secret_access_key); + } + let sessions = all_rows(&store, SecretTable::IamSessions, PAGE).await; + assert_eq!(sessions.len(), 1, "{sessions:?}"); + let session = &sessions[0]; + assert_eq!(session.aad_row(), session_row); + assert_eq!( + *catalog_key + .decrypt(&session.aad_row(), &session.secret_key_encrypted) + .unwrap(), + session_secret + ); + + // Write: each secret under the DEK, by _id. The DEK opens the documents + // read again, and the catalog key no longer does. A document that is + // gone is not written back. + let writes: Vec = keys + .iter() + .map(|row| rewrite(row, &catalog_key, &dek)) + .collect(); + store + .write_secrets(SecretTable::AccessKeys, &writes) + .await + .unwrap(); + store + .write_secrets( + SecretTable::IamSessions, + &[rewrite(session, &catalog_key, &dek)], + ) + .await + .unwrap(); + for table in SecretTable::ALL { + for row in all_rows(&store, table, PAGE).await { + assert!( + dek.decrypt(&row.aad_row(), &row.secret_key_encrypted) + .is_ok(), + "{row:?}" + ); + assert!( + catalog_key + .decrypt(&row.aad_row(), &row.secret_key_encrypted) + .is_err() + ); + } + } + let gone = SecretWrite { + key: bson::oid::ObjectId::new().to_hex(), + ..writes[0].clone() + }; + store + .write_secrets(SecretTable::AccessKeys, &[gone]) + .await + .unwrap(); + assert_eq!( + all_rows(&store, SecretTable::AccessKeys, PAGE).await.len(), + 3 + ); + + // The credential store shares the DEK and opens both documents; one + // built with no key opens neither, and a store with no key writes none. + let credentials = + MongoCredentialStore::on_database_for_tests(deployment.catalog(), Some(Arc::clone(&dek))); + let found = credentials + .lookup_credential(&created[0].access_key_id) + .await + .unwrap() + .unwrap(); + assert_eq!(found.secret_key, created[0].secret_access_key); + let found = credentials + .lookup_credential(session_key_id) + .await + .unwrap() + .unwrap(); + assert_eq!( + (found.secret_key.as_str(), found.expires_at), + (session_secret, Some(expires_at)) + ); + let keyless = MongoCredentialStore::on_database_for_tests(deployment.catalog(), None); + assert!( + keyless + .lookup_credential(&created[0].access_key_id) + .await + .is_err() + ); + let keyless_store = + MongoCatalogStore::on_database_for_tests(deployment.client.clone(), deployment.catalog()); + assert!( + keyless_store + .create_access_key(ACCOUNT, "alice") + .await + .is_err() + ); + + // Delete: the documents reset removes, and a settings document. + store + .delete_secrets( + SecretTable::AccessKeys, + &[keys[0].key.clone(), keys[1].key.clone()], + ) + .await + .unwrap(); + assert_eq!( + all_rows(&store, SecretTable::AccessKeys, PAGE).await.len(), + 1 + ); + store.set_setting("row_to_delete", "value").await.unwrap(); + store.delete_setting("row_to_delete").await.unwrap(); + store.delete_setting("row_to_delete").await.unwrap(); + assert_eq!(store.get_setting("row_to_delete").await.unwrap(), None); + let settings: Vec = Deployment::documents(&deployment.catalog(), "settings").await; + assert!( + settings + .iter() + .all(|d| d.get_str("_id") != Ok("row_to_delete")), + "{settings:?}" + ); + deployment.drop_databases().await; +} + +/// The stores that `CatalogMigrations::locked_stores` opens for the +/// encryption-key commands work while the lock is held, and refuse once the +/// lock is released and its lease has run out. +#[tokio::test] +async fn the_stores_under_the_migration_lock_check_its_lease() { + let Some(uri) = server() else { + return; + }; + let deployment = Deployment::new(&uri, "locked").await; + deployment.create().await; + let timing = Timing { + lease: std::time::Duration::from_secs(3), + renew_every: std::time::Duration::from_secs(1), + margin: std::time::Duration::from_secs(1), + idle_limit: std::time::Duration::from_secs(2), + ..Timing::PRODUCTION + }; + let (held, target) = lock( + &deployment.target, + false, + std::time::Duration::from_secs(10), + timing, + ) + .await + .expect("lock"); + let held = held_lock_for_tests(held, target); + let stores = MongoCatalogMigrations + .locked_stores(&held, None) + .await + .expect("the stores under the lock"); + stores + .settings() + .set_setting("row_under_lock", "value") + .await + .unwrap(); + assert_eq!( + stores + .settings() + .get_setting("row_under_lock") + .await + .unwrap() + .as_deref(), + Some("value") + ); + assert!( + stores + .settings() + .replace_setting("row_under_lock", "value", "replaced") + .await + .unwrap() + ); + let page = stores + .management() + .read_secret_page(SecretTable::AccessKeys, None, PAGE) + .await + .unwrap(); + assert!(page.rows.is_empty() && page.next.is_none()); + stores + .management() + .delete_setting("row_under_lock") + .await + .unwrap(); + + MongoCatalogMigrations.release(held).await; + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + assert!(stores.settings().get_setting("catalog_id").await.is_err()); + drop(stores); + deployment.drop_databases().await; +} diff --git a/crates/storage-postgres/src/bootstrapper.rs b/crates/storage-postgres/src/bootstrapper.rs index 6223d7d52..f2cce5395 100755 --- a/crates/storage-postgres/src/bootstrapper.rs +++ b/crates/storage-postgres/src/bootstrapper.rs @@ -426,6 +426,7 @@ impl Bootstrapper for PostgresBootstrapper { password: self.config.admin_password.clone(), }), data_connection: Some(self.app_connection_url(&self.config.data_db)), + ..Target::default() } } diff --git a/crates/storage-postgres/src/catalog_store.rs b/crates/storage-postgres/src/catalog_store.rs index 27b815988..e63bbe28e 100755 --- a/crates/storage-postgres/src/catalog_store.rs +++ b/crates/storage-postgres/src/catalog_store.rs @@ -12,6 +12,7 @@ use std::sync::Arc; use extenddb_storage::management_store::{MetricsRow, OpError, OpResult}; +use extenddb_storage::secret_keys::SecretKeys; use futures::future::BoxFuture; use sqlx::PgPool; @@ -21,28 +22,26 @@ use sqlx::PgPool; /// and shared (via `Arc`) across management API handlers and background workers. pub struct PostgresCatalogStore { pool: PgPool, - /// P119: Cached encryption key (immutable after bootstrap). Avoids - /// per-request DB query on access key and assume-role operations. - encryption_key: Option>, + /// The key holder the server's factory loaded at startup, shared with + /// the credential store: the catalog key, or the DEK of the key ring. + /// Access key creation and import encrypt with it, and AssumeRole + /// reads it through `CatalogStore::secret_keys`. `None` for a store + /// opened without a key, which writes no credential. + keys: Option>, } impl PostgresCatalogStore { - /// Create a new catalog store wrapping the given pool. + /// Create a new catalog store wrapping the given pool, with no key + /// holder. #[must_use] pub fn new(pool: PgPool) -> Self { - Self { - pool, - encryption_key: None, - } + Self { pool, keys: None } } - /// Create a new catalog store with a pre-loaded encryption key (P119). + /// Create a new catalog store with the key holder the factory loaded. #[must_use] - pub fn with_encryption_key(pool: PgPool, encryption_key: String) -> Self { - Self { - pool, - encryption_key: Some(Arc::from(encryption_key.as_str())), - } + pub fn with_secret_keys(pool: PgPool, keys: Option>) -> Self { + Self { pool, keys } } /// Borrow the underlying pool (escape hatch for callers not yet migrated). @@ -50,12 +49,6 @@ impl PostgresCatalogStore { pub fn pool(&self) -> &PgPool { &self.pool } - - /// Get the cached encryption key. Returns `None` if not loaded at startup. - #[must_use] - pub fn encryption_key(&self) -> Option<&Arc> { - self.encryption_key.as_ref() - } } // ── SettingsStore ────────────────────────────────────────────────────── @@ -99,6 +92,29 @@ impl extenddb_storage::management_store::SettingsStore for PostgresCatalogStore }) } + fn replace_setting( + &self, + key: &str, + expected: &str, + value: &str, + ) -> futures::future::BoxFuture<'_, OpResult> { + let (key, expected, value) = (key.to_owned(), expected.to_owned(), value.to_owned()); + let pool = self.pool.clone(); + Box::pin(async move { + let done = sqlx::query("UPDATE settings SET value = $3 WHERE key = $1 AND value = $2") + .bind(&key) + .bind(&expected) + .bind(&value) + .execute(&pool) + .await + .map_err(|e| { + tracing::error!("replace_setting: {e}"); + OpError::Internal("Database error".to_owned()) + })?; + Ok(done.rows_affected() == 1) + }) + } + fn list_settings(&self) -> futures::future::BoxFuture<'_, OpResult>> { let pool = self.pool.clone(); Box::pin(async move { @@ -112,10 +128,17 @@ impl extenddb_storage::management_store::SettingsStore for PostgresCatalogStore }) } - fn cached_encryption_key(&self) -> Option { - self.encryption_key - .as_ref() - .map(std::string::ToString::to_string) + fn set_data_connection( + &self, + kek: &[u8; 32], + connection_string: &str, + ) -> BoxFuture<'_, OpResult<()>> { + let kek = zeroize::Zeroizing::new(*kek); + let connection_string = zeroize::Zeroizing::new(connection_string.to_owned()); + Box::pin(async move { + self.set_data_connection_impl(&kek, &connection_string) + .await + }) } } @@ -154,43 +177,37 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for PostgresCatalogStore { fn test_data_database_connection( &self, + key: &extenddb_storage::server_components::KeySource, ) -> futures::future::BoxFuture<'_, extenddb_storage::diagnostics::DiagResult> { + use extenddb_storage::diagnostics::DiagError; let pool = self.pool.clone(); + let key = key.clone(); Box::pin(async move { - // Get data database connection string and name from settings - let conn_row: Option<(String,)> = sqlx::query_as( - "SELECT value FROM settings WHERE key = 'data_database_connection_string'", - ) - .fetch_optional(&pool) - .await - .map_err(|e| extenddb_storage::diagnostics::DiagError::QueryFailed(e.to_string()))?; - + let not_configured = + || DiagError::QueryFailed("Data database not configured".to_string()); let name_row: Option<(String,)> = sqlx::query_as("SELECT value FROM settings WHERE key = 'data_database_name'") .fetch_optional(&pool) .await - .map_err(|e| { - extenddb_storage::diagnostics::DiagError::QueryFailed(e.to_string()) - })?; - - match (conn_row, name_row) { - (Some((conn,)), Some((name,))) => { - // Test connection - sqlx::postgres::PgPoolOptions::new() - .max_connections(1) - .connect(&conn) - .await - .map_err(|e| { - extenddb_storage::diagnostics::DiagError::ConnectionFailed( - e.to_string(), - ) - })?; - Ok(name) - } - _ => Err(extenddb_storage::diagnostics::DiagError::QueryFailed( - "Data database not configured".to_string(), - )), - } + .map_err(|e| DiagError::QueryFailed(e.to_string()))?; + let (name,) = name_row.ok_or_else(not_configured)?; + + // The connection string as the server reads it: in a catalog with + // a key ring the row is encrypted, and the KEK of key_file opens + // it (RFC-0000 section 12). + let target = + crate::migrations::PostgresTarget::new((*pool.connect_options()).clone(), &name) + .with_key_source(key, false); + let conn = crate::migrations::data_connection_string(&target) + .await + .map_err(|e| DiagError::QueryFailed(e.to_string()))? + .ok_or_else(not_configured)?; + sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&conn) + .await + .map_err(|e| DiagError::ConnectionFailed(e.to_string()))?; + Ok(name) }) } } @@ -422,9 +439,7 @@ impl extenddb_storage::management_store::RateLimitStore for PostgresCatalogStore // Implement CatalogStore supertrait impl extenddb_storage::CatalogStore for PostgresCatalogStore { - fn cached_encryption_key(&self) -> Option { - self.encryption_key - .as_ref() - .map(std::string::ToString::to_string) + fn secret_keys(&self) -> Option<&SecretKeys> { + self.keys.as_deref() } } diff --git a/crates/storage-postgres/src/credential_store.rs b/crates/storage-postgres/src/credential_store.rs index 912d663e3..5de04c4a7 100755 --- a/crates/storage-postgres/src/credential_store.rs +++ b/crates/storage-postgres/src/credential_store.rs @@ -5,36 +5,53 @@ //! //! Implements `extenddb_auth::CredentialStore` by looking up access keys and //! session credentials from the catalog database, decrypting secrets with -//! AES-256-GCM through `extenddb_storage::secret_cipher`. The access key id is -//! the AAD; a secret that does not authenticate under it is not returned. +//! the key holder the catalog store shares (`extenddb_storage::secret_keys`). +//! The row a secret was read from is its AAD; a secret that does not +//! authenticate under it is not returned. + +use std::sync::Arc; use extenddb_auth::{CredentialStore, StoredCredential}; use extenddb_core::error::DynamoDbError; -use extenddb_storage::secret_cipher::decrypt_secret; +use extenddb_storage::secret_keys::{SecretKeys, SecretRow}; use sqlx::PgPool; -use zeroize::{Zeroize, ZeroizeOnDrop}; /// Credential store backed by the catalog `PostgreSQL` database. /// -/// The `encryption_key` is zeroed from memory on drop. -#[derive(Zeroize, ZeroizeOnDrop)] +/// With no key holder (a factory caller that passed `KeySource::None`) every +/// lookup of a stored secret fails. pub struct DbCredentialStore { - #[zeroize(skip)] pool: PgPool, - /// Base64-encoded AES-256-GCM encryption key from the settings table. - encryption_key: String, + keys: Option>, } impl DbCredentialStore { - /// Create a new credential store. - /// - /// `encryption_key` is the base64-encoded 32-byte key from the `settings` table. + /// Create a new credential store over the key holder the catalog store + /// shares. #[must_use] - pub fn new(pool: PgPool, encryption_key: String) -> Self { - Self { - pool, - encryption_key, - } + pub fn new(pool: PgPool, keys: Option>) -> Self { + Self { pool, keys } + } + + /// Decrypt the secret of `row`, logging a failure under `what`. + fn open( + &self, + row: &SecretRow<'_>, + encrypted: &[u8], + what: &str, + ) -> Result { + let opened = match &self.keys { + Some(keys) => keys.decrypt(row, encrypted), + None => Err("the store was opened without an encryption key".to_owned()), + }; + let mut secret = opened.map_err(|e| { + tracing::error!( + "{what} decryption failed for access key {}: {e}", + row.access_key_id + ); + DynamoDbError::InternalServerError("Internal error during authentication".to_owned()) + })?; + Ok(std::mem::take(&mut *secret)) } } @@ -80,13 +97,11 @@ impl DbCredentialStore { return Ok(None); }; - let secret_key = - decrypt_secret(&encrypted, &self.encryption_key, access_key_id).map_err(|e| { - tracing::error!("Secret key decryption failed for access key {access_key_id}: {e}"); - DynamoDbError::InternalServerError( - "Internal error during authentication".to_owned(), - ) - })?; + let secret_key = self.open( + &SecretRow::access_key(access_key_id, &account_id, &user_name), + &encrypted, + "Secret key", + )?; Ok(Some(StoredCredential { secret_key, @@ -136,15 +151,19 @@ impl DbCredentialStore { )); } - let secret_key = - decrypt_secret(&encrypted, &self.encryption_key, access_key_id).map_err(|e| { - tracing::error!( - "Session secret key decryption failed for access key {access_key_id}: {e}" - ); - DynamoDbError::InternalServerError( - "Internal error during authentication".to_owned(), - ) - })?; + // `expires_at` is stored in microseconds; the AAD carries whole + // seconds, which `unix_timestamp` gives by flooring. + let secret_key = self.open( + &SecretRow::session( + access_key_id, + &account_id, + &role_name, + &session_name, + expires_at.unix_timestamp(), + ), + &encrypted, + "Session secret key", + )?; Ok(Some(StoredCredential { secret_key, diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 9409b6e44..237fcf728 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -359,8 +359,30 @@ impl Drop for ControlPlanePollerGuard { } } +/// Where [`PostgresEngine::open`] finds the data database's connection +/// string. +pub(crate) enum DataConnection<'a> { + /// The catalog's `data_database_connection_string` row, as stored: a + /// catalog without a key ring keeps it in plaintext. + Row, + /// The string the server's registration opened, or `None` when the + /// catalog has no such row. + Opened(Option<&'a str>), +} + impl PostgresEngine { pub async fn new(config: &PostgresConfig, region: &str) -> Result { + Self::open(config, region, DataConnection::Row).await + } + + /// [`PostgresEngine::new`] with the data database's connection string + /// taken from `data_connection`. Without a string the catalog pool + /// serves the data too. + pub(crate) async fn open( + config: &PostgresConfig, + region: &str, + data_connection: DataConnection<'_>, + ) -> Result { // Enforce a minimum of 10 connections per pool. Smaller values starve // the auth/authz query fanout under concurrent load. If the configured // value is below the floor, log a warning and clamp. @@ -389,19 +411,25 @@ impl PostgresEngine { // P54 Bug 1: Read data database connection string from catalog settings. // Falls back to the catalog pool if no separate data database is configured. + let row = match data_connection { + DataConnection::Row => sqlx::query_as::<_, (String,)>( + "SELECT value FROM settings WHERE key = 'data_database_connection_string'", + ) + .fetch_optional(&pool) + .await + .ok() + .flatten() + .map(|(value,)| zeroize::Zeroizing::new(value)), + DataConnection::Opened(value) => value.map(|v| zeroize::Zeroizing::new(v.to_owned())), + }; let mut shared_data_pool = false; - let data_pool = match sqlx::query_as::<_, (String,)>( - "SELECT value FROM settings WHERE key = 'data_database_connection_string'", - ) - .fetch_optional(&pool) - .await - { - Ok(Some((data_conn,))) if !data_conn.is_empty() => PgPoolOptions::new() + let data_pool = match row.as_deref() { + Some(data_conn) if !data_conn.is_empty() => PgPoolOptions::new() .max_connections(pool_size) .min_connections(min_conns) .test_before_acquire(false) .max_lifetime(std::time::Duration::from_secs(1800)) - .connect(&data_conn) + .connect(data_conn) .await .map_err(|e| { StorageError::Connection(format!("data database connection failed: {e}")) @@ -858,15 +886,26 @@ fn server_components_factory( options.max_concurrent_jobs, ); let region = region.to_string(); + let mut options = options; + let key_source = std::mem::take(&mut options.key_source); Box::pin(async move { // Every caller registers, a command too: a migration must not run - // under one. A command's session carries its own name. - let registration = migrations::ServerRegistration::register_as( + // under one. A command's session carries its own name. The key + // loads inside the registration, before the catalog status is read + // (RFC-0000 sections 7 and 12). + let registration = migrations::ServerRegistration::register_keyed( &connection_string, options.command.unwrap_or(migrations::SERVE_APPLICATION), + key_source, ) - .await - .map_err(BackendError::Catalog)?; + .await?; + let keys = registration.secret_keys(); + // In a catalog with a key ring the row is encrypted, and the one key + // holder the registration loaded opens it. + let data_connection = registration + .data_connection_string() + .await + .map_err(BackendError::Catalog)?; // Build PostgresConfig from extracted values let pg_config = PostgresConfig { @@ -876,12 +915,17 @@ fn server_components_factory( }; // Create PostgresEngine - let mut engine = PostgresEngine::new(&pg_config, ®ion) - .await - .map_err(|e| BackendError::ConnectionFailed { - backend: "postgres".to_string(), - details: e.to_string(), - })?; + let mut engine = PostgresEngine::open( + &pg_config, + ®ion, + DataConnection::Opened(data_connection.as_deref().map(String::as_str)), + ) + .await + .map_err(|e| BackendError::ConnectionFailed { + backend: "postgres".to_string(), + details: e.to_string(), + })?; + drop(data_connection); engine.serving = Some(Arc::new(registration)); // The startup recovery is a server's; a command reading beside one, @@ -955,27 +999,14 @@ fn server_components_factory( details: format!("Failed to create catalog pool: {e}"), })?; - // Load encryption key - let enc_key: Option = - sqlx::query_scalar("SELECT value FROM settings WHERE key = 'encryption_key'") - .fetch_optional(&catalog_pool) - .await - .map_err(|e| { - BackendError::InitializationFailed(format!( - "Failed to fetch encryption key: {e}" - )) - })?; - - let catalog_store = Arc::new(match enc_key { - Some(k) => PostgresCatalogStore::with_encryption_key(catalog_pool.clone(), k), - None => return Err(BackendError::MissingEncryptionKey), - }) as Arc; - - // Create auth provider - let enc_key = extenddb_storage::CatalogStore::cached_encryption_key(&*catalog_store) - .ok_or(BackendError::MissingEncryptionKey)?; + let catalog_store = Arc::new(PostgresCatalogStore::with_secret_keys( + catalog_pool.clone(), + keys.clone(), + )) as Arc; + + // The credential store shares the catalog store's key holder. let cred_store: Arc = - Arc::new(DbCredentialStore::new(catalog_pool.clone(), enc_key)); + Arc::new(DbCredentialStore::new(catalog_pool.clone(), keys)); // Create runtime hooks let runtime_hooks = Box::new(PostgresRuntimeHooks { diff --git a/crates/storage-postgres/src/management_store/access_keys.rs b/crates/storage-postgres/src/management_store/access_keys.rs index c5f67817f..888fd659f 100755 --- a/crates/storage-postgres/src/management_store/access_keys.rs +++ b/crates/storage-postgres/src/management_store/access_keys.rs @@ -3,8 +3,9 @@ //! Access key, session, and caller-tag operations for `PostgresCatalogStore`. +use extenddb_storage::CatalogStore as _; use extenddb_storage::management_store::{AccessKeyCreated, OpError, OpResult}; -use extenddb_storage::secret_cipher::encrypt_secret; +use extenddb_storage::secret_keys::{SecretRow, require_keys}; use super::database_error; use crate::catalog_store::PostgresCatalogStore; @@ -18,27 +19,18 @@ impl PostgresCatalogStore { account_id: &str, user_name: &str, ) -> OpResult { - // P119: Use cached encryption key if available, fall back to DB query. - let enc_key: String = if let Some(cached) = self.encryption_key() { - cached.to_string() - } else { - let row: Option = - sqlx::query_scalar("SELECT value FROM settings WHERE key = 'encryption_key'") - .fetch_optional(self.pool()) - .await - .map_err(|e| { - tracing::error!("create_access_key fetch encryption key: {e}"); - OpError::Internal("Database error".to_owned()) - })?; - row.ok_or_else(|| OpError::Internal("Encryption key not configured".to_owned()))? - }; - + let keys = require_keys(self.secret_keys())?; let access_key_id = generate_access_key_id(); let secret_key = generate_secret_key(); - let encrypted = encrypt_secret(&secret_key, &enc_key, &access_key_id).map_err(|e| { - tracing::error!("create_access_key encryption: {e}"); - OpError::Internal("Database error".to_owned()) - })?; + let encrypted = keys + .encrypt( + &SecretRow::access_key(&access_key_id, account_id, user_name), + &secret_key, + ) + .map_err(|e| { + tracing::error!("create_access_key encryption: {e}"); + OpError::Internal("Database error".to_owned()) + })?; sqlx::query( "INSERT INTO access_keys (access_key_id, account_id, user_name, secret_key_encrypted) \ @@ -117,23 +109,13 @@ impl PostgresCatalogStore { access_key_id: &str, secret_access_key: &str, ) -> OpResult<()> { - // P119: Use cached encryption key if available, fall back to DB query. - let enc_key: String = if let Some(cached) = self.encryption_key() { - cached.to_string() - } else { - let row: Option = - sqlx::query_scalar("SELECT value FROM settings WHERE key = 'encryption_key'") - .fetch_optional(self.pool()) - .await - .map_err(|e| { - tracing::error!("import_access_key fetch encryption key: {e}"); - OpError::Internal("Database error".to_owned()) - })?; - row.ok_or_else(|| OpError::Internal("Encryption key not configured".to_owned()))? - }; - - let encrypted = - encrypt_secret(secret_access_key, &enc_key, access_key_id).map_err(|e| { + let keys = require_keys(self.secret_keys())?; + let encrypted = keys + .encrypt( + &SecretRow::access_key(access_key_id, account_id, user_name), + secret_access_key, + ) + .map_err(|e| { tracing::error!("import_access_key encryption: {e}"); OpError::Internal("Database error".to_owned()) })?; @@ -178,6 +160,9 @@ impl PostgresCatalogStore { session_policy: &Option, expires_at: time::OffsetDateTime, ) -> OpResult<()> { + require_keys(self.secret_keys())?; + // AssumeRole truncated `expires_at` to whole seconds before its + // encrypt, so the stored value is the one in the secret's AAD. sqlx::query( "INSERT INTO iam_sessions \ (session_token, access_key_id, secret_key_encrypted, account_id, role_name, \ diff --git a/crates/storage-postgres/src/management_store/mod.rs b/crates/storage-postgres/src/management_store/mod.rs index ceb087928..f40186005 100755 --- a/crates/storage-postgres/src/management_store/mod.rs +++ b/crates/storage-postgres/src/management_store/mod.rs @@ -7,8 +7,10 @@ //! file under the 500-line limit. use extenddb_storage::management_store::{ - AccessKeyCreated, AccountDetail, GroupDetail, OpError, OpResult, RoleDetail, UserDetail, + AccessKeyCreated, AccountDetail, GroupDetail, OpError, OpResult, RoleDetail, SecretPage, + SecretWrite, UserDetail, }; +use extenddb_storage::secret_keys::SecretTable; use futures::future::BoxFuture; use super::catalog_store::PostgresCatalogStore; @@ -18,6 +20,7 @@ mod accounts; mod groups; mod policies; mod roles; +mod secret_rows; mod users; /// The error of a failed statement, logged with `what`. It keeps the @@ -624,4 +627,38 @@ impl extenddb_storage::management_store::ManagementStore for PostgresCatalogStor let resource = resource.to_string(); Box::pin(async move { self.fetch_caller_tags_impl(&account_id, &resource).await }) } + + // ── Encryption-key commands (in `secret_rows`) ───────────────── + + fn read_secret_page( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> BoxFuture<'_, OpResult> { + let page = page.map(ToOwned::to_owned); + Box::pin(async move { + self.read_secret_page_impl(table, page.as_deref(), page_size) + .await + }) + } + + fn write_secrets( + &self, + table: SecretTable, + rows: &[SecretWrite], + ) -> BoxFuture<'_, OpResult<()>> { + let rows = rows.to_vec(); + Box::pin(async move { self.write_secrets_impl(table, &rows).await }) + } + + fn delete_secrets(&self, table: SecretTable, keys: &[String]) -> BoxFuture<'_, OpResult<()>> { + let keys = keys.to_vec(); + Box::pin(async move { self.delete_secrets_impl(table, &keys).await }) + } + + fn delete_setting(&self, key: &str) -> BoxFuture<'_, OpResult<()>> { + let key = key.to_owned(); + Box::pin(async move { self.delete_setting_impl(&key).await }) + } } diff --git a/crates/storage-postgres/src/management_store/secret_rows.rs b/crates/storage-postgres/src/management_store/secret_rows.rs new file mode 100644 index 000000000..0c18e8b47 --- /dev/null +++ b/crates/storage-postgres/src/management_store/secret_rows.rs @@ -0,0 +1,237 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The stored secrets as the encryption-key commands read and rewrite them, +//! and the write of the data database connection string under the key ring, +//! for `PostgresCatalogStore`. + +use extenddb_storage::key_commands::data_connection_key; +use extenddb_storage::key_ring::KEY_RING_SETTING; +use extenddb_storage::management_store::{ + OpError, OpResult, SecretPage, SecretWrite, StoredSecretRow, +}; +use extenddb_storage::secret_keys::{CATALOG_ID_SETTING, DATA_CONNECTION_SETTING, SecretTable}; +use sqlx::postgres::PgConnectOptions; +use time::OffsetDateTime; + +use super::database_error; +use crate::catalog_store::PostgresCatalogStore; + +/// An `access_keys` row: key, secret, account, user, created. +type AccessKeyRow = (String, Vec, String, String, OffsetDateTime); + +/// An `iam_sessions` row: token, access key ID, secret, account, role, +/// session name, expiry, created. +type SessionRow = ( + String, + String, + Vec, + String, + String, + String, + OffsetDateTime, + OffsetDateTime, +); + +impl PostgresCatalogStore { + pub(crate) async fn read_secret_page_impl( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> OpResult { + let limit = i64::try_from(page_size).unwrap_or(i64::MAX); + let rows: Vec = match table { + SecretTable::AccessKeys => { + let rows: Vec = sqlx::query_as( + "SELECT access_key_id, secret_key_encrypted, account_id, user_name, \ + created_at FROM access_keys \ + WHERE $1::text IS NULL OR access_key_id > $1 \ + ORDER BY access_key_id LIMIT $2", + ) + .bind(page) + .bind(limit) + .fetch_all(self.pool()) + .await + .map_err(|e| database_error("read_secret_page", &e))?; + rows.into_iter() + .map( + |(id, secret, account_id, user_name, created)| StoredSecretRow { + table, + key: id.clone(), + access_key_id: id, + account_id, + principal_name: user_name, + session_name: None, + expires_at: None, + created_at: Some(created), + secret_key_encrypted: secret, + write_timestamp: None, + }, + ) + .collect() + } + SecretTable::IamSessions => { + let rows: Vec = sqlx::query_as( + "SELECT session_token, access_key_id, secret_key_encrypted, account_id, \ + role_name, session_name, expires_at, created_at FROM iam_sessions \ + WHERE $1::text IS NULL OR session_token > $1 \ + ORDER BY session_token LIMIT $2", + ) + .bind(page) + .bind(limit) + .fetch_all(self.pool()) + .await + .map_err(|e| database_error("read_secret_page", &e))?; + rows.into_iter() + .map( + |(token, id, secret, account_id, role, session, expires, created)| { + StoredSecretRow { + table, + key: token, + access_key_id: id, + account_id, + principal_name: role, + session_name: Some(session), + expires_at: Some(expires.unix_timestamp()), + created_at: Some(created), + secret_key_encrypted: secret, + write_timestamp: None, + } + }, + ) + .collect() + } + }; + let next = (rows.len() == page_size) + .then(|| rows.last().map(|row| row.key.clone())) + .flatten(); + Ok(SecretPage { rows, next }) + } + + /// One `UPDATE ... FROM (VALUES ...)` by primary key. A key that matches + /// no row changes nothing. + pub(crate) async fn write_secrets_impl( + &self, + table: SecretTable, + rows: &[SecretWrite], + ) -> OpResult<()> { + if rows.is_empty() { + return Ok(()); + } + let mut update = sqlx::QueryBuilder::::new(format!( + "UPDATE {} AS t SET secret_key_encrypted = v.secret FROM (", + table.name() + )); + update.push_values(rows, |mut values, row| { + values + .push_bind(row.key.as_str()) + .push_unseparated("::text") + .push_bind(row.secret_key_encrypted.as_slice()) + .push_unseparated("::bytea"); + }); + update.push(format!( + ") AS v(key, secret) WHERE t.{} = v.key", + table.key_column() + )); + update + .build() + .execute(self.pool()) + .await + .map_err(|e| database_error("write_secrets", &e))?; + Ok(()) + } + + pub(crate) async fn delete_secrets_impl( + &self, + table: SecretTable, + keys: &[String], + ) -> OpResult<()> { + sqlx::query(&format!( + "DELETE FROM {} WHERE {} = ANY($1)", + table.name(), + table.key_column() + )) + .bind(keys) + .execute(self.pool()) + .await + .map_err(|e| database_error("delete_secrets", &e))?; + Ok(()) + } + + pub(crate) async fn delete_setting_impl(&self, key: &str) -> OpResult<()> { + sqlx::query("DELETE FROM settings WHERE key = $1") + .bind(key) + .execute(self.pool()) + .await + .map_err(|e| database_error("delete_setting", &e))?; + Ok(()) + } + + /// `encryption-key set-data-connection`: in one transaction, read the + /// key ring `FOR SHARE`, open its DEK with `kek`, and write + /// `connection_string` into the `data_database_connection_string` row, + /// encrypted under that DEK. A `rotate` that writes the ring waits for + /// the commit, or this sees its two DEKs and refuses. + /// + /// # Errors + /// + /// [`OpError::Validation`] for a string that is not a PostgreSQL + /// connection string, a catalog without a ring, a ring with an + /// unfinished switch or two DEKs, or a ring the KEK does not open; a + /// database error otherwise. + pub(crate) async fn set_data_connection_impl( + &self, + kek: &[u8; 32], + connection_string: &str, + ) -> OpResult<()> { + // `serve` opens this row with sqlx's parser, and `migrate` and + // `verify` with the parser that the command runs first. The two + // grammars differ, so a string must pass both. + connection_string.parse::().map_err(|e| { + OpError::Validation(format!( + "the data database connection string is not a PostgreSQL connection \ + string: {e}" + )) + })?; + let mut tx = self + .pool() + .begin() + .await + .map_err(|e| database_error("set_data_connection", &e))?; + let ring: Option = + sqlx::query_scalar("SELECT value FROM settings WHERE key = $1 FOR SHARE") + .bind(KEY_RING_SETTING) + .fetch_optional(&mut *tx) + .await + .map_err(|e| database_error("set_data_connection", &e))?; + let catalog_id: Option = + sqlx::query_scalar("SELECT value FROM settings WHERE key = $1") + .bind(CATALOG_ID_SETTING) + .fetch_optional(&mut *tx) + .await + .map_err(|e| database_error("set_data_connection", &e))?; + let catalog_id = catalog_id.ok_or_else(|| { + OpError::Validation( + "the catalog has no catalog_id row; run extenddb migrate --yes first".to_owned(), + ) + })?; + let dek = + data_connection_key(ring.as_deref(), kek, &catalog_id).map_err(OpError::Validation)?; + let sealed = dek + .encrypt_setting(connection_string) + .map_err(|e| OpError::Internal(format!("set_data_connection: {e}")))?; + sqlx::query( + "INSERT INTO settings (key, value) VALUES ($1, $2) \ + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", + ) + .bind(DATA_CONNECTION_SETTING) + .bind(&sealed) + .execute(&mut *tx) + .await + .map_err(|e| database_error("set_data_connection", &e))?; + tx.commit() + .await + .map_err(|e| database_error("set_data_connection", &e)) + } +} diff --git a/crates/storage-postgres/src/migrations/backend.rs b/crates/storage-postgres/src/migrations/backend.rs index 2924fa23f..c6f0186ad 100644 --- a/crates/storage-postgres/src/migrations/backend.rs +++ b/crates/storage-postgres/src/migrations/backend.rs @@ -21,10 +21,10 @@ //! checked. use async_trait::async_trait; -use extenddb_storage::management_store::ManagementStore; +use extenddb_storage::management_store::{ManagementStore, SettingsStore}; use extenddb_storage::migrations::{ - CatalogTraces, Done, HasManagementStore, LedgerColumns, LedgerRow, LedgerWrites, Migration, - MigrationBackend, MigrationError, MigrationId, Released, Step, StoreKind, StoreRef, + CatalogTraces, Done, HasManagementStore, LedgerColumns, LedgerRow, LedgerWrites, LockedStores, + Migration, MigrationBackend, MigrationError, MigrationId, Released, Step, StoreKind, StoreRef, in_transaction, record_rows, }; use sqlx::PgPool; @@ -102,6 +102,28 @@ impl HasManagementStore for PostgresStores { } } +/// The catalog's stores under a held migration lock, for `encryption-key +/// switch`, `rotate` and `reset` (RFC-0000 section 8, common rules): the +/// management store over the runner's catalog connection, holding no key. +/// Dropping it closes the runner's connections. +pub(crate) struct LockedCatalog(PostgresMigrations); + +impl LockedCatalog { + pub(crate) fn new(migrations: PostgresMigrations) -> Self { + Self(migrations) + } +} + +impl LockedStores for LockedCatalog { + fn management(&self) -> &dyn ManagementStore { + &self.0.stores.management + } + + fn settings(&self) -> &dyn SettingsStore { + &self.0.stores.management + } +} + /// How long each statement of a body waits for a table lock. const LOCK_TIMEOUT_SECS: u64 = 5; @@ -124,6 +146,9 @@ pub struct PostgresMigrations { read_only: bool, /// Whether each database accepts [`CONNECTION_CHECK`]: catalog, data. connection_check: [bool; 2], + /// A status session of the catalog store alone: no data store is listed, + /// and `stores.data` is the catalog's connection, which no read reaches. + catalog_store_alone: bool, } impl PostgresMigrations { @@ -203,6 +228,26 @@ impl PostgresMigrations { )) } })?; + if read_only && target.catalog_store_alone { + // The status of the catalog store alone reaches no data database, + // so the data connection string row is not read. + return Ok(Self { + stores: PostgresStores { + management: PostgresCatalogStore::new(catalog.clone()), + data: catalog.clone(), + catalog, + data_watch: None, + lock, + application, + }, + catalog_name, + data_name: String::new(), + data_connection_row: None, + read_only, + connection_check: [false; 2], + catalog_store_alone: true, + }); + } let data_options = match served_data(target, &catalog).await { Ok(options) => options, Err(e) => { @@ -283,6 +328,7 @@ impl PostgresMigrations { data_connection_row: target.data_connection_row.clone(), read_only, connection_check, + catalog_store_alone: false, }) } @@ -292,7 +338,9 @@ impl PostgresMigrations { pub async fn close(self) { if self.read_only { let _ = exec(&self.stores.catalog, "ROLLBACK").await; - let _ = exec(&self.stores.data, "ROLLBACK").await; + if !self.catalog_store_alone { + let _ = exec(&self.stores.data, "ROLLBACK").await; + } } self.stores.catalog.close().await; self.stores.data.close().await; @@ -457,6 +505,7 @@ impl MigrationBackend for PostgresMigrations { async fn store_names(&self, kind: StoreKind) -> Result, MigrationError> { Ok(match kind { StoreKind::Catalog => vec![self.catalog_name.clone()], + StoreKind::Data if self.catalog_store_alone => Vec::new(), StoreKind::Data => vec![self.data_name.clone()], StoreKind::Account => Vec::new(), }) diff --git a/crates/storage-postgres/src/migrations/commands.rs b/crates/storage-postgres/src/migrations/commands.rs index dc7822f49..eee836448 100644 --- a/crates/storage-postgres/src/migrations/commands.rs +++ b/crates/storage-postgres/src/migrations/commands.rs @@ -17,12 +17,12 @@ use std::time::Duration; use async_trait::async_trait; use extenddb_storage::migrations::{ - AdminRole, CatalogMigrations, CatalogStatus, HeldLock, LedgerRow, Listed, MigrationError, - MigrationId, RunKind, RunReport, Runner, StatusNote, StoreKind, Target, + AdminRole, CatalogMigrations, CatalogStatus, HeldLock, LedgerRow, Listed, LockedStores, + MigrationError, MigrationId, RunKind, RunReport, Runner, StatusNote, StoreKind, Target, }; use sqlx::postgres::PgConnectOptions; -use super::backend::{OpenError, PostgresMigrations}; +use super::backend::{LockedCatalog, OpenError, PostgresMigrations}; use super::connect::{missing_database, one_connection, relation_exists, sql_error}; use super::sessions::denied_with_notes; use super::{MigrationLock, PostgresTarget, catalog_status, migrate_holding}; @@ -95,6 +95,19 @@ impl CatalogMigrations for PostgresCatalogMigrations { explain_denied(target, status.await).await } + /// The status of the catalog database alone: its ledger and settings. + /// No data database is reached, so no `data_database_connection_string` + /// row is read. + async fn catalog_store_status(&self, target: &Target) -> Result { + match resolve(target).await? { + Some(mut target) => { + target.catalog_store_alone = true; + catalog_status(&target).await + } + None => Ok(CatalogStatus::Uninitialized), + } + } + async fn catalog_ledger(&self, target: &Target) -> Result, MigrationError> { let rows = async { let Some(target) = resolve(target).await? else { @@ -184,6 +197,25 @@ impl CatalogMigrations for PostgresCatalogMigrations { result } + /// The management store over the runner's catalog connection, opened + /// as `migrate --yes` opens it. The lock's target carries the key the + /// command read, which opens the data connection string row of a + /// catalog with a key ring; `data_connection` (`reset`) takes the place + /// of that row. + async fn locked_stores( + &self, + lock: &HeldLock, + data_connection: Option<&str>, + ) -> Result, MigrationError> { + let held = held(lock)?; + let target = match data_connection { + Some(connection) => held.target.clone().with_given_data_connection(connection), + None => held.target.clone(), + }; + let migrations = PostgresMigrations::open(&target, &held.lock).await?; + Ok(Box::new(LockedCatalog::new(migrations))) + } + async fn status_notes(&self, target: &Target) -> Result, MigrationError> { let notes = async { match resolve(target).await? { @@ -247,21 +279,36 @@ fn no_catalog_database(catalog: &PgConnectOptions) -> MigrationError { /// The databases `target` names, or `None` when its catalog database does /// not exist. Reads the `data_database_name` row on a read-only connection. +/// The result carries the key the command read (`target.key_source`), which +/// opens the data connection string row of a catalog with a key ring, and +/// for `encryption-key switch` alone (`target.plaintext_data_connection`) +/// accepts the plaintext row of an unfinished switch. A data store +/// connection string on the target (`init`'s, which migration 1 records, or +/// the one `encryption-key reset` reads from standard input, RFC-0000 +/// section 8.6) reaches the data database in place of the row. /// /// # Errors /// /// The connection string is not a PostgreSQL URL, or the catalog cannot be /// reached or read. pub async fn resolve(target: &Target) -> Result, MigrationError> { + let keyed = |resolved: PostgresTarget| { + let resolved = + resolved.with_key_source(target.key_source.clone(), target.plaintext_data_connection); + match &target.data_connection { + Some(connection) => resolved.with_given_data_connection(connection), + None => resolved, + } + }; let catalog = catalog_options(target)?; let catalog_db = catalog.get_database().unwrap_or("postgres").to_owned(); if let Some(data) = &target.data_store { // Given on the command line (`--data-db`, or the name `init` // resolved), so it wins over the database the catalog's connection // string row names, on that row's server. - return Ok(Some( + return Ok(Some(keyed( PostgresTarget::new(catalog, data.clone()).with_given_data_database(), - )); + ))); } let fallback = crate::bootstrapper::derive_data_db_name(&catalog_db); let pool = match one_connection(catalog.clone(), true, Duration::from_secs(10)).await { @@ -288,7 +335,7 @@ pub async fn resolve(target: &Target) -> Result, Migratio .await; pool.close().await; let data = recorded?.unwrap_or(fallback); - Ok(Some(PostgresTarget::new(catalog, data))) + Ok(Some(keyed(PostgresTarget::new(catalog, data)))) } /// The admin role's connection on the server of `data`, the data database diff --git a/crates/storage-postgres/src/migrations/connection_row.rs b/crates/storage-postgres/src/migrations/connection_row.rs new file mode 100644 index 000000000..f2dbff4eb --- /dev/null +++ b/crates/storage-postgres/src/migrations/connection_row.rs @@ -0,0 +1,100 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use extenddb_storage::key_ring::{KEY_RING_SETTING, open_ring}; +use extenddb_storage::migrations::MigrationError; +use extenddb_storage::secret_keys::{CATALOG_ID_SETTING, DATA_CONNECTION_SETTING}; +use sqlx::PgPool; +use zeroize::Zeroizing; + +use super::connect::{relation_exists, sql_error}; +use super::{DataKey, PostgresTarget}; + +/// The catalog's `data_database_connection_string` row as the server +/// connects with it; `None` when the catalog has no settings table, or no +/// such row and no key ring. +/// +/// A catalog without a key ring keeps the row in plaintext. In a catalog +/// with a ring the row is encrypted under the ring's DEK, and `target`'s key +/// opens it before anything parses it (RFC-0000 section 12): a missing row, +/// a row that no DEK of the ring opens, and a plaintext row are refused, +/// except the plaintext row of an unfinished switch, which only the backend +/// that `encryption-key switch` opens accepts. A connection string that +/// `encryption-key reset` read from standard input takes the place of the +/// row, whatever the catalog holds. +pub(super) async fn connection_row( + target: &PostgresTarget, + catalog: &PgPool, +) -> Result>, MigrationError> { + if let DataKey::Given(given) = &target.data_key { + return Ok(Some((**given).clone())); + } + if !relation_exists(catalog, "settings").await? { + return Ok(None); + } + let rows: Vec<(String, String)> = + sqlx::query_as("SELECT key, value FROM settings WHERE key IN ($1, $2, $3)") + .bind(DATA_CONNECTION_SETTING) + .bind(KEY_RING_SETTING) + .bind(CATALOG_ID_SETTING) + .fetch_all(catalog) + .await + .map_err(|e| sql_error("read data_database_connection_string", &e))?; + let value = |key: &str| rows.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()); + let row = value(DATA_CONNECTION_SETTING); + match value(KEY_RING_SETTING) { + None => Ok(row.map(|r| Zeroizing::new(r.to_owned()))), + Some(ring) => open_connection_row(&target.data_key, row, ring, value(CATALOG_ID_SETTING)) + .map(Some) + .map_err(MigrationError::Refused), + } +} + +/// [`connection_row`] for a catalog with the key ring `ring`. +fn open_connection_row( + key: &DataKey, + row: Option<&str>, + ring: &str, + catalog_id: Option<&str>, +) -> Result, String> { + const UNOPENED: &str = "the catalog's data_database_connection_string row does not open \ + under the DEK of its key ring, so the data database's password cannot be read; run \ + extenddb encryption-key status, and write the connection string with extenddb \ + encryption-key set-data-connection"; + let Some(row) = row.filter(|r| !r.is_empty()) else { + return Err( + "the catalog has a key ring and no data_database_connection_string row; \ + write the data database's connection string with extenddb encryption-key \ + set-data-connection" + .to_owned(), + ); + }; + match key { + DataKey::None => Err( + "the catalog has a key ring, so its data_database_connection_string row is \ + encrypted; run the command with the configuration whose [auth.encryption] \ + key_file names the KEK of the ring" + .to_owned(), + ), + DataKey::Loaded(keys) => keys.decrypt_setting(row).map_err(|_| UNOPENED.to_owned()), + // `connection_row` returns the given string before it reads a row. + DataKey::Given(given) => Ok((**given).clone()), + DataKey::Kek { + kek, + plaintext_during_switch, + } => { + let open = open_ring(ring, catalog_id, kek).map_err(|refusal| refusal.to_string())?; + if let Some(opened) = open + .deks + .iter() + .find_map(|dek| dek.decrypt_setting(row).ok()) + { + return Ok(opened); + } + if *plaintext_during_switch && open.ring.switch_from_catalog_key { + return Ok(Zeroizing::new(row.to_owned())); + } + Err(UNOPENED.to_owned()) + } + } +} diff --git a/crates/storage-postgres/src/migrations/mod.rs b/crates/storage-postgres/src/migrations/mod.rs index 295e523e1..ac3bbf63d 100644 --- a/crates/storage-postgres/src/migrations/mod.rs +++ b/crates/storage-postgres/src/migrations/mod.rs @@ -23,6 +23,7 @@ mod backend; mod commands; mod connect; +mod connection_row; mod failure; mod held; mod index_helper; @@ -44,9 +45,11 @@ mod rows; mod sessions; mod vector_extension; +use std::sync::Arc; use std::time::Duration; use extenddb_storage::file_body; +use extenddb_storage::key_ring::Kek; use extenddb_storage::migrations::m0002_resource_tag_condition_keys::{ self, ResourceTagConditionKeys, }; @@ -54,7 +57,10 @@ use extenddb_storage::migrations::{ CatalogStatus, Kind, Migration, MigrationBackend, MigrationError, MigrationId, Released, RunReport, Runner, StatusNote, StoreBody, StoreKind, }; +use extenddb_storage::secret_keys::SecretKeys; +use extenddb_storage::server_components::KeySource; use sqlx::postgres::PgConnectOptions; +use zeroize::Zeroizing; pub use backend::{PostgresMigrations, PostgresStores}; pub use commands::{PostgresCatalogMigrations, resolve}; @@ -62,7 +68,7 @@ pub use locks::{KEEPALIVE_INTERVAL, MigrationLock, SERVE_APPLICATION, ServingReg #[cfg(feature = "test-util")] pub use postcheck::{Column, Definitions, Index, compare, describe}; pub use registrar::ServerRegistration; -pub use sessions::{require_data_connection_row, served_data_options}; +pub use sessions::{data_connection_string, require_data_connection_row, served_data_options}; pub use vector_extension::try_create_vector_extension; /// The definitions migration 1 creates in an empty catalog database, which @@ -371,7 +377,9 @@ pub(crate) const fn runs_in(id: MigrationId) -> RunsIn { /// `data_database_connection_string` row, which the server connects with, /// when the catalog has it, and refuses when that row names another database /// than `data_database` unless `data_database_given`; without the row it -/// uses the catalog's server and credentials with `data_database`. +/// uses the catalog's server and credentials with `data_database`. In a +/// catalog with a key ring the row is encrypted under the ring's DEK, and +/// `data_key` opens it. #[derive(Debug, Clone)] pub struct PostgresTarget { /// The catalog database, with the credentials the command was given. @@ -386,6 +394,52 @@ pub struct PostgresTarget { pub data_connection_row: Option, /// Timeout for each connection attempt. pub(crate) connect_timeout: Duration, + /// What opens the connection string row of a catalog with a key ring. + pub(crate) data_key: DataKey, + /// Whether a status read covers the catalog store alone, reaching no + /// data database ([`PostgresMigrations::open_for_status`]). + pub(crate) catalog_store_alone: bool, +} + +/// What opens the `data_database_connection_string` row of a catalog with a +/// key ring (RFC-0000 section 12). A catalog without a ring keeps the row in +/// plaintext, and every variant reads it as it is. +#[derive(Clone, Default)] +pub(crate) enum DataKey { + /// No key: a catalog with a ring is refused. + #[default] + None, + /// The KEK the command read: each read unwraps the ring with it and + /// opens the row with a DEK of the ring. `plaintext_during_switch` + /// accepts the plaintext row while the ring's `switch_from_catalog_key` + /// is true, for `encryption-key switch` alone. + Kek { + kek: Kek, + plaintext_during_switch: bool, + }, + /// The key holder the server's registration loaded. + Loaded(Arc), + /// The connection string the command read from standard input + /// (`encryption-key reset`, RFC-0000 section 8.6), in place of the row, + /// which no key of the run opens. + Given(Arc>), +} + +impl std::fmt::Debug for DataKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::None => f.write_str("None"), + Self::Kek { + plaintext_during_switch, + .. + } => write!( + f, + "Kek {{ plaintext_during_switch: {plaintext_during_switch} }}" + ), + Self::Loaded(keys) => write!(f, "Loaded({keys:?})"), + Self::Given(_) => f.write_str("Given(..)"), + } + } } impl PostgresTarget { @@ -399,9 +453,45 @@ impl PostgresTarget { data_database_given: false, data_connection_row: None, connect_timeout: Duration::from_secs(10), + data_key: DataKey::None, + catalog_store_alone: false, } } + /// Open the connection string row of a catalog with a key ring with the + /// key the command read: a KEK, which unwraps the ring at each read. The + /// catalog key and no key open no such row. `plaintext_during_switch` is + /// for `encryption-key switch` alone: it accepts the plaintext row while + /// the ring's `switch_from_catalog_key` is true. + #[must_use] + pub fn with_key_source(mut self, key_source: KeySource, plaintext_during_switch: bool) -> Self { + self.data_key = match key_source { + KeySource::Kek(kek) => DataKey::Kek { + kek, + plaintext_during_switch, + }, + KeySource::CatalogKey | KeySource::None => DataKey::None, + }; + self + } + + /// Open the connection string row of a catalog with a key ring with a + /// key holder already loaded, as the server's registration does. + #[must_use] + pub fn with_secret_keys(mut self, keys: Arc) -> Self { + self.data_key = DataKey::Loaded(keys); + self + } + + /// Reach the data database with `connection_string` in place of the + /// catalog's row, which `encryption-key reset` reads from standard input + /// because no key of the run opens the row (RFC-0000 section 8.6). + #[must_use] + pub fn with_given_data_connection(mut self, connection_string: &str) -> Self { + self.data_key = DataKey::Given(Arc::new(Zeroizing::new(connection_string.to_owned()))); + self + } + /// Mark the data database as given on the command line. #[must_use] pub fn with_given_data_database(mut self) -> Self { diff --git a/crates/storage-postgres/src/migrations/registrar.rs b/crates/storage-postgres/src/migrations/registrar.rs index f45e18fa0..bc4a50eb2 100644 --- a/crates/storage-postgres/src/migrations/registrar.rs +++ b/crates/storage-postgres/src/migrations/registrar.rs @@ -16,25 +16,32 @@ //! status the server started with; otherwise a migration ran in between, //! and the server stops. -use std::sync::{Mutex, PoisonError}; +use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; use async_trait::async_trait; use extenddb_storage::hooks::{Reregistration, ServingRegistrar}; use extenddb_storage::migrations::{CatalogStatus, MigrationError, Target}; +use extenddb_storage::secret_keys::SecretKeys; +use extenddb_storage::server_components::{BackendError, KeySource, load_secret_keys}; +use zeroize::Zeroizing; use super::locks::{KEEPALIVE_INTERVAL, SERVE_APPLICATION, ServingRegistration}; +use super::sessions::{close_status, status_session}; use super::{PostgresTarget, catalog_status, require_data_connection_row, resolve}; +use crate::catalog_store::PostgresCatalogStore; /// The serving registration of a running server, with what it needs to /// take it again: the catalog's databases, the status the server started -/// with, and the name its session carries. +/// with, and the name its session carries; and the key holder loaded under +/// it, which the server's stores share. pub struct ServerRegistration { target: PostgresTarget, started: CatalogStatus, keepalive: Duration, application: &'static str, current: Mutex, + keys: Option>, } impl ServerRegistration { @@ -103,24 +110,80 @@ impl ServerRegistration { keepalive: Duration, application: &'static str, ) -> Result { - let Some(target) = resolve(&Target::at(connection_string)).await? else { - return Err(MigrationError::Status(CatalogStatus::Uninitialized)); + Self::register_loading(connection_string, keepalive, application, KeySource::None) + .await + .map_err(|e| match e { + BackendError::Catalog(e) => e, + other => MigrationError::Refused(other.to_string()), + }) + } + + /// [`ServerRegistration::register_as`] for the server factory, which + /// also loads the key (RFC-0000 sections 7 and 12): after the serving + /// key is taken and before the status is read, the key rows are read + /// and `key_source` loads the one key holder that serves the status + /// read, the data database's connection string and the stores. A KEK + /// in `key_source` is wiped when the load returns. + /// + /// # Errors + /// + /// The refusals of [`load_secret_keys`], and those of + /// [`ServerRegistration::register`] as [`BackendError::Catalog`]. + pub async fn register_keyed( + connection_string: &str, + application: &'static str, + key_source: KeySource, + ) -> Result { + Self::register_loading( + connection_string, + KEEPALIVE_INTERVAL, + application, + key_source, + ) + .await + } + + async fn register_loading( + connection_string: &str, + keepalive: Duration, + application: &'static str, + key_source: KeySource, + ) -> Result { + let Some(target) = resolve(&Target::at(connection_string)) + .await + .map_err(BackendError::Catalog)? + else { + return Err(BackendError::Catalog(MigrationError::Status( + CatalogStatus::Uninitialized, + ))); }; let registration = ServingRegistration::register_keepalive(&target.catalog, keepalive, application) - .await?; + .await + .map_err(BackendError::Catalog)?; + let keys = match load_keys(&target, key_source).await { + Ok(keys) => keys, + Err(e) => { + registration.release().await; + return Err(e); + } + }; + let target = match &keys { + Some(keys) => target.with_secret_keys(Arc::clone(keys)), + None => target, + }; let status = match catalog_status(&target).await { Ok(status) => status, Err(e) => { registration.release().await; - return Err(e); + return Err(BackendError::Catalog(e)); } }; match status { CatalogStatus::Current { .. } | CatalogStatus::AheadCompatible { .. } => { if let Err(e) = require_data_connection_row(&target).await { registration.release().await; - return Err(e); + return Err(BackendError::Catalog(e)); } if matches!(status, CatalogStatus::AheadCompatible { .. }) { tracing::warn!( @@ -134,14 +197,52 @@ impl ServerRegistration { keepalive, application, current: Mutex::new(registration), + keys, }) } status => { registration.release().await; - Err(MigrationError::Status(status)) + Err(BackendError::Catalog(MigrationError::Status(status))) } } } + + /// The key holder loaded under this registration, or `None` when it + /// was taken with `KeySource::None`. + #[must_use] + pub fn secret_keys(&self) -> Option> { + self.keys.clone() + } + + /// The catalog's data database connection string, opened with the key + /// holder of this registration in a catalog with a key ring; `None` + /// when the catalog has no such row. + /// + /// # Errors + /// + /// The catalog cannot be read, or the key holder does not open the row. + pub async fn data_connection_string( + &self, + ) -> Result>, MigrationError> { + super::data_connection_string(&self.target).await + } +} + +/// Load the key holder of `key_source` from the catalog's key rows, on a +/// read-only session of its own. `KeySource::None` opens no session. +async fn load_keys( + target: &PostgresTarget, + key_source: KeySource, +) -> Result>, BackendError> { + if matches!(key_source, KeySource::None) { + return Ok(None); + } + let pool = status_session(&target.catalog, target.connect_timeout) + .await + .map_err(BackendError::Catalog)?; + let keys = load_secret_keys(&PostgresCatalogStore::new(pool.clone()), key_source).await; + close_status(pool).await; + keys } #[async_trait] diff --git a/crates/storage-postgres/src/migrations/sessions.rs b/crates/storage-postgres/src/migrations/sessions.rs index aa6fb12b3..cc7bcb02c 100644 --- a/crates/storage-postgres/src/migrations/sessions.rs +++ b/crates/storage-postgres/src/migrations/sessions.rs @@ -30,9 +30,11 @@ use std::time::{Duration, Instant}; use extenddb_storage::migrations::{MigrationError, MigrationId, StatusNote, StoreKind, StoreRef}; use sqlx::PgPool; use sqlx::postgres::PgConnectOptions; +use zeroize::Zeroizing; use super::PostgresTarget; -use super::connect::{RUNNER_APPLICATION_PREFIX, one_connection, relation_exists, sql_error}; +use super::connect::{RUNNER_APPLICATION_PREFIX, one_connection, sql_error}; +use super::connection_row::connection_row; /// How often the wait for an earlier runner looks again. const POLL: Duration = Duration::from_millis(200); @@ -131,18 +133,6 @@ pub(crate) async fn wait_for_earlier_runners( } } -/// The catalog's `data_database_connection_string` row; `None` when the -/// catalog has no settings table or no such row. -async fn connection_row(catalog: &PgPool) -> Result, MigrationError> { - if !relation_exists(catalog, "settings").await? { - return Ok(None); - } - sqlx::query_scalar("SELECT value FROM settings WHERE key = 'data_database_connection_string'") - .fetch_optional(catalog) - .await - .map_err(|e| sql_error("read data_database_connection_string", &e)) -} - /// A status session (read-only, named `extenddb status`) on `options`. pub(crate) async fn status_session( options: &PgConnectOptions, @@ -168,9 +158,11 @@ pub(crate) async fn close_status(pool: PgPool) { } /// [`connection_row`] on a status session of its own. -async fn read_connection_row(target: &PostgresTarget) -> Result, MigrationError> { +async fn read_connection_row( + target: &PostgresTarget, +) -> Result>, MigrationError> { let pool = status_session(&target.catalog, target.connect_timeout).await?; - let row = connection_row(&pool).await; + let row = connection_row(target, &pool).await; close_status(pool).await; row } @@ -180,23 +172,25 @@ async fn read_connection_row(target: &PostgresTarget) -> Result, /// when the catalog has the row; otherwise the catalog's server and /// credentials with the target's data database. A target whose data /// database was given on the command line keeps that name on the row's -/// server. +/// server. In a catalog with a key ring the row is opened first +/// ([`connection_row`]). /// /// # Errors /// /// The row is not a PostgreSQL URL, or it names another data database than -/// the target's, which was not given on the command line. +/// the target's, which was not given on the command line, or the catalog +/// has a key ring and the target's key does not open the row. pub(crate) async fn served_data( target: &PostgresTarget, catalog: &PgPool, ) -> Result { - served_from(target, connection_row(catalog).await?) + served_from(target, connection_row(target, catalog).await?.as_deref()) } /// [`served_data`] from the row's value. fn served_from( target: &PostgresTarget, - row: Option, + row: Option<&String>, ) -> Result { let Some(row) = row.filter(|r| !r.is_empty()) else { return Ok(target.data()); @@ -233,7 +227,20 @@ fn served_from( pub async fn served_data_options( target: &PostgresTarget, ) -> Result { - served_from(target, read_connection_row(target).await?) + served_from(target, read_connection_row(target).await?.as_deref()) +} + +/// The catalog's data database connection string as the server connects +/// with it, opened with the target's key in a catalog with a key ring +/// ([`connection_row`]); `None` when the catalog has no such row. +/// +/// # Errors +/// +/// As [`connection_row`], or the catalog cannot be reached. +pub async fn data_connection_string( + target: &PostgresTarget, +) -> Result>, MigrationError> { + read_connection_row(target).await } /// For the server: refuse a catalog with no `data_database_connection_string` @@ -242,9 +249,10 @@ pub async fn served_data_options( /// /// # Errors /// -/// The row is missing or empty, or the catalog cannot be read. +/// The row is missing or empty, the catalog cannot be read, or the catalog +/// has a key ring and the target's key does not open the row. pub async fn require_data_connection_row(target: &PostgresTarget) -> Result<(), MigrationError> { - match read_connection_row(target).await? { + match read_connection_row(target).await?.as_deref() { Some(value) if !value.is_empty() => Ok(()), _ => Err(MigrationError::Refused(format!( "the catalog database {} has no data_database_connection_string row, which \ diff --git a/crates/storage-postgres/tests/backup_restore.rs b/crates/storage-postgres/tests/backup_restore.rs index 4c29544a8..b35539928 100644 --- a/crates/storage-postgres/tests/backup_restore.rs +++ b/crates/storage-postgres/tests/backup_restore.rs @@ -5669,11 +5669,15 @@ mod catalog_index { put_indexed_items(&s, "gq_src", &desc, 1).await; assert_eq!(pending().await, 1, "the write queued its index update"); - // The factory reads the encryption key `init` writes. + // The factory reads the encryption key `init` writes, and refuses + // one that is not 32 bytes in base64. + let key = extenddb_storage::bootstrapper::helpers::generate_encryption_key() + .expect("generate key"); sqlx::query( - "INSERT INTO settings (key, value) VALUES ('encryption_key', 'test-key') \ + "INSERT INTO settings (key, value) VALUES ('encryption_key', $1) \ ON CONFLICT (key) DO NOTHING", ) + .bind(&key) .execute(&s.catalog) .await .expect("encryption key"); diff --git a/crates/storage-postgres/tests/key_ring_rows.rs b/crates/storage-postgres/tests/key_ring_rows.rs new file mode 100644 index 000000000..5c10d64ab --- /dev/null +++ b/crates/storage-postgres/tests/key_ring_rows.rs @@ -0,0 +1,545 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The catalog rows of a deployment that uses a KEK file: the +//! `data_database_connection_string` row under the key ring (RFC-0000 +//! section 12), and the store methods the encryption-key commands rewrite +//! the stored secrets with (section 8.4). See `migrations_support` for the +//! database these tests need. + +mod migrations_support; +#[path = "key_ring_rows/pass_methods.rs"] +mod pass_methods; + +use std::sync::Arc; + +use extenddb_storage::diagnostics::DiagnosticsStore; +use extenddb_storage::key_ring::{KEY_RING_SETTING, KeyRing, catalog_key_id}; +use extenddb_storage::management_store::{ + ManagementStore, SecretWrite, SettingsStore, StoredSecretRow, +}; +use extenddb_storage::migrations::{CatalogStatus, MigrationError, MigrationId}; +use extenddb_storage::secret_keys::{SecretKeys, SecretRow, SecretTable}; +use extenddb_storage::server_components::KeySource; +use extenddb_storage_postgres::PostgresCatalogStore; +use extenddb_storage_postgres::migrations::{catalog_status, data_connection_string}; +use migrations_support::{ACCOUNT, LATEST, Scratch, base_conn, skip}; +use sqlx::PgPool; +use zeroize::Zeroizing; + +const KEK: [u8; 32] = [3; 32]; +const OTHER_KEK: [u8; 32] = [4; 32]; +const CATALOG_KEY: &str = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="; + +async fn installed(base: &str, prefix: &str) -> Scratch { + let s = Scratch::new(base, prefix).await; + s.migrate_through(MigrationId::LATEST).await; + s +} + +async fn set_row(catalog: &PgPool, key: &str, value: Option<&str>) { + match value { + Some(value) => sqlx::query( + "INSERT INTO settings (key, value) VALUES ($1, $2) \ + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", + ) + .bind(key) + .bind(value) + .execute(catalog) + .await + .expect("write a settings row"), + None => sqlx::query("DELETE FROM settings WHERE key = $1") + .bind(key) + .execute(catalog) + .await + .expect("delete a settings row"), + }; +} + +/// The key a case's target carries. +#[derive(Clone, Copy, Debug)] +enum Key { + None, + Kek, + KekDuringSwitch, + OtherKek, + Loaded, +} + +/// The ring a case's catalog holds. +#[derive(Clone, Copy, Debug)] +enum Ring { + Absent, + Switching, + Finished, +} + +/// The `data_database_connection_string` row of a case. +#[derive(Clone, Copy, Debug)] +enum Row { + Plaintext, + Encrypted, + NotAUrl, + Absent, +} + +/// Every reader of the row (the status read, the registration, `migrate`) +/// opens it the same way: plaintext without a ring; with a ring, only under +/// a DEK of the ring, except the plaintext row of an unfinished switch, +/// which only the switch's own backend accepts. +#[tokio::test] +async fn the_data_connection_row_opens_by_the_ring_and_the_target_key() { + let Some(base) = base_conn() else { + return skip("data connection row under the key ring"); + }; + let s = installed(&base, "pgk_dataconn").await; + let catalog = s.catalog().await; + let catalog_id: String = + sqlx::query_scalar("SELECT value FROM settings WHERE key = 'catalog_id'") + .fetch_one(&catalog) + .await + .expect("migration 6 writes the catalog id"); + let dek = Arc::new(SecretKeys::dek_for_tests([5; 32], 1, &catalog_id)); + let catalog_key = SecretKeys::catalog_key(CATALOG_KEY).expect("a catalog key"); + let ring = |switching: bool| { + let retiring = switching.then(|| catalog_key_id(&KEK, &catalog_key)); + KeyRing::seal(&KEK, &catalog_id, &[&dek], switching, retiring) + .expect("seal the ring") + .to_json() + }; + let url = s.data_url(); + let encrypted = dek.encrypt_setting(&url).expect("encrypt the row"); + + let (opens, refused) = (true, false); + let cases: &[(&str, Ring, Row, Key, bool)] = &[ + ( + "no ring, plaintext", + Ring::Absent, + Row::Plaintext, + Key::None, + opens, + ), + ( + "switching, plaintext, the switch", + Ring::Switching, + Row::Plaintext, + Key::KekDuringSwitch, + opens, + ), + ( + "switching, plaintext, another command", + Ring::Switching, + Row::Plaintext, + Key::Kek, + refused, + ), + ( + "switching, plaintext, no key", + Ring::Switching, + Row::Plaintext, + Key::None, + refused, + ), + ( + "switching, encrypted, the switch", + Ring::Switching, + Row::Encrypted, + Key::KekDuringSwitch, + opens, + ), + ( + "finished, encrypted, a command", + Ring::Finished, + Row::Encrypted, + Key::Kek, + opens, + ), + ( + "finished, encrypted, the server", + Ring::Finished, + Row::Encrypted, + Key::Loaded, + opens, + ), + ( + "finished, encrypted, no key", + Ring::Finished, + Row::Encrypted, + Key::None, + refused, + ), + ( + "finished, encrypted, another KEK", + Ring::Finished, + Row::Encrypted, + Key::OtherKek, + refused, + ), + ( + "finished, plaintext, the switch", + Ring::Finished, + Row::Plaintext, + Key::KekDuringSwitch, + refused, + ), + ( + "finished, plaintext, the server", + Ring::Finished, + Row::Plaintext, + Key::Loaded, + refused, + ), + ( + "finished, not a URL", + Ring::Finished, + Row::NotAUrl, + Key::Kek, + refused, + ), + ( + "finished, no row", + Ring::Finished, + Row::Absent, + Key::Kek, + refused, + ), + ]; + for (name, ring_state, row, key, expected) in cases { + let ring_text = match ring_state { + Ring::Absent => None, + Ring::Switching => Some(ring(true)), + Ring::Finished => Some(ring(false)), + }; + set_row(&catalog, KEY_RING_SETTING, ring_text.as_deref()).await; + let row_text = match row { + Row::Plaintext => Some(url.as_str()), + Row::Encrypted => Some(encrypted.as_str()), + Row::NotAUrl => Some("not a connection string"), + Row::Absent => None, + }; + set_row(&catalog, "data_database_connection_string", row_text).await; + let target = s.target(); + let target = match key { + Key::None => target, + Key::Kek => target.with_key_source(KeySource::Kek(Zeroizing::new(KEK).into()), false), + Key::KekDuringSwitch => { + target.with_key_source(KeySource::Kek(Zeroizing::new(KEK).into()), true) + } + Key::OtherKek => { + target.with_key_source(KeySource::Kek(Zeroizing::new(OTHER_KEK).into()), false) + } + Key::Loaded => target.with_secret_keys(Arc::clone(&dek)), + }; + let status = catalog_status(&target).await; + if *expected { + assert_eq!( + status.as_ref().ok(), + Some(&CatalogStatus::Current { version: LATEST }), + "{name}: {:?}", + status.as_ref().err() + ); + let opened = data_connection_string(&target) + .await + .expect("the row opens") + .expect("the row exists"); + assert!( + *opened == url, + "{name}: the opened row is not the stored string" + ); + } else { + let Err(MigrationError::Refused(message)) = &status else { + panic!("{name}: not refused: {:?}", status.as_ref().ok()); + }; + assert!( + !message.contains(&url), + "{name}: the refusal prints the row" + ); + if matches!(key, Key::OtherKek) { + assert!(message.contains("KEK"), "{name}: {message}"); + } + } + } + catalog.close().await; + drop(s); +} + +/// `set-data-connection` writes the row under the ring's DEK, where the +/// readers open it, and refuses a string that does not parse, a catalog +/// without a ring, an unfinished switch and an unfinished rotation. +#[tokio::test] +async fn set_data_connection_writes_the_row_under_the_ring() { + let Some(base) = base_conn() else { + return skip("set-data-connection"); + }; + let s = installed(&base, "pgk_setconn").await; + let catalog = s.catalog().await; + let catalog_id: String = + sqlx::query_scalar("SELECT value FROM settings WHERE key = 'catalog_id'") + .fetch_one(&catalog) + .await + .expect("migration 6 writes the catalog id"); + let first = SecretKeys::dek_for_tests([5; 32], 1, &catalog_id); + let second = SecretKeys::dek_for_tests([6; 32], 2, &catalog_id); + let catalog_key = SecretKeys::catalog_key(CATALOG_KEY).expect("a catalog key"); + let seal = |deks: &[&SecretKeys], switching: bool| { + let retiring = switching.then(|| catalog_key_id(&KEK, &catalog_key)); + KeyRing::seal(&KEK, &catalog_id, deks, switching, retiring) + .expect("seal the ring") + .to_json() + }; + let store = PostgresCatalogStore::new(catalog.clone()); + let url = s.data_url(); + let cases = [ + ("no ring", None, url.as_str(), false), + ( + "an unfinished switch", + Some(seal(&[&first], true)), + url.as_str(), + false, + ), + ( + "two DEKs", + Some(seal(&[&first, &second], false)), + url.as_str(), + false, + ), + ( + "not a URL", + Some(seal(&[&first], false)), + "postgres://[bad", + false, + ), + ("one DEK", Some(seal(&[&first], false)), url.as_str(), true), + ]; + for (name, ring, value, writes) in &cases { + set_row(&catalog, KEY_RING_SETTING, ring.as_deref()).await; + set_row( + &catalog, + "data_database_connection_string", + Some("unchanged"), + ) + .await; + let result = store.set_data_connection(&KEK, value).await; + let row: String = sqlx::query_scalar( + "SELECT value FROM settings WHERE key = 'data_database_connection_string'", + ) + .fetch_one(&catalog) + .await + .expect("read the row"); + if *writes { + result.unwrap_or_else(|e| panic!("{name}: {e:?}")); + assert!(row != url, "{name}: the row is in plaintext"); + let target = s + .target() + .with_key_source(KeySource::Kek(Zeroizing::new(KEK).into()), false); + let opened = data_connection_string(&target) + .await + .expect("the row opens") + .expect("the row exists"); + assert!( + *opened == url, + "{name}: the opened row is not the written string" + ); + // `verify`'s data database check opens the row as the status + // read does: with the KEK of the ring, and not without it. + let data_name = store + .test_data_database_connection(&KeySource::Kek(Zeroizing::new(KEK).into())) + .await + .unwrap_or_else(|e| panic!("{name}: verify's check with the KEK: {e}")); + assert!( + url.ends_with(&format!("/{data_name}")), + "{name}: {data_name}" + ); + assert!( + store + .test_data_database_connection(&KeySource::None) + .await + .is_err(), + "{name}: verify's check opened the row without a key" + ); + } else { + assert!(result.is_err(), "{name}: not refused"); + assert_eq!(row, "unchanged", "{name}: the row changed"); + } + } + catalog.close().await; + drop(s); +} + +/// The server factory loads the key inside its registration: a switched +/// catalog (a key ring, the connection string row encrypted under its DEK, +/// no catalog key) starts with the KEK of the ring, with the DEK in the +/// stores; without key_file the start is refused. +#[tokio::test] +async fn a_server_starts_on_a_switched_catalog_with_its_kek() { + let Some(base) = base_conn() else { + return skip("server start on a switched catalog"); + }; + let s = installed(&base, "pgk_serve").await; + let catalog = s.catalog().await; + let catalog_id: String = + sqlx::query_scalar("SELECT value FROM settings WHERE key = 'catalog_id'") + .fetch_one(&catalog) + .await + .expect("migration 6 writes the catalog id"); + let dek = SecretKeys::dek_for_tests([5; 32], 1, &catalog_id); + let ring = KeyRing::seal(&KEK, &catalog_id, &[&dek], false, None).expect("seal the ring"); + set_row(&catalog, KEY_RING_SETTING, Some(&ring.to_json())).await; + let encrypted = dek.encrypt_setting(&s.data_url()).expect("encrypt the row"); + set_row( + &catalog, + "data_database_connection_string", + Some(&encrypted), + ) + .await; + catalog.close().await; + + let config = extenddb_storage_postgres::PostgresStorageConfig { + connection_string: s.catalog_url(), + pool_size: 10, + catalog_pool_size: None, + }; + let start = |key_source: KeySource| { + let mut options = extenddb_storage::server_components::ServerComponentsOptions::default(); + options.startup_recovery = false; + options.key_source = key_source; + (extenddb_storage_postgres::backend().server_components)(&config, "us-east-1", options) + }; + let started = start(KeySource::Kek(Zeroizing::new(KEK).into())) + .await + .unwrap_or_else(|e| panic!("starts with the KEK: {e}")); + let keys = started.catalog_store.secret_keys().expect("a key holder"); + assert_eq!(keys.dek_id(), Some(1)); + drop(started); + match start(KeySource::CatalogKey).await { + Err(extenddb_storage::server_components::BackendError::InitializationFailed(message)) => { + assert!( + message.contains("Set [auth.encryption] key_file"), + "{message}" + ); + } + Err(other) => panic!("refused for another reason: {other}"), + Ok(_) => panic!("started without key_file"), + } + drop(s); +} + +/// The commands reach the data database through `Target`: its key opens +/// the connection string row (the plaintext row of an unfinished switch for +/// `switch` alone), and after a lost KEK (`reset`) the status read under the +/// lock and the stores of the lock use the connection string the command +/// read, which no key of the run opens. +#[tokio::test] +async fn the_commands_reach_the_data_database_through_the_target() { + use std::time::Duration; + + use extenddb_storage::migrations::{CatalogMigrations, Target}; + use extenddb_storage_postgres::migrations::PostgresCatalogMigrations; + + let Some(base) = base_conn() else { + return skip("the target's key and connection string"); + }; + let s = installed(&base, "pgk_target").await; + let catalog = s.catalog().await; + let catalog_id: String = + sqlx::query_scalar("SELECT value FROM settings WHERE key = 'catalog_id'") + .fetch_one(&catalog) + .await + .expect("migration 6 writes the catalog id"); + let dek = SecretKeys::dek_for_tests([5; 32], 1, &catalog_id); + let catalog_key = SecretKeys::catalog_key(CATALOG_KEY).expect("a catalog key"); + let migrations = PostgresCatalogMigrations; + let at = |kek: [u8; 32], plaintext: bool, data_connection: Option| Target { + location: s.catalog_url(), + key_source: KeySource::Kek(Zeroizing::new(kek).into()), + plaintext_data_connection: plaintext, + data_connection, + ..Target::default() + }; + let current = CatalogStatus::Current { version: LATEST }; + + // An unfinished switch with the plaintext row: only the switch's target + // reads it. + let switching = KeyRing::seal( + &KEK, + &catalog_id, + &[&dek], + true, + Some(catalog_key_id(&KEK, &catalog_key)), + ) + .expect("seal the ring"); + set_row(&catalog, KEY_RING_SETTING, Some(&switching.to_json())).await; + assert_eq!( + migrations.status(&at(KEK, true, None)).await.ok(), + Some(current.clone()) + ); + assert!(matches!( + migrations.status(&at(KEK, false, None)).await, + Err(MigrationError::Refused(_)) + )); + + // A finished ring with the row under its DEK, and a lost KEK. + let finished = KeyRing::seal(&KEK, &catalog_id, &[&dek], false, None).expect("seal the ring"); + set_row(&catalog, KEY_RING_SETTING, Some(&finished.to_json())).await; + let encrypted = dek.encrypt_setting(&s.data_url()).expect("encrypt the row"); + set_row( + &catalog, + "data_database_connection_string", + Some(&encrypted), + ) + .await; + catalog.close().await; + assert!(matches!( + migrations.status(&at(OTHER_KEK, false, None)).await, + Err(MigrationError::Refused(_)) + )); + let given = at(OTHER_KEK, false, Some(s.data_url())); + let lock = migrations + .lock(&given, Duration::from_secs(5)) + .await + .expect("the migration lock"); + assert_eq!( + migrations.status_under_lock(&lock, &given).await.ok(), + Some(current.clone()) + ); + let stores = migrations + .locked_stores(&lock, Some(&s.data_url())) + .await + .expect("the stores of the lock"); + assert_eq!( + stores + .settings() + .get_setting("catalog_id") + .await + .expect("read"), + Some(catalog_id.clone()) + ); + drop(stores); + migrations.release(lock).await; + + // With the KEK of the ring, the row opens and no string is needed. + let keyed = at(KEK, false, None); + let lock = migrations + .lock(&keyed, Duration::from_secs(5)) + .await + .expect("the migration lock"); + assert_eq!( + migrations.status_under_lock(&lock, &keyed).await.ok(), + Some(current) + ); + let stores = migrations + .locked_stores(&lock, None) + .await + .expect("the stores of the lock"); + assert!( + stores + .management() + .read_secret_page(SecretTable::AccessKeys, None, 10) + .await + .expect("read the access keys") + .rows + .is_empty() + ); + drop(stores); + migrations.release(lock).await; + drop(s); +} diff --git a/crates/storage-postgres/tests/key_ring_rows/pass_methods.rs b/crates/storage-postgres/tests/key_ring_rows/pass_methods.rs new file mode 100644 index 000000000..e5ee14385 --- /dev/null +++ b/crates/storage-postgres/tests/key_ring_rows/pass_methods.rs @@ -0,0 +1,166 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +/// Every row of `table`, read one row per page so the page token is used. +async fn all_rows(store: &PostgresCatalogStore, table: SecretTable) -> Vec { + let mut rows = Vec::new(); + let mut page = None; + loop { + let read = store + .read_secret_page(table, page.as_deref(), 1) + .await + .expect("read a page"); + rows.extend(read.rows); + match read.next { + Some(next) => page = Some(next), + None => return rows, + } + } +} + +/// The pass methods read every row with its AAD fields, page by page, write +/// a batch of ciphertexts by primary key, delete rows and a settings row, +/// and treat a row that is gone as no error. +#[tokio::test] +async fn the_pass_methods_read_write_and_delete_by_primary_key() { + let Some(base) = base_conn() else { + return skip("pass methods"); + }; + let s = installed(&base, "pgk_pass").await; + let catalog = s.catalog().await; + let old = Arc::new(SecretKeys::catalog_key(CATALOG_KEY).expect("a catalog key")); + let store = PostgresCatalogStore::with_secret_keys(catalog.clone(), Some(Arc::clone(&old))); + store + .create_account(ACCOUNT, "acct") + .await + .expect("account"); + store + .create_user(ACCOUNT, "alice", None) + .await + .expect("user"); + for _ in 0..3 { + store + .create_access_key(ACCOUNT, "alice") + .await + .expect("access key"); + } + store + .create_role( + ACCOUNT, + "r1", + &serde_json::json!({"Version": "2012-10-17", "Statement": []}), + ) + .await + .expect("role"); + // An expired session is read and rewritten like any other. + let expired = time::OffsetDateTime::now_utc() + .replace_nanosecond(0) + .expect("whole seconds") + - time::Duration::hours(1); + for (token, id) in [ + ("tok-a", "ASIAEXTENDDBPGTEST01"), + ("tok-b", "ASIAEXTENDDBPGTEST02"), + ] { + let row = SecretRow::session(id, ACCOUNT, "r1", "s", expired.unix_timestamp()); + let sealed = old.encrypt(&row, "session-secret").expect("seal"); + store + .store_session( + token, id, &sealed, ACCOUNT, "r1", "s", &None, &None, expired, + ) + .await + .expect("session"); + } + + let new = SecretKeys::dek_for_tests([9; 32], 1, "pg-test"); + for table in SecretTable::ALL { + let rows = all_rows(&store, table).await; + assert_eq!( + rows.len(), + if table == SecretTable::AccessKeys { + 3 + } else { + 2 + } + ); + let mut writes: Vec = rows + .iter() + .map(|row| { + let secret = old + .decrypt(&row.aad_row(), &row.secret_key_encrypted) + .expect("the row's fields are its AAD"); + SecretWrite { + key: row.key.clone(), + secret_key_encrypted: new.encrypt(&row.aad_row(), &secret).expect("seal"), + write_timestamp: None, + } + }) + .collect(); + writes.push(SecretWrite { + key: "gone".to_owned(), + secret_key_encrypted: vec![1; 28], + write_timestamp: None, + }); + store + .write_secrets(table, &writes) + .await + .expect("write a batch"); + for row in all_rows(&store, table).await { + new.decrypt(&row.aad_row(), &row.secret_key_encrypted) + .expect("each row holds its new ciphertext"); + } + } + store + .delete_secrets( + SecretTable::IamSessions, + &["tok-b".to_owned(), "gone".to_owned()], + ) + .await + .expect("delete sessions"); + assert_eq!(all_rows(&store, SecretTable::IamSessions).await.len(), 1); + store + .set_setting("encryption_key", CATALOG_KEY) + .await + .expect("a catalog key row"); + store + .delete_setting("encryption_key") + .await + .expect("delete the catalog key row"); + store + .delete_setting("encryption_key") + .await + .expect("delete it again"); + assert_eq!( + store.get_setting("encryption_key").await.expect("read"), + None + ); + catalog.close().await; + drop(s); +} + +/// The encryption-key check every backend runs, on a catalog as `init` +/// leaves it (the catalog key row and the plaintext connection string row), +/// through the catalog store with the catalog key. +#[tokio::test] +async fn the_postgres_store_passes_the_encryption_key_check() { + let Some(base) = base_conn() else { + return skip("encryption-key check"); + }; + let s = installed(&base, "pgk_check").await; + let catalog = s.catalog().await; + set_row(&catalog, "encryption_key", Some(CATALOG_KEY)).await; + let keys = SecretKeys::catalog_key(CATALOG_KEY).expect("a catalog key"); + let store = PostgresCatalogStore::with_secret_keys(catalog.clone(), Some(Arc::new(keys))); + extenddb_storage::key_conformance::run( + &store, + &store, + extenddb_storage::key_conformance::Expectations { + write_timestamps: false, + data_connection: true, + }, + ) + .await; + catalog.close().await; + drop(s); +} diff --git a/crates/storage-sqlite/src/catalog_store.rs b/crates/storage-sqlite/src/catalog_store.rs index 651fdb5cc..3a47071e0 100644 --- a/crates/storage-sqlite/src/catalog_store.rs +++ b/crates/storage-sqlite/src/catalog_store.rs @@ -14,6 +14,7 @@ use extenddb_storage::diagnostics::{DiagError, DiagResult, DiagnosticsStore}; use extenddb_storage::management_store::{ MetricsFilter, MetricsRow, MetricsStore, OpError, OpResult, RateLimitStore, SettingsStore, }; +use extenddb_storage::secret_keys::SecretKeys; use futures::future::BoxFuture; use sqlx::SqlitePool; use time::OffsetDateTime; @@ -22,11 +23,12 @@ use crate::sqlite_util::{format_timestamp, parse_timestamp}; /// Catalog store over the shared SQLite pool. /// -/// The encryption key is cached at construction (from the `settings` table) so -/// access-key creation/import can encrypt secrets without an extra query. +/// The key holder is the one the server's factory loaded, shared with the +/// credential store, so access-key creation and import encrypt without an +/// extra query. pub struct SqliteCatalogStore { pool: SqlitePool, - encryption_key: Option>, + keys: Option>, /// Serializes this store's writers with the engine's (design decision D1, /// see `store.rs`). For a file-backed database the catalog pool opens the /// same file as the engine pool, so an uncoordinated catalog write can @@ -38,7 +40,8 @@ pub struct SqliteCatalogStore { } impl SqliteCatalogStore { - /// Construct without a cached encryption key (settings/diagnostics-only use). + /// Construct without a key holder (settings/diagnostics-only use). The + /// store refuses to create or import an access key. /// /// Used by the out-of-process factories (the `settings`/`doctor` CLI /// paths), where no engine exists in the process; the fresh lock still @@ -46,22 +49,22 @@ impl SqliteCatalogStore { pub fn new(pool: SqlitePool) -> Self { Self { pool, - encryption_key: None, + keys: None, write_lock: Arc::new(tokio::sync::Mutex::new(())), } } - /// Construct with the cached AES-256-GCM encryption key (base64) and the - /// engine's write lock, so catalog writers queue with engine writers - /// (design decision D1). - pub fn with_encryption_key( + /// Construct with the key holder the factory loaded (`None` for a caller + /// that passed `KeySource::None`) and the engine's write lock, so catalog + /// writers queue with engine writers (design decision D1). + pub fn with_secret_keys( pool: SqlitePool, - encryption_key: String, + keys: Option>, write_lock: Arc>, ) -> Self { Self { pool, - encryption_key: Some(Arc::from(encryption_key.as_str())), + keys, write_lock, } } @@ -70,10 +73,6 @@ impl SqliteCatalogStore { &self.pool } - pub(crate) fn encryption_key(&self) -> Option<&Arc> { - self.encryption_key.as_ref() - } - /// Acquire the write lock (design decision D1: every writer holds it for /// the duration of its statement or transaction, so no two writers ever /// contend at the SQLite level). Reads never take it. Callers must acquire @@ -119,6 +118,27 @@ impl SettingsStore for SqliteCatalogStore { }) } + fn replace_setting( + &self, + key: &str, + expected: &str, + value: &str, + ) -> BoxFuture<'_, OpResult> { + let (key, expected, value) = (key.to_owned(), expected.to_owned(), value.to_owned()); + Box::pin(async move { + // D1: every writer holds the write lock. + let _writer = self.lock_writes().await; + let done = sqlx::query("UPDATE settings SET value = ? WHERE key = ? AND value = ?") + .bind(&value) + .bind(&key) + .bind(&expected) + .execute(&self.pool) + .await + .map_err(|e| OpError::Internal(format!("replace_setting: {e}")))?; + Ok(done.rows_affected() == 1) + }) + } + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { Box::pin(async move { sqlx::query_as("SELECT key, value FROM settings ORDER BY key") @@ -127,10 +147,6 @@ impl SettingsStore for SqliteCatalogStore { .map_err(|e| OpError::Internal(format!("list_settings: {e}"))) }) } - - fn cached_encryption_key(&self) -> Option { - self.encryption_key.as_ref().map(|k| k.to_string()) - } } // ── MetricsStore ─────────────────────────────────────────────────────── @@ -383,7 +399,10 @@ impl DiagnosticsStore for SqliteCatalogStore { }) } - fn test_data_database_connection(&self) -> BoxFuture<'_, DiagResult> { + fn test_data_database_connection( + &self, + _key: &extenddb_storage::server_components::KeySource, + ) -> BoxFuture<'_, DiagResult> { Box::pin(async move { // Catalog and data share one SQLite file; report its recorded name. let row: Option<(String,)> = @@ -399,7 +418,7 @@ impl DiagnosticsStore for SqliteCatalogStore { // ── CatalogStore supertrait ──────────────────────────────────────────── impl CatalogStore for SqliteCatalogStore { - fn cached_encryption_key(&self) -> Option { - self.encryption_key.as_ref().map(|k| k.to_string()) + fn secret_keys(&self) -> Option<&SecretKeys> { + self.keys.as_deref() } } diff --git a/crates/storage-sqlite/src/credential_store.rs b/crates/storage-sqlite/src/credential_store.rs index 8f0b3bded..0fb36f111 100644 --- a/crates/storage-sqlite/src/credential_store.rs +++ b/crates/storage-sqlite/src/credential_store.rs @@ -5,31 +5,48 @@ //! //! `AKIA…` keys resolve to long-lived IAM user access keys; `ASIA…` keys //! resolve to temporary `AssumeRole` sessions (with expiry enforcement). -//! Secrets are decrypted with AES-256-GCM through -//! `extenddb_storage::secret_cipher`; the `access_key_id` is the AAD. +//! Secrets are decrypted with the key holder the catalog store shares, with +//! the row the secret was read from as the AAD +//! (`extenddb_storage::secret_keys`). + +use std::sync::Arc; use extenddb_auth::{CredentialStore, StoredCredential}; use extenddb_core::error::DynamoDbError; -use extenddb_storage::secret_cipher::decrypt_secret; +use extenddb_storage::secret_keys::{SecretKeys, SecretRow}; use sqlx::SqlitePool; -use zeroize::{Zeroize, ZeroizeOnDrop}; use crate::sqlite_util::parse_timestamp; -/// Credential store over the catalog SQLite pool. -#[derive(Zeroize, ZeroizeOnDrop)] +/// Credential store over the catalog SQLite pool. With no key holder (a +/// factory caller that passed `KeySource::None`) every lookup of a stored +/// secret fails. pub struct SqliteCredentialStore { - #[zeroize(skip)] pool: SqlitePool, - encryption_key: String, + keys: Option>, } impl SqliteCredentialStore { - pub fn new(pool: SqlitePool, encryption_key: String) -> Self { - Self { - pool, - encryption_key, - } + pub fn new(pool: SqlitePool, keys: Option>) -> Self { + Self { pool, keys } + } + + /// Decrypt the secret of `row`, logging a failure under `what`. + fn open( + &self, + row: &SecretRow<'_>, + encrypted: &[u8], + what: &str, + ) -> Result { + let opened = match &self.keys { + Some(keys) => keys.decrypt(row, encrypted), + None => Err("the store was opened without an encryption key".to_owned()), + }; + let mut secret = opened.map_err(|e| { + tracing::error!("{what} decryption failed for {}: {e}", row.access_key_id); + DynamoDbError::InternalServerError("Internal error during authentication".to_owned()) + })?; + Ok(std::mem::take(&mut *secret)) } async fn lookup_user( @@ -51,13 +68,11 @@ impl SqliteCredentialStore { let Some((encrypted, account_id, user_name, is_active)) = row else { return Ok(None); }; - let secret_key = - decrypt_secret(&encrypted, &self.encryption_key, access_key_id).map_err(|e| { - tracing::error!("secret decryption failed for {access_key_id}: {e}"); - DynamoDbError::InternalServerError( - "Internal error during authentication".to_owned(), - ) - })?; + let secret_key = self.open( + &SecretRow::access_key(access_key_id, &account_id, &user_name), + &encrypted, + "secret", + )?; Ok(Some(StoredCredential { secret_key, account_id, @@ -102,13 +117,17 @@ impl SqliteCredentialStore { )); } - let secret_key = - decrypt_secret(&encrypted, &self.encryption_key, access_key_id).map_err(|e| { - tracing::error!("session secret decryption failed for {access_key_id}: {e}"); - DynamoDbError::InternalServerError( - "Internal error during authentication".to_owned(), - ) - })?; + let secret_key = self.open( + &SecretRow::session( + access_key_id, + &account_id, + &role_name, + &session_name, + expires.unix_timestamp(), + ), + &encrypted, + "session secret", + )?; Ok(Some(StoredCredential { secret_key, account_id, diff --git a/crates/storage-sqlite/src/lib.rs b/crates/storage-sqlite/src/lib.rs index fc0413dcb..b0c5fa050 100644 --- a/crates/storage-sqlite/src/lib.rs +++ b/crates/storage-sqlite/src/lib.rs @@ -201,19 +201,34 @@ use std::sync::Arc; use extenddb_auth::CredentialStore; use extenddb_storage::migrations::{MigrationError, Runner}; -use extenddb_storage::server_components::{BackendError, ServerComponents}; +use extenddb_storage::server_components::{ + BackendError, KeySource, ServerComponents, load_secret_keys, +}; use crate::hooks::SqliteRuntimeHooks; fn sqlite_server_components_factory( config: &(dyn extenddb_storage::config::StorageConfig + 'static), region: &str, - options: extenddb_storage::server_components::ServerComponentsOptions, + mut options: extenddb_storage::server_components::ServerComponentsOptions, ) -> futures::future::BoxFuture<'static, Result> { let db_path = config.connection_config().to_owned(); let pool_size = config.max_connections(); let region = region.to_owned(); + let key_source = std::mem::take(&mut options.key_source); Box::pin(async move { + // An in-memory catalog is new at each start, so no command of + // another process can have switched it to a KEK file. + if matches!(key_source, KeySource::Kek(_)) + && matches!(serve_lock::database_file(&db_path), Ok(None)) + { + return Err(BackendError::InitializationFailed( + "an in-memory SQLite catalog cannot use [auth.encryption] key_file: the catalog \ + is created at each start and has no key ring; unset key_file, or store the \ + catalog in a database file" + .to_owned(), + )); + } // One server per database file, taken before the database is opened: // startup recovery below assumes no other server is using it, and a // migration holds the same lock. A file database only; an in-memory @@ -272,7 +287,7 @@ fn sqlite_server_components_factory( details: e.to_string(), })?; if options.beside_server { - return components_of(engine, &db_path).await; + return components_of(engine, &db_path, key_source).await; } // An in-memory database exists only on the engine's single @@ -318,7 +333,7 @@ fn sqlite_server_components_factory( // command exits with none of it half done. if !options.startup_recovery { engine.serve_lock = serve_lock; - return components_of(engine, &db_path).await; + return components_of(engine, &db_path, key_source).await; } // Recover any in-flight control-plane transitions from a prior run. @@ -393,17 +408,18 @@ fn sqlite_server_components_factory( } engine.serve_lock = serve_lock; - components_of(engine, &db_path).await + components_of(engine, &db_path, key_source).await }) } /// The server components around an opened engine: the catalog and /// credential stores over a second pool on the same file (the engine's own -/// connection for an in-memory database, whose data lives only there) and -/// the runtime hooks. +/// connection for an in-memory database, whose data lives only there), +/// sharing the one key holder `key_source` loads, and the runtime hooks. async fn components_of( engine: SqliteEngine, db_path: &str, + key_source: KeySource, ) -> Result { let in_memory = engine.in_memory; let control_plane_notify = engine.control_plane_notify(); @@ -424,14 +440,7 @@ async fn components_of( })? }; - let enc_key: Option = - sqlx::query_scalar("SELECT value FROM settings WHERE key = 'encryption_key'") - .fetch_optional(&catalog_pool) - .await - .map_err(|e| { - BackendError::InitializationFailed(format!("fetch encryption key: {e}")) - })?; - let enc_key = enc_key.ok_or(BackendError::MissingEncryptionKey)?; + let keys = load_secret_keys(&SqliteCatalogStore::new(catalog_pool.clone()), key_source).await?; // The catalog store writes through the second pool over the same // file, so its writers must hold the SAME lock instance as the @@ -441,13 +450,13 @@ async fn components_of( // For an in-memory database the pools are one and the sharing is // harmless. The credential store only reads and needs no lock. let catalog_store: Arc = - Arc::new(SqliteCatalogStore::with_encryption_key( + Arc::new(SqliteCatalogStore::with_secret_keys( catalog_pool.clone(), - enc_key.clone(), + keys.clone(), Arc::clone(&engine.write_lock), )); let credential_store: Arc = - Arc::new(SqliteCredentialStore::new(catalog_pool, enc_key)); + Arc::new(SqliteCredentialStore::new(catalog_pool, keys)); let runtime_hooks = Box::new(SqliteRuntimeHooks { engine: engine.clone(), @@ -479,10 +488,11 @@ mod serve_lock_tests { }; let mut options = extenddb_storage::server_components::ServerComponentsOptions::default(); options.bootstrap_if_uninitialized = true; - let first = super::sqlite_server_components_factory(&config, "us-east-1", options) + let first = super::sqlite_server_components_factory(&config, "us-east-1", options.clone()) .await .expect("first server"); - let Err(err) = super::sqlite_server_components_factory(&config, "us-east-1", options).await + let Err(err) = + super::sqlite_server_components_factory(&config, "us-east-1", options.clone()).await else { panic!("a second server on the same file started"); }; @@ -516,7 +526,7 @@ mod serve_lock_tests { let mut options = extenddb_storage::server_components::ServerComponentsOptions::default(); options.bootstrap_if_uninitialized = true; let stale = std::time::Duration::from_secs(300); - let first = super::sqlite_server_components_factory(&config, "us-east-1", options) + let first = super::sqlite_server_components_factory(&config, "us-east-1", options.clone()) .await .expect("first server"); let claim = first diff --git a/crates/storage-sqlite/src/management_store/access_keys.rs b/crates/storage-sqlite/src/management_store/access_keys.rs index 86126d241..57cc30f7a 100644 --- a/crates/storage-sqlite/src/management_store/access_keys.rs +++ b/crates/storage-sqlite/src/management_store/access_keys.rs @@ -3,48 +3,38 @@ //! Access-key management for `SqliteCatalogStore`, including key generation. //! -//! Secrets are encrypted with the catalog encryption key before storage by -//! `extenddb_storage::secret_cipher`. The ciphertext layout is -//! `nonce(12) || ciphertext || tag(16)`, with the `access_key_id` bound as -//! additional authenticated data (AAD) so a stored secret cannot be -//! transplanted onto a different key id. +//! Secrets are encrypted before storage with the store's key holder +//! (`extenddb_storage::secret_keys`). The ciphertext layout is +//! `nonce(12) || ciphertext || tag(16)`, with the row bound as additional +//! authenticated data (AAD) so a stored secret cannot be transplanted onto +//! another row. +use extenddb_storage::CatalogStore as _; use extenddb_storage::management_store::{AccessKeyCreated, OpError, OpResult}; -use extenddb_storage::secret_cipher::encrypt_secret; +use extenddb_storage::secret_keys::{SecretRow, require_keys}; use time::OffsetDateTime; use crate::catalog_store::SqliteCatalogStore; use crate::sqlite_util::{is_fk_violation, is_unique_violation, parse_timestamp}; impl SqliteCatalogStore { - /// Resolve the AES-256-GCM encryption key (base64), preferring the cached - /// value and falling back to the `settings` table. - async fn resolve_encryption_key(&self) -> OpResult { - if let Some(k) = self.encryption_key() { - return Ok(k.to_string()); - } - let row: Option<(String,)> = - sqlx::query_as("SELECT value FROM settings WHERE key = 'encryption_key'") - .fetch_optional(self.pool()) - .await - .map_err(|e| OpError::Internal(format!("fetch encryption key: {e}")))?; - row.map(|(v,)| v) - .ok_or_else(|| OpError::Internal("Encryption key not configured".to_owned())) - } - pub(crate) async fn create_access_key_impl( &self, account_id: &str, user_name: &str, ) -> OpResult { - let enc_key = self.resolve_encryption_key().await?; + let keys = require_keys(self.secret_keys())?; let access_key_id = generate_access_key_id(); let secret_access_key = generate_secret_key(); - let encrypted = encrypt_secret(&secret_access_key, &enc_key, &access_key_id) + let encrypted = keys + .encrypt( + &SecretRow::access_key(&access_key_id, account_id, user_name), + &secret_access_key, + ) .map_err(|e| OpError::Internal(format!("encrypt secret: {e}")))?; - // D1: every writer holds the write lock. Key generation, encryption, - // and the encryption-key read above all run before it. + // D1: every writer holds the write lock. Key generation and + // encryption above run before it. let _writer = self.lock_writes().await; sqlx::query( "INSERT INTO access_keys \ @@ -135,12 +125,16 @@ impl SqliteCatalogStore { access_key_id: &str, secret_access_key: &str, ) -> OpResult<()> { - let enc_key = self.resolve_encryption_key().await?; - let encrypted = encrypt_secret(secret_access_key, &enc_key, access_key_id) + let keys = require_keys(self.secret_keys())?; + let encrypted = keys + .encrypt( + &SecretRow::access_key(access_key_id, account_id, user_name), + secret_access_key, + ) .map_err(|e| OpError::Internal(format!("encrypt secret: {e}")))?; - // D1: every writer holds the write lock. Encryption and the - // encryption-key read above run before it. + // D1: every writer holds the write lock. Encryption above runs + // before it. let _writer = self.lock_writes().await; sqlx::query( "INSERT INTO access_keys \ diff --git a/crates/storage-sqlite/src/management_store/mod.rs b/crates/storage-sqlite/src/management_store/mod.rs index 7e1884a31..472a090ab 100644 --- a/crates/storage-sqlite/src/management_store/mod.rs +++ b/crates/storage-sqlite/src/management_store/mod.rs @@ -14,13 +14,16 @@ mod accounts; mod groups; mod policies; mod roles; +mod secret_rows; mod users; +use extenddb_storage::CatalogStore as _; use extenddb_storage::management_store::{ AccessKeyCreated, AccountDetail, GroupDetail, GroupListEntry, ManagementStore, OpError, - OpResult, RoleDetail, RoleListEntry, SessionPolicyEntry, StoredDocument, UserDetail, - UserListEntry, + OpResult, RoleDetail, RoleListEntry, SecretPage, SecretWrite, SessionPolicyEntry, + StoredDocument, UserDetail, UserListEntry, }; +use extenddb_storage::secret_keys::SecretTable; use futures::future::BoxFuture; use time::OffsetDateTime; @@ -587,8 +590,11 @@ impl ManagementStore for SqliteCatalogStore { let session_name = session_name.to_owned(); let session_tags = session_tags.as_ref().map(ToString::to_string); let session_policy = session_policy.as_ref().map(ToString::to_string); + // AssumeRole truncated `expires_at` to whole seconds before its + // encrypt, so this text is the value in the secret's AAD. let expires = format_timestamp(expires_at); Box::pin(async move { + extenddb_storage::secret_keys::require_keys(self.secret_keys())?; // D1: every writer holds the write lock. let _writer = self.lock_writes().await; sqlx::query( @@ -734,6 +740,44 @@ impl ManagementStore for SqliteCatalogStore { Ok(Vec::new()) }) } + + // ── Encryption-key commands (in `secret_rows`) ───────────────── + + fn read_secret_page( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> BoxFuture<'_, OpResult> { + let page = page.map(ToOwned::to_owned); + Box::pin(async move { + self.read_secret_page_impl(table, page.as_deref(), page_size) + .await + }) + } + + fn write_secrets( + &self, + table: SecretTable, + rows: &[SecretWrite], + ) -> BoxFuture<'_, OpResult<()>> { + let rows = rows.to_vec(); + Box::pin(async move { self.write_secrets_impl(table, &rows).await }) + } + + fn delete_secrets(&self, table: SecretTable, keys: &[String]) -> BoxFuture<'_, OpResult<()>> { + let keys = keys.to_vec(); + Box::pin(async move { self.delete_secrets_impl(table, &keys).await }) + } + + fn delete_setting(&self, key: &str) -> BoxFuture<'_, OpResult<()>> { + let key = key.to_owned(); + Box::pin(async move { self.delete_setting_impl(&key).await }) + } + + fn erase_free_space(&self) -> BoxFuture<'_, OpResult<()>> { + Box::pin(self.erase_free_space_impl()) + } } #[cfg(test)] @@ -756,7 +800,13 @@ mod migration_tests { .await .unwrap(); crate::migrations::apply_for_tests(&pool).await; - SqliteCatalogStore::new(pool) + // A key holder, so the store writes the session the tests store. + let keys = extenddb_storage::secret_keys::SecretKeys::dek_for_tests([7; 32], 1, "test"); + SqliteCatalogStore::with_secret_keys( + pool, + Some(std::sync::Arc::new(keys)), + std::sync::Arc::new(tokio::sync::Mutex::new(())), + ) } fn policy(resource_tag_key: &str) -> serde_json::Value { diff --git a/crates/storage-sqlite/src/management_store/secret_rows.rs b/crates/storage-sqlite/src/management_store/secret_rows.rs new file mode 100644 index 000000000..2227ee9ae --- /dev/null +++ b/crates/storage-sqlite/src/management_store/secret_rows.rs @@ -0,0 +1,556 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The stored secrets as the encryption-key commands read and rewrite them, +//! for `SqliteCatalogStore`. +//! +//! Each write runs in one `BEGIN IMMEDIATE` transaction with +//! `PRAGMA secure_delete = ON`, so SQLite overwrites a replaced ciphertext +//! or a deleted row with zeros, and ends with `PRAGMA +//! wal_checkpoint(TRUNCATE)`, which copies the new pages into the database +//! file and empties the WAL. After the last write of `switch`, `rotate` and +//! `reset`, `VACUUM` rebuilds every page, which removes the old copies of +//! rows that SQLite moved between pages before the command. A copy of the +//! files taken after a command holds no ciphertext it replaced and no row it +//! deleted. + +use extenddb_storage::management_store::{ + OpError, OpResult, SecretPage, SecretWrite, StoredSecretRow, +}; +use extenddb_storage::secret_keys::SecretTable; + +use crate::catalog_store::SqliteCatalogStore; +use crate::sqlite_util::parse_timestamp; + +/// An `access_keys` row: key, secret, account, user, created. +type AccessKeyRow = (String, Vec, String, String, String); + +/// An `iam_sessions` row: token, access key ID, secret, account, role, +/// session name, expiry, created. +type SessionRow = ( + String, + String, + Vec, + String, + String, + String, + String, + String, +); + +impl SqliteCatalogStore { + pub(crate) async fn read_secret_page_impl( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> OpResult { + let what = "read_secret_page"; + let limit = i64::try_from(page_size).unwrap_or(i64::MAX); + let rows = match table { + SecretTable::AccessKeys => { + let rows: Vec = sqlx::query_as( + "SELECT access_key_id, secret_key_encrypted, account_id, user_name, \ + created_at FROM access_keys \ + WHERE ? IS NULL OR access_key_id > ? ORDER BY access_key_id LIMIT ?", + ) + .bind(page) + .bind(page) + .bind(limit) + .fetch_all(self.pool()) + .await + .map_err(|e| OpError::Internal(format!("{what}: {e}")))?; + rows.into_iter() + .map( + |(id, secret, account_id, user_name, created)| StoredSecretRow { + table, + key: id.clone(), + access_key_id: id, + account_id, + principal_name: user_name, + session_name: None, + expires_at: None, + created_at: parse_timestamp(&created).ok(), + secret_key_encrypted: secret, + write_timestamp: None, + }, + ) + .collect::>() + } + SecretTable::IamSessions => { + let rows: Vec = sqlx::query_as( + "SELECT session_token, access_key_id, secret_key_encrypted, account_id, \ + role_name, session_name, expires_at, created_at FROM iam_sessions \ + WHERE ? IS NULL OR session_token > ? ORDER BY session_token LIMIT ?", + ) + .bind(page) + .bind(page) + .bind(limit) + .fetch_all(self.pool()) + .await + .map_err(|e| OpError::Internal(format!("{what}: {e}")))?; + rows.into_iter() + .map( + |(token, id, secret, account_id, role, session, expires, created)| { + let expires_at = parse_timestamp(&expires).map_err(|e| { + OpError::Internal(format!( + "{what}: the expires_at of session {id} does not parse: {e}" + )) + })?; + Ok(StoredSecretRow { + table, + key: token, + access_key_id: id, + account_id, + principal_name: role, + session_name: Some(session), + expires_at: Some(expires_at.unix_timestamp()), + created_at: parse_timestamp(&created).ok(), + secret_key_encrypted: secret, + write_timestamp: None, + }) + }, + ) + .collect::>>()? + } + }; + let next = (rows.len() == page_size) + .then(|| rows.last().map(|row| row.key.clone())) + .flatten(); + Ok(SecretPage { rows, next }) + } + + pub(crate) async fn write_secrets_impl( + &self, + table: SecretTable, + rows: &[SecretWrite], + ) -> OpResult<()> { + let sql = format!( + "UPDATE {} SET secret_key_encrypted = ? WHERE {} = ?", + table.name(), + table.key_column() + ); + let rows: Vec<_> = rows + .iter() + .map(|row| (Some(row.secret_key_encrypted.as_slice()), row.key.as_str())) + .collect(); + self.overwrite("write_secrets", &sql, &rows).await + } + + pub(crate) async fn delete_secrets_impl( + &self, + table: SecretTable, + keys: &[String], + ) -> OpResult<()> { + let sql = format!( + "DELETE FROM {} WHERE {} = ?", + table.name(), + table.key_column() + ); + let rows: Vec<_> = keys.iter().map(|k| (None, k.as_str())).collect(); + self.overwrite("delete_secrets", &sql, &rows).await + } + + pub(crate) async fn delete_setting_impl(&self, key: &str) -> OpResult<()> { + self.overwrite( + "delete_setting", + "DELETE FROM settings WHERE key = ?", + &[(None, key)], + ) + .await + } + + /// Run `sql` once per row, binding the row's bytes (when it has them) + /// and then its key, in one transaction under `secure_delete`, then + /// checkpoint and truncate the WAL. A key that matches no row changes + /// nothing and is not an error. + async fn overwrite( + &self, + what: &str, + sql: &str, + rows: &[(Option<&[u8]>, &str)], + ) -> OpResult<()> { + let failed = |e: sqlx::Error| OpError::Internal(format!("{what}: {e}")); + // D1: every writer holds the write lock, here through the + // checkpoint, so no write of this process lands between the two. + let _writer = self.lock_writes().await; + let mut tx = self + .pool() + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(failed)?; + sqlx::query("PRAGMA secure_delete = ON") + .execute(&mut *tx) + .await + .map_err(failed)?; + for &(bytes, key) in rows { + let statement = sqlx::query(sql); + let statement = match bytes { + Some(bytes) => statement.bind(bytes), + None => statement, + }; + statement + .bind(key) + .execute(&mut *tx) + .await + .map_err(failed)?; + } + tx.commit().await.map_err(failed)?; + self.checkpoint(what).await + } + + /// `VACUUM` under `PRAGMA secure_delete = ON` and `PRAGMA temp_store = + /// MEMORY`, then the checkpoint. A row that SQLite moved to another page + /// as its table grew, before the command, left its old bytes in the page + /// it moved from, where `secure_delete` does not reach; `VACUUM` + /// rebuilds every page, and `temp_store = MEMORY` keeps the rebuild out + /// of a temporary file. + pub(crate) async fn erase_free_space_impl(&self) -> OpResult<()> { + const WHAT: &str = "erase_free_space"; + let failed = |e: sqlx::Error| OpError::Internal(format!("{WHAT}: {e}")); + let _writer = self.lock_writes().await; + let mut connection = self.pool().acquire().await.map_err(failed)?; + for statement in [ + "PRAGMA secure_delete = ON", + "PRAGMA temp_store = MEMORY", + "VACUUM", + ] { + sqlx::query(statement) + .execute(&mut *connection) + .await + .map_err(failed)?; + } + // The migration lock's pool holds one connection, which the + // checkpoint takes next. + drop(connection); + self.checkpoint(WHAT).await + } + + /// `PRAGMA wal_checkpoint(TRUNCATE)`, which copies the new pages into the + /// database file and empties the WAL, under the write lock the caller + /// holds. + async fn checkpoint(&self, what: &str) -> OpResult<()> { + let (busy, _, _): (i64, i64, i64) = sqlx::query_as("PRAGMA wal_checkpoint(TRUNCATE)") + .fetch_one(self.pool()) + .await + .map_err(|e| OpError::Internal(format!("{what}: {e}")))?; + if busy != 0 { + return Err(OpError::Internal(format!( + "{what}: another connection to the database blocked the WAL checkpoint, so the \ + WAL file can still hold the replaced bytes; stop every process that has the \ + database open and run the command again" + ))); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::path::Path; + use std::sync::Arc; + use std::time::Duration; + + use extenddb_storage::key_commands::{KekFile, KeyStores, Outcome, RunFlags, switch}; + use extenddb_storage::key_ring::{KEY_RING_SETTING, open_ring}; + use extenddb_storage::management_store::{ManagementStore, SettingsStore}; + use extenddb_storage::secret_keys::{SecretKeys, SecretRow}; + use serde_json::json; + use zeroize::Zeroizing; + + use super::*; + + const ACCOUNT: &str = "123456789012"; + + /// Every row of `table`, read one row per page so the page token is used. + async fn all_rows(store: &SqliteCatalogStore, table: SecretTable) -> Vec { + let mut rows = Vec::new(); + let mut page = None; + loop { + let read = store + .read_secret_page(table, page.as_deref(), 1) + .await + .expect("read a page"); + rows.extend(read.rows); + match read.next { + Some(next) => page = Some(next), + None => return rows, + } + } + } + + /// The bytes of every file in `dir`: the database, its WAL and its + /// shared-memory index. + fn files(dir: &Path) -> Vec<(String, Vec)> { + std::fs::read_dir(dir) + .expect("list the directory") + .map(|entry| { + let path = entry.expect("an entry").path(); + let bytes = std::fs::read(&path).expect("read a file"); + (path.display().to_string(), bytes) + }) + .collect() + } + + /// The files that hold `needle`. + fn holding(files: &[(String, Vec)], needle: &[u8]) -> Vec { + files + .iter() + .filter(|(_, bytes)| bytes.windows(needle.len()).any(|w| w == needle)) + .map(|(name, _)| name.clone()) + .collect() + } + + /// A KEK that the test holds in memory. + struct TestKek([u8; 32]); + + impl KekFile for TestKek { + fn path(&self) -> &str { + "/run/credentials/extenddb.service/kek" + } + + fn read(&self) -> Result, String> { + Ok(Zeroizing::new(self.0)) + } + } + + /// After `switch --yes` (every secret re-encrypted under the new DEK and + /// the catalog key deleted) and the delete of a session, the files of + /// the database hold neither the catalog key nor any ciphertext that was + /// replaced or deleted, though they held the catalog key before. The 80 + /// access keys span several pages, so SQLite moved some rows between + /// pages as the table grew. + #[tokio::test] + async fn a_pass_leaves_no_catalog_key_and_no_old_ciphertext_in_the_files() { + let dir = std::env::temp_dir().join(format!( + "extenddb-secure-delete-{}", + uuid::Uuid::new_v4().simple() + )); + std::fs::create_dir_all(&dir).expect("dir"); + let location = dir.join("catalog.db").to_string_lossy().into_owned(); + crate::migrations::migrate(&location, "test", Duration::from_secs(5)) + .await + .expect("a current catalog"); + let pool = crate::catalog_pool(&location).await.expect("pool"); + let catalog_key = extenddb_storage::bootstrapper::helpers::generate_encryption_key() + .expect("a catalog key"); + let catalog = Arc::new(SecretKeys::catalog_key(&catalog_key).expect("key holder")); + let store = SqliteCatalogStore::with_secret_keys( + pool.clone(), + Some(Arc::clone(&catalog)), + Arc::new(tokio::sync::Mutex::new(())), + ); + store + .set_setting("encryption_key", &catalog_key) + .await + .expect("the catalog key row"); + store + .create_account(ACCOUNT, "acct") + .await + .expect("account"); + store + .create_user(ACCOUNT, "alice", None) + .await + .expect("user"); + for _ in 0..80 { + store + .create_access_key(ACCOUNT, "alice") + .await + .expect("access key"); + } + store + .create_role( + ACCOUNT, + "r1", + &json!({"Version": "2012-10-17", "Statement": []}), + ) + .await + .expect("role"); + let expires = time::OffsetDateTime::now_utc() + .replace_nanosecond(0) + .expect("whole") + + time::Duration::hours(1); + for (token, id) in [ + ("tok-1", "ASIAEXTENDDBTEST0001"), + ("tok-2", "ASIAEXTENDDBTEST0002"), + ] { + let row = SecretRow::session(id, ACCOUNT, "r1", "s", expires.unix_timestamp()); + let sealed = catalog.encrypt(&row, "session-secret").expect("seal"); + store + .store_session( + token, id, &sealed, ACCOUNT, "r1", "s", &None, &None, expires, + ) + .await + .expect("session"); + } + let old: Vec> = { + let mut old = Vec::new(); + for table in SecretTable::ALL { + old.extend( + all_rows(&store, table) + .await + .into_iter() + .map(|row| row.secret_key_encrypted), + ); + } + old + }; + assert_eq!( + old.len(), + 82, + "eighty access keys, which span several pages, and two sessions" + ); + assert!( + !holding(&files(&dir), catalog_key.as_bytes()).is_empty(), + "the files hold the catalog key before the switch" + ); + + // `switch --yes` over a store with no key, as the command opens it. + let offline = SqliteCatalogStore::new(pool.clone()); + let stores = KeyStores { + management: &offline, + settings: &offline, + }; + let kek = TestKek(rand::random()); + let flags = RunFlags { + yes: true, + ..RunFlags::default() + }; + let outcome = switch(stores, &kek, flags).await.expect("switch"); + assert!(matches!(outcome, Outcome::Done(_)), "{outcome:?}"); + assert_eq!( + offline.get_setting("encryption_key").await.expect("read"), + None + ); + let open = open_ring( + &offline + .get_setting(KEY_RING_SETTING) + .await + .expect("read") + .expect("the ring"), + offline + .get_setting("catalog_id") + .await + .expect("read") + .as_deref(), + &kek.0, + ) + .expect("the ring opens"); + let dek = open.active(); + for table in SecretTable::ALL { + for row in all_rows(&offline, table).await { + dek.decrypt(&row.aad_row(), &row.secret_key_encrypted) + .expect("every secret opens under the DEK"); + } + } + + // A deleted session's ciphertext goes too. + let mut old = old; + let sessions = all_rows(&offline, SecretTable::IamSessions).await; + let deleted = sessions + .iter() + .find(|row| row.key == "tok-2") + .expect("tok-2"); + old.push(deleted.secret_key_encrypted.clone()); + offline + .delete_secrets(SecretTable::IamSessions, &["tok-2".to_owned()]) + .await + .expect("delete a session"); + assert_eq!(all_rows(&store, SecretTable::IamSessions).await.len(), 1); + pool.close().await; + + let after = files(&dir); + assert!( + holding(&after, catalog_key.as_bytes()).is_empty(), + "a file still holds the catalog key" + ); + for (i, ciphertext) in old.iter().enumerate() { + assert!( + holding(&after, ciphertext).is_empty(), + "a file still holds old ciphertext {i}" + ); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// Writing or deleting a row that is gone changes nothing and succeeds. + #[tokio::test] + async fn a_write_or_delete_of_a_missing_row_succeeds() { + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(1) + .connect("sqlite::memory:") + .await + .expect("in-memory sqlite"); + crate::migrations::apply_for_tests(&pool).await; + let store = SqliteCatalogStore::new(pool); + for table in SecretTable::ALL { + let write = SecretWrite { + key: "gone".to_owned(), + secret_key_encrypted: vec![1; 28], + write_timestamp: None, + }; + store.write_secrets(table, &[write]).await.expect("write"); + store + .delete_secrets(table, &["gone".to_owned()]) + .await + .expect("delete"); + let page = store.read_secret_page(table, None, 10).await.expect("read"); + assert_eq!(page, SecretPage::default()); + } + store + .delete_setting("absent") + .await + .expect("delete a setting"); + } +} + +/// The encryption-key check every backend runs, on a file catalog as `init` +/// leaves it, through the catalog store with the catalog key. +#[cfg(test)] +mod conformance { + use std::sync::Arc; + use std::time::Duration; + + use extenddb_storage::key_conformance::{Expectations, run}; + use extenddb_storage::management_store::SettingsStore; + use extenddb_storage::secret_keys::SecretKeys; + + use crate::catalog_store::SqliteCatalogStore; + + #[tokio::test] + async fn the_sqlite_store_passes_the_encryption_key_check() { + let dir = std::env::temp_dir().join(format!( + "extenddb-key-conformance-{}", + uuid::Uuid::new_v4().simple() + )); + std::fs::create_dir_all(&dir).expect("dir"); + let location = dir.join("catalog.db").to_string_lossy().into_owned(); + crate::migrations::migrate(&location, "test", Duration::from_secs(5)) + .await + .expect("a current catalog"); + let pool = crate::catalog_pool(&location).await.expect("pool"); + let catalog_key = extenddb_storage::bootstrapper::helpers::generate_encryption_key() + .expect("a catalog key"); + SqliteCatalogStore::new(pool.clone()) + .set_setting("encryption_key", &catalog_key) + .await + .expect("the catalog key row"); + let keys = SecretKeys::catalog_key(&catalog_key).expect("key holder"); + let store = SqliteCatalogStore::with_secret_keys( + pool.clone(), + Some(Arc::new(keys)), + Arc::new(tokio::sync::Mutex::new(())), + ); + run( + &store, + &store, + Expectations { + write_timestamps: false, + data_connection: false, + }, + ) + .await; + pool.close().await; + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/storage-sqlite/src/migrations/backend.rs b/crates/storage-sqlite/src/migrations/backend.rs index dfafa1921..eded80af6 100644 --- a/crates/storage-sqlite/src/migrations/backend.rs +++ b/crates/storage-sqlite/src/migrations/backend.rs @@ -26,11 +26,11 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use async_trait::async_trait; -use extenddb_storage::management_store::ManagementStore; +use extenddb_storage::management_store::{ManagementStore, SettingsStore}; use extenddb_storage::migrations::{ - CatalogTraces, Done, HasManagementStore, LedgerColumns, LedgerRow, LedgerWrites, Migration, - MigrationBackend, MigrationError, MigrationId, Released, RunReport, Runner, Step, StoreKind, - StoreRef, in_transaction, record_rows, sql_ledger_ddl, + CatalogTraces, Done, HasManagementStore, LedgerColumns, LedgerRow, LedgerWrites, LockedStores, + Migration, MigrationBackend, MigrationError, MigrationId, Released, RunReport, Runner, Step, + StoreKind, StoreRef, in_transaction, record_rows, sql_ledger_ddl, }; use sqlx::sqlite::SqlitePoolOptions; use sqlx::{ConnectOptions, Connection, SqlitePool}; @@ -51,6 +51,28 @@ impl HasManagementStore for SqliteStores { } } +/// The catalog's stores under a held migration lock, for `encryption-key +/// switch`, `rotate` and `reset` (RFC-0000 section 8, common rules): the +/// management store over the runner's one connection, holding no key. +/// Dropping it closes the connection. +pub(crate) struct LockedCatalog(SqliteMigrations); + +impl LockedCatalog { + pub(crate) fn new(migrations: SqliteMigrations) -> Self { + Self(migrations) + } +} + +impl LockedStores for LockedCatalog { + fn management(&self) -> &dyn ManagementStore { + &self.0.stores.management + } + + fn settings(&self) -> &dyn SettingsStore { + &self.0.stores.management + } +} + /// The ledger's `applied_at` column in SQLite, which has no time type: the /// UTC time as text, to the millisecond. const APPLIED_AT: &str = "TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))"; diff --git a/crates/storage-sqlite/src/migrations/commands.rs b/crates/storage-sqlite/src/migrations/commands.rs index 51fcc1a41..8e41828ca 100644 --- a/crates/storage-sqlite/src/migrations/commands.rs +++ b/crates/storage-sqlite/src/migrations/commands.rs @@ -9,10 +9,11 @@ use std::time::Duration; use async_trait::async_trait; use extenddb_storage::migrations::{ CatalogMigrations, CatalogStatus, HasManagementStore, HeldLock, LedgerRow, Listed, - MigrationBackend, MigrationError, MigrationId, RunKind, RunReport, Runner, Target, - policy_rewrite_lines, policy_rewrite_pending, + LockedStores, MigrationBackend, MigrationError, MigrationId, RunKind, RunReport, Runner, + Target, policy_rewrite_lines, policy_rewrite_pending, }; +use super::backend::LockedCatalog; use super::{ MigrationLock, SqliteMigrations, catalog_status, in_memory_refusal, lock_for_migration, }; @@ -131,6 +132,20 @@ impl CatalogMigrations for SqliteCatalogMigrations { migrations.close().await; result } + + /// The management store over the runner's one connection to the file, + /// opened as `migrate --yes` opens it, under the file's lock. SQLite has + /// no data connection string, so `data_connection` is not read. + async fn locked_stores( + &self, + lock: &HeldLock, + data_connection: Option<&str>, + ) -> Result, MigrationError> { + let _ = data_connection; + let location = locked_location(lock)?; + let migrations = SqliteMigrations::open(location).await?; + Ok(Box::new(LockedCatalog::new(migrations))) + } } /// `word` as one word of a POSIX shell command: as it is when every diff --git a/crates/storage-sqlite/src/migrations/serve_tests.rs b/crates/storage-sqlite/src/migrations/serve_tests.rs index 5b432edcb..e4ba83fc8 100644 --- a/crates/storage-sqlite/src/migrations/serve_tests.rs +++ b/crates/storage-sqlite/src/migrations/serve_tests.rs @@ -6,14 +6,15 @@ //! and writes nothing when it refuses; a dev build migrates `Uninitialized` //! and `Behind` first, and refuses the rest; an in-memory database is //! created by the runner every time. The lock that keeps a migrator, a -//! second migrator and a server apart is tested here too. +//! second migrator and a server apart is tested here too, and so is the +//! refusal of an encryption key that the secret cipher refuses. use std::path::Path; use std::time::Duration; use extenddb_storage::migrations::{CatalogStatus, MigrationError, MigrationId, exit}; use extenddb_storage::server_components::{ - BackendError, ServerComponents, ServerComponentsOptions, + BackendError, KeySource, ServerComponents, ServerComponentsOptions, }; use super::migrate; @@ -164,6 +165,31 @@ async fn a_dev_server_creates_a_missing_catalog_and_its_rows() { assert!(copies(&db).is_empty(), "a new database has nothing to copy"); } +/// A dev server writes no catalog key into a catalog that has a key ring, +/// whether or not it then starts. +#[tokio::test] +async fn a_dev_server_writes_no_catalog_key_beside_a_key_ring() { + let db = temp_db("serve-dev-ring"); + let location = db.to_string_lossy().into_owned(); + super::migrate(&location, "1.0.0-test", Duration::from_secs(5)) + .await + .expect("a current catalog"); + exec( + &db, + "INSERT INTO settings (key, value) VALUES ('encryption_key_ring', '{}')", + ) + .await; + let _ = start(&location, true).await; + let pool = plain_pool(&db).await; + let key: Option = + sqlx::query_scalar("SELECT value FROM settings WHERE key = 'encryption_key'") + .fetch_optional(&pool) + .await + .expect("read"); + pool.close().await; + assert!(key.is_none(), "the dev bootstrap wrote a catalog key"); +} + #[tokio::test] async fn a_dev_server_refuses_a_catalog_that_needs_attention() { let db = temp_db("serve-dev-attention"); @@ -217,6 +243,40 @@ async fn a_server_refuses_while_a_migration_holds_the_database() { ); } +/// A server refuses a catalog whose encryption key the secret cipher refuses, +/// and names the reason. Without the check it started, and every signed +/// request failed with a 500. +#[tokio::test] +async fn a_server_refuses_an_encryption_key_the_cipher_refuses() { + let db = temp_db("serve-bad-key"); + let location = current_catalog(&db).await; + let set_key = + |key: &str| format!("UPDATE settings SET value = '{key}' WHERE key = 'encryption_key'"); + // 32 bytes and a trailing newline. + exec( + &db, + &set_key("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n"), + ) + .await; + match start(&location, false).await { + Err(BackendError::InvalidEncryptionKey(r)) => { + assert!(r.starts_with("decode encryption key: "), "{r}"); + } + Err(other) => panic!("refused for another reason: {other}"), + Ok(_) => panic!("the server started"), + } + exec( + &db, + &set_key("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="), + ) + .await; + drop( + start(&location, false) + .await + .expect("starts with a 32-byte key"), + ); +} + #[tokio::test] async fn a_server_serves_a_catalog_ahead_by_additive_migrations_only() { let db = temp_db("serve-ahead"); @@ -260,6 +320,85 @@ async fn an_in_memory_server_creates_its_catalog_through_the_runner() { assert_eq!(version, Some(LATEST.to_string())); } +/// An in-memory catalog is new at each start, so it refuses key_file. +#[tokio::test] +async fn an_in_memory_server_refuses_a_key_file() { + let config = crate::config::SqliteConfig { + path: ":memory:".to_owned(), + pool_size: 2, + }; + let mut options = options(false); + options.key_source = KeySource::Kek(zeroize::Zeroizing::new([3; 32]).into()); + match crate::sqlite_server_components_factory(&config, "us-east-1", options).await { + Err(BackendError::InitializationFailed(message)) => { + assert!(message.contains("in-memory"), "{message}"); + } + Err(other) => panic!("refused for another reason: {other}"), + Ok(_) => panic!("an in-memory server started with key_file"), + } +} + +/// A switched catalog (a key ring, no catalog key) starts with the KEK of +/// its ring, and both stores then hold the ring's DEK; without key_file, or +/// with another KEK, the server refuses. +#[tokio::test] +async fn a_server_loads_the_dek_of_a_switched_catalog_with_its_kek() { + use extenddb_storage::key_ring::KeyRing; + use extenddb_storage::secret_keys::SecretKeys; + + const KEK: [u8; 32] = [3; 32]; + let db = temp_db("serve-ring"); + let location = current_catalog(&db).await; + let pool = plain_pool(&db).await; + let catalog_id: String = + sqlx::query_scalar("SELECT value FROM settings WHERE key = 'catalog_id'") + .fetch_one(&pool) + .await + .expect("the catalog id"); + let dek = SecretKeys::dek_for_tests([5; 32], 1, &catalog_id); + let ring = KeyRing::seal(&KEK, &catalog_id, &[&dek], false, None).expect("a ring"); + sqlx::query("DELETE FROM settings WHERE key = 'encryption_key'") + .execute(&pool) + .await + .expect("delete the catalog key"); + sqlx::query("INSERT INTO settings (key, value) VALUES ('encryption_key_ring', ?)") + .bind(ring.to_json()) + .execute(&pool) + .await + .expect("write the ring"); + pool.close().await; + + let start_with = |key_source: KeySource| { + let location = location.clone(); + async move { + let config = crate::config::SqliteConfig { + path: location, + pool_size: 2, + }; + let mut options = options(false); + options.key_source = key_source; + crate::sqlite_server_components_factory(&config, "us-east-1", options).await + } + }; + let kek = |bytes: [u8; 32]| KeySource::Kek(zeroize::Zeroizing::new(bytes).into()); + let started = start_with(kek(KEK)).await.expect("starts with the KEK"); + let keys = started.catalog_store.secret_keys().expect("a key holder"); + assert_eq!(keys.dek_id(), Some(1)); + drop(started); + for (source, expected) in [ + (KeySource::CatalogKey, "Set [auth.encryption] key_file"), + (kek([4; 32]), "and the key file holds the KEK with id"), + ] { + match start_with(source).await { + Err(BackendError::InitializationFailed(message)) => { + assert!(message.contains(expected), "{message}"); + } + Err(other) => panic!("refused for another reason: {other}"), + Ok(_) => panic!("the server started"), + } + } +} + #[tokio::test] async fn two_migrators_apply_once() { let db = temp_db("two"); @@ -338,3 +477,46 @@ async fn a_caller_holding_the_serve_lock_migrates_through_migrate_holding() { ); drop(held); } + +/// The stores of a held migration lock read and write the catalog, and a +/// server refuses to start while the lock is held. +#[tokio::test] +async fn the_stores_of_a_held_lock_write_the_catalog() { + use extenddb_storage::migrations::{CatalogMigrations, Target}; + use extenddb_storage::secret_keys::SecretTable; + + let db = temp_db("locked-stores"); + let location = current_catalog(&db).await; + let migrations = super::SqliteCatalogMigrations; + let lock = migrations + .lock(&Target::at(&location), Duration::from_secs(5)) + .await + .expect("the migration lock"); + let stores = migrations + .locked_stores(&lock, None) + .await + .expect("the stores of the lock"); + stores + .settings() + .set_setting("locked_stores_test", "written") + .await + .expect("write a setting"); + let page = stores + .management() + .read_secret_page(SecretTable::AccessKeys, None, 10) + .await + .expect("read the access keys"); + assert!(page.rows.is_empty()); + let err = refusal(start(&location, false).await); + assert!(matches!(err, MigrationError::Locked(_)), "{err:?}"); + drop(stores); + migrations.release(lock).await; + let pool = plain_pool(&db).await; + let value: Option = + sqlx::query_scalar("SELECT value FROM settings WHERE key = 'locked_stores_test'") + .fetch_optional(&pool) + .await + .expect("read"); + pool.close().await; + assert_eq!(value.as_deref(), Some("written")); +} diff --git a/crates/storage-sqlite/src/store.rs b/crates/storage-sqlite/src/store.rs index a8f7c8de0..379ee22a8 100644 --- a/crates/storage-sqlite/src/store.rs +++ b/crates/storage-sqlite/src/store.rs @@ -263,9 +263,13 @@ impl SqliteEngine { let internal = |e: String| StorageError::Internal(e); - // Encryption key. + // Encryption key: only into a catalog that has neither a catalog key + // nor a key ring. A switched catalog has the ring and no catalog + // key, and a catalog key written into it at each start would stop + // the next start. let key_exists: bool = sqlx::query_scalar( - "SELECT EXISTS(SELECT 1 FROM settings WHERE key = 'encryption_key')", + "SELECT EXISTS(SELECT 1 FROM settings \ + WHERE key IN ('encryption_key', 'encryption_key_ring'))", ) .fetch_one(&self.pool) .await @@ -649,13 +653,12 @@ mod d1_write_lock_tests { /// Build a catalog store over the engine's pool and, critically, the /// engine's OWN write lock, mirroring the server wiring in `lib.rs`. The - /// cached key lets access-key creation encrypt without a settings lookup. + /// key holder lets access-key creation encrypt. fn catalog_store(engine: &SqliteEngine) -> crate::SqliteCatalogStore { - use base64::Engine as _; - let key = base64::engine::general_purpose::STANDARD.encode([0u8; 32]); - crate::SqliteCatalogStore::with_encryption_key( + let keys = extenddb_storage::secret_keys::SecretKeys::dek_for_tests([0; 32], 1, "test"); + crate::SqliteCatalogStore::with_secret_keys( engine.pool.clone(), - key, + Some(std::sync::Arc::new(keys)), std::sync::Arc::clone(&engine.write_lock), ) } diff --git a/crates/storage/src/diagnostics.rs b/crates/storage/src/diagnostics.rs index 8f4943b57..96e4b9964 100644 --- a/crates/storage/src/diagnostics.rs +++ b/crates/storage/src/diagnostics.rs @@ -36,8 +36,14 @@ pub trait DiagnosticsStore: Send + Sync { /// Count the number of secondary indexes in the catalog. fn count_indexes(&self) -> BoxFuture<'_, DiagResult>; - /// Test connection to the data database. + /// Test connection to the data database. On PostgreSQL, whose catalog + /// holds the data database's connection string, `key` opens that row in + /// a catalog with a key ring (RFC-0000 section 12); the other backends + /// read no such row and ignore it. /// /// Returns the database name on success, or an error if connection fails. - fn test_data_database_connection(&self) -> BoxFuture<'_, DiagResult>; + fn test_data_database_connection( + &self, + key: &crate::server_components::KeySource, + ) -> BoxFuture<'_, DiagResult>; } diff --git a/crates/storage/src/key_commands/mod.rs b/crates/storage/src/key_commands/mod.rs new file mode 100644 index 000000000..ad1adeb52 --- /dev/null +++ b/crates/storage/src/key_commands/mod.rs @@ -0,0 +1,530 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `extenddb encryption-key` commands as library functions (RFC-0000 +//! sections 8, 8.1 to 8.3, 8.5 and 8.6), over the store methods. +//! +//! The command line around them is the app's: it parses the arguments, reads +//! the KEK file through the file rule ([`KekFile`]), opens the stores through +//! the migration backend, takes and frees the migration lock for `switch`, +//! `rotate` and `reset`, prints the [`Outcome`] and sets the exit code. These +//! functions make the checks and the writes in the order the RFC gives: +//! +//! - the nothing-to-do check comes first, right after the KEK file is read +//! and the ring unwrapped; +//! - every command except `status` and `reset` checks the ring before it +//! writes, in the order of section 7; +//! - `switch --yes` and `rotate --yes` open every stored secret with the keys +//! the run holds before their first write, and stop when one opens under +//! none, unless `--keep-unopenable`; +//! - without `--yes` a command previews and writes nothing. + +mod reset; +mod rewrap; +mod switch; + +pub use reset::{data_connection_key, reset}; +pub use rewrap::{rewrap, rotate}; +pub use switch::switch; + +use zeroize::Zeroizing; + +use crate::key_pass::{ + DataConnection, PAGE_SIZE, PassError, PassKeys, SecretListing, Survey, TableCounts, survey, +}; +use crate::key_ring::{ + KEY_RING_SETTING, KeyId, KeyRefusal, KeyRing, KeyRows, LOST_KEK_STEPS, catalog_key_id, + join_ids, kek_id, +}; +use crate::management_store::{ManagementStore, OpError, SettingsStore}; +use crate::secret_cipher::KEY_LEN; +use crate::secret_keys::{CATALOG_KEY_SETTING, SecretKeys, SecretTable}; + +/// The notice at the end of every command that writes, except `reset`. +pub const NO_REVOCATION_NOTICE: &str = "This does not revoke any credential. Each access key \ + keeps its secret. A secret that leaked before this run works until its access key is \ + re-created."; + +/// The notice at the end of `reset`, which deletes every stored secret. +#[must_use] +pub fn reset_notice() -> String { + format!( + "Every access key and every session was deleted. For the steps after a reset, \ + {LOST_KEK_STEPS}." + ) +} + +/// A KEK file, read through the file rule (section 2). The app implements it; +/// this crate reads no file. +pub trait KekFile: Send + Sync { + /// The path as given. The `key_file` line of the summary prints it made + /// absolute ([`Summary::key_file_line`]). + fn path(&self) -> &str; + + /// Read the file through the file rule and parse it + /// ([`crate::key_ring::parse_kek_file`]). The commands call it at the + /// start, and the pass calls it again before an old key goes. + /// + /// # Errors + /// + /// The path and the check that failed. + fn read(&self) -> Result, String>; +} + +/// The stores a command runs over, opened through the migration backend for +/// `switch`, `rotate` and `reset`. +#[derive(Clone, Copy)] +pub struct KeyStores<'a> { + /// The rows of `access_keys` and `iam_sessions`. + pub management: &'a dyn ManagementStore, + /// The `encryption_key`, `encryption_key_ring`, `catalog_id` and, on + /// PostgreSQL, `data_database_connection_string` rows. + pub settings: &'a dyn SettingsStore, +} + +/// The options of `switch` and `rotate`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct RunFlags { + /// `--yes`: write. Without it the command previews. + pub yes: bool, + /// `--keep-unopenable`. + pub keep_unopenable: bool, + /// `--accept-catalog-key` (section 8.5). + pub accept_catalog_key: bool, + /// The configuration sets `key_file`. `switch` and `reset` read it. + pub key_file_configured: bool, +} + +/// What a command found or did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + /// The ring is already in the target state. Exit 0. + NothingToDo { + /// The ring's KEK id. + kek_id: KeyId, + /// The ring's DEK id. + dek_id: u64, + }, + /// No `--yes`: what `--yes` would do. Nothing was written. + Preview(Preview), + /// The command wrote and finished. + Done(Summary), +} + +/// What `--yes` would do. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Preview { + /// One line per write, in order. + pub steps: Vec, + /// The stored secrets and the key each opens under. `reset` tries no key + /// and has none. + pub survey: Option, +} + +/// The summary that every command that writes prints at the end. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Summary { + /// The KEK id of the ring the command wrote. + pub kek_id: KeyId, + /// The DEK id of that ring. + pub dek_id: u64, + /// The name of each key of the run, indexed as in + /// [`crate::key_pass::PassKeys::names`]. + pub key_names: Vec, + /// The counts of `access_keys` and `iam_sessions`. + pub tables: [(SecretTable, TableCounts); 2], + /// `None` without a connection string row (every backend but + /// PostgreSQL), else whether the command rewrote it. + pub data_connection_rewritten: Option, + /// The stored secrets that no key opens, by access key ID. + pub unopenable: Vec, + /// `reset`: the access key IDs it deleted. + pub deleted_access_key_ids: Vec, + /// Whether the command deleted an `encryption_key` row. + pub deleted_catalog_key: bool, + /// The path for the `key_file` line of the configuration. + pub key_file: String, +} + +impl Summary { + /// The `[auth.encryption]` line for the configuration. A relative path + /// is made absolute against this process's working directory, as the + /// migration advice prints a config path, because a daemon `serve` reads + /// the file from `/`. Symlinks stay as given: the file rule resolves them + /// at each read, and a Kubernetes secret volume replaces its target. + #[must_use] + pub fn key_file_line(&self) -> String { + let path = std::path::absolute(&self.key_file) + .map_or_else(|_| self.key_file.clone(), |p| p.display().to_string()); + format!("key_file = {path:?}") + } +} + +/// What `status` prints. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StatusReport { + /// The catalog holds an `encryption_key` row. + pub catalog_key_present: bool, + /// The ring, when the catalog has one. + pub ring: Option, + /// The stored secrets per key, when a key opens them: the catalog key, + /// or the ring's DEKs with the KEK given. + pub survey: Option, +} + +/// The ring as `status` prints it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RingStatus { + /// The ring's fields. Not authenticated unless `failed_dek_ids` is empty + /// and the KEK id matches. + pub ring: KeyRing, + /// The id of the KEK given to `status`, if one was. + pub given_kek_id: Option, + /// The DEK ids that fail to unwrap under the given KEK. + pub failed_dek_ids: Vec, +} + +/// Why a command stopped. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeyCommandError { + /// The key state refuses the command; the message names the next step. + Refused(String), + /// The KEK file failed the file rule or did not parse. + Kek(String), + /// A store call failed. + Store(OpError), + /// The pass stopped. + Pass(PassError), +} + +impl std::fmt::Display for KeyCommandError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Refused(message) | Self::Kek(message) => f.write_str(message), + Self::Store(e) => write!(f, "storage error: {}", e.message()), + Self::Pass(e) => write!(f, "{e}"), + } + } +} + +impl std::error::Error for KeyCommandError {} + +impl From for KeyCommandError { + fn from(e: OpError) -> Self { + Self::Store(e) + } +} + +impl From for KeyCommandError { + fn from(e: PassError) -> Self { + Self::Pass(e) + } +} + +/// Section 8.5, rule 1: a catalog key row is an old key only while the ring's +/// `switch_from_catalog_key` is true and the row's id under the KEK equals +/// `retiring_catalog_key_id`. `ring` is authentic: every DEK unwrapped. +#[must_use] +pub fn catalog_key_is_retiring( + ring: &KeyRing, + kek: &[u8; KEY_LEN], + catalog_key: &SecretKeys, +) -> bool { + ring.switch_from_catalog_key + && ring.retiring_catalog_key_id.as_ref() == Some(&catalog_key_id(kek, catalog_key)) +} + +fn refused(refusal: KeyRefusal) -> KeyCommandError { + KeyCommandError::Refused(refusal.to_string()) +} + +fn refuse(message: impl Into) -> KeyCommandError { + KeyCommandError::Refused(message.into()) +} + +fn read_kek(file: &dyn KekFile) -> Result, KeyCommandError> { + file.read().map_err(KeyCommandError::Kek) +} + +/// The ring row that a command needs, or the section 7 refusal for its +/// absence. +fn ring_row(rows: &KeyRows) -> Result<&str, KeyCommandError> { + rows.ring.as_deref().ok_or_else(|| { + refused(if rows.catalog_key.is_some() { + KeyRefusal::CatalogKeyWithoutRing + } else { + KeyRefusal::NoRing + }) + }) +} + +fn catalog_id(rows: &KeyRows) -> Result<&str, KeyCommandError> { + rows.catalog_id.as_deref().ok_or_else(|| { + refuse( + "the catalog has no catalog_id row, which migration 6 writes. Run \ + `extenddb migrate --yes` first", + ) + }) +} + +fn catalog_key(rows: &KeyRows) -> Result, KeyCommandError> { + rows.catalog_key + .as_deref() + .map(|key| { + SecretKeys::catalog_key(key) + .map_err(|reason| refuse(format!("the encryption_key row is not a key: {reason}"))) + }) + .transpose() +} + +/// The refusal of a catalog key beside a finished ring, without +/// `--accept-catalog-key` (section 8.5). +fn catalog_key_not_accepted() -> KeyCommandError { + refuse(format!( + "{}. After reading that list, `--accept-catalog-key` re-encrypts those secrets under \ + the ring's DEK and deletes the row", + KeyRefusal::CatalogKeyAfterSwitch + )) +} + +fn seal( + kek: &[u8; KEY_LEN], + catalog_id: &str, + deks: &[&SecretKeys], + switch_from_catalog_key: bool, + retiring: Option, +) -> Result { + KeyRing::seal(kek, catalog_id, deks, switch_from_catalog_key, retiring) + .map_err(|reason| refuse(format!("seal the key ring: {reason}"))) +} + +/// Write the ring row, with one audit line, as `extenddb settings set` does. +/// With `read`, the ring text the command read, the write lands only while +/// the row still holds that text: `rewrap` runs outside the migration lock, +/// so a `rotate` can write the ring between another command's read and its +/// write. +async fn write_ring( + settings: &dyn SettingsStore, + ring: &KeyRing, + command: &str, + read: Option<&str>, +) -> Result<(), KeyCommandError> { + let text = ring.to_json(); + match read { + None => settings.set_setting(KEY_RING_SETTING, &text).await?, + Some(read) + if settings + .replace_setting(KEY_RING_SETTING, read, &text) + .await? => {} + Some(_) => { + return Err(refuse(format!( + "the key ring changed while `extenddb encryption-key {command}` ran, so nothing \ + was written. Run the command again" + ))); + } + } + tracing::warn!( + target: "extenddb::audit::settings", + "encryption-key {command}: wrote {KEY_RING_SETTING}, kek_id={}, dek_ids={}, \ + switch_from_catalog_key={}", + ring.kek.id, + join_ids(&ring.dek_ids()), + ring.switch_from_catalog_key, + ); + Ok(()) +} + +/// Step 3 of the pass: read the KEK file again before an old key goes, and +/// stop when it is gone or holds another KEK. +fn reread_kek(file: &dyn KekFile, ring: &KeyRing) -> Result<(), KeyCommandError> { + let kek = file.read().map_err(|reason| { + refuse(format!( + "the KEK file cannot be read again before the old key is deleted: {reason}. Every \ + key is kept; run the command again" + )) + })?; + let id = kek_id(&kek); + if id != ring.kek.id { + return Err(refuse(format!( + "the KEK file now holds the KEK with id {id}, not {}, the KEK of the key ring. \ + Every key is kept; put the file back and run the command again", + ring.kek.id + ))); + } + Ok(()) +} + +/// The check before a first write (section 8, common rules, and section 12). +fn check_before_write( + survey: &Survey, + flags: RunFlags, + plaintext_data_connection: bool, +) -> Result<(), KeyCommandError> { + let unopenable: Vec = survey.unopenable().into_iter().cloned().collect(); + if !unopenable.is_empty() && !flags.keep_unopenable { + return Err(PassError::Unopenable(unopenable).into()); + } + match survey.data_connection { + DataConnection::Absent | DataConnection::Opens(_) => Ok(()), + DataConnection::Plaintext if plaintext_data_connection => Ok(()), + DataConnection::Plaintext | DataConnection::Unopenable => Err(refuse( + "the data_database_connection_string row opens under no key of this run. Run \ + `extenddb encryption-key status`", + )), + } +} + +/// `None` without a connection string row, else `Some(false)`: for the +/// summary of a run that did not rewrite it. +fn untouched(data_connection: DataConnection) -> Option { + (data_connection != DataConnection::Absent).then_some(false) +} + +fn dek_id(keys: &SecretKeys) -> u64 { + keys.dek_id().unwrap_or(0) +} + +/// The last step of `switch`, `rotate` and `reset`: rebuild the catalog +/// file so that no free page keeps a ciphertext the run replaced (SQLite +/// only). Every row is written by then, and a run of the same command again +/// rebuilds the file, so a failure says both. +async fn erase_free_space(stores: KeyStores<'_>, command: &str) -> Result<(), KeyCommandError> { + stores.management.erase_free_space().await.map_err(|e| { + refuse(format!( + "`extenddb encryption-key {command}` wrote every row, and then the rebuild of the \ + database file that erases the ciphertexts it replaced failed: {}. Run the same \ + command again", + e.message() + )) + }) +} + +/// Delete the `encryption_key` row, then read it back and stop when it is +/// still there. +/// +/// A store's `Ok` from a delete does not prove the row is gone. A run that +/// reported the catalog key deleted while the plaintext row stayed readable +/// would leave the operator with a key they believe is gone, so the run +/// stops instead, with every key kept, and runs again from there. +/// +/// # Errors +/// +/// [`KeyCommandError::Store`] from either call, or +/// [`KeyCommandError::Refused`] when the row survived the delete. +async fn delete_catalog_key(stores: KeyStores<'_>, command: &str) -> Result<(), KeyCommandError> { + stores + .management + .delete_setting(CATALOG_KEY_SETTING) + .await?; + let read_back = stores.settings.get_setting(CATALOG_KEY_SETTING).await; + let failed = match &read_back { + Ok(None) => String::new(), + Ok(Some(_)) => { + return Err(refuse( + "the catalog's encryption_key row is still there after the delete, so the \ + catalog key was not removed. Every key is kept; run the command again", + )); + } + // The delete ran and may have landed. A re-run that finds no row + // deletes nothing, so this line is the only record of it. + Err(e) => format!("; the read-back failed: {}", e.message()), + }; + tracing::warn!( + target: "extenddb::audit::settings", + "encryption-key {command}: deleted {CATALOG_KEY_SETTING}{failed}" + ); + read_back.map(drop).map_err(Into::into) +} + +/// Delete the rows of `table` that `keys` names, a page at a time, then read +/// one row back and stop when the table still holds one. A row that remains +/// is a delete that did not land, or a row a server wrote after the deletes. +/// Either stops the run, as [`delete_catalog_key`] describes. +/// +/// # Errors +/// +/// [`KeyCommandError::Store`] from either call, or +/// [`KeyCommandError::Refused`] when a row survived the deletes. +async fn delete_secret_rows( + stores: KeyStores<'_>, + table: SecretTable, + keys: &[String], +) -> Result<(), KeyCommandError> { + for batch in keys.chunks(PAGE_SIZE) { + stores.management.delete_secrets(table, batch).await?; + } + let page = stores.management.read_secret_page(table, None, 1).await?; + if !page.rows.is_empty() { + return Err(refuse(format!( + "the catalog's {} table still holds a row after the delete. Every key is kept; run \ + the command again", + table.name() + ))); + } + Ok(()) +} + +/// `extenddb encryption-key status`: the key source, the KEK id, the DEK ids +/// and the stored secrets per key. Writes nothing. A ring whose DEKs fail to +/// unwrap is reported with its fields marked as not authenticated. +/// +/// # Errors +/// +/// A store error, or a KEK file that fails. +pub async fn status( + stores: KeyStores<'_>, + kek: Option<&dyn KekFile>, +) -> Result { + let kek = kek.map(read_kek).transpose()?; + let rows = KeyRows::read(stores.settings).await?; + let catalog_key = catalog_key(&rows)?; + let mut opened: Option> = None; + let ring = match rows.ring.as_deref() { + None => None, + Some(text) => { + let ring = KeyRing::parse(text).map_err(|reason| { + refused(KeyRefusal::DamagedRing { + reason: format!("the ring does not parse: {reason}"), + }) + })?; + let mut failed_dek_ids = Vec::new(); + if let (Some(kek), Some(catalog_id)) = (&kek, rows.catalog_id.as_deref()) { + match ring.unwrap(kek, catalog_id) { + Ok(deks) => opened = Some(deks), + Err(failed) => failed_dek_ids = failed, + } + } + Some(RingStatus { + given_kek_id: kek.as_ref().map(|kek| kek_id(kek)), + ring, + failed_dek_ids, + }) + } + }; + // The target is the ring's active DEK when the ring opens, else the + // catalog key; every other key the run holds is an old key. + let keys = match (&opened, &catalog_key) { + (Some(deks), catalog_key) => { + let (active, older) = deks.split_last().expect("an open ring holds a DEK"); + let old = older.iter().chain(catalog_key.as_ref()).collect(); + Some(PassKeys { + target: active, + old, + }) + } + (None, Some(catalog_key)) => Some(PassKeys { + target: catalog_key, + old: Vec::new(), + }), + (None, None) => None, + }; + let survey = match keys { + Some(keys) => Some(survey(stores.management, stores.settings, &keys).await?), + None => None, + }; + Ok(StatusReport { + catalog_key_present: rows.catalog_key.is_some(), + ring, + survey, + }) +} diff --git a/crates/storage/src/key_commands/reset.rs b/crates/storage/src/key_commands/reset.rs new file mode 100644 index 000000000..61f34676a --- /dev/null +++ b/crates/storage/src/key_commands/reset.rs @@ -0,0 +1,213 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use crate::key_pass::{TableCounts, for_each_page}; +use crate::key_ring::{KeyRefusal, KeyRing, KeyRows, kek_id, new_dek, open_ring}; +use crate::secret_cipher::KEY_LEN; +use crate::secret_keys::{DATA_CONNECTION_SETTING, SecretKeys, SecretTable}; + +use super::{ + KekFile, KeyCommandError, KeyStores, Outcome, Preview, RunFlags, Summary, catalog_id, + delete_catalog_key, delete_secret_rows, erase_free_space, read_kek, refuse, refused, seal, + write_ring, +}; + +/// `extenddb encryption-key reset --key-file --discard-secrets` +/// (section 8.6). `discard_secrets` is the flag; without it the command +/// refuses. `data_connection` is the PostgreSQL connection string that the +/// app read from standard input, which step 3 writes encrypted under the new +/// DEK; `None` on the other backends. +/// +/// # Errors +/// +/// [`KeyCommandError`]; a run that stops before its ring write runs again +/// from the start. +pub async fn reset( + stores: KeyStores<'_>, + kek: &dyn KekFile, + flags: RunFlags, + discard_secrets: bool, + data_connection: Option<&str>, +) -> Result { + if !discard_secrets { + return Err(refuse( + "reset deletes every access key and every session, and keeps every user, role, \ + policy, group, account and table. Pass --discard-secrets to run it", + )); + } + let kek_file = kek; + let kek = read_kek(kek_file)?; + let rows = KeyRows::read(stores.settings).await?; + let old_ring = rows.ring.as_deref().map(KeyRing::parse); + if old_ring.is_none() && rows.catalog_key.is_some() { + return Err(if flags.key_file_configured { + refused(KeyRefusal::CatalogKeyWithoutRing) + } else { + refuse( + "the catalog uses the catalog key of its encryption_key row and has no key \ + ring, so no KEK is lost. `extenddb encryption-key switch --key-file ` \ + moves it to a KEK file", + ) + }); + } + // A ring that names this KEK: the KEK is not lost. + if let (Some(Ok(ring)), Some(text)) = (&old_ring, rows.ring.as_deref()) + && ring.kek.id == kek_id(&kek) + { + let open = open_ring(text, rows.catalog_id.as_deref(), &kek).map_err(refused)?; + // A run that stopped at its rebuild rebuilds the file now. + if flags.yes { + erase_free_space(stores, "reset").await?; + } + return Ok(Outcome::NothingToDo { + kek_id: open.ring.kek.id.clone(), + dek_id: open.ring.active_dek_id(), + }); + } + let catalog_id = catalog_id(&rows)?; + if data_connection.is_none() + && stores + .settings + .get_setting(DATA_CONNECTION_SETTING) + .await? + .is_some() + { + return Err(refuse( + "reset on PostgreSQL reads the data database connection string on standard input", + )); + } + + // Every row it deletes, by table. + let mut doomed: Vec<(SecretTable, Vec)> = Vec::new(); + let mut deleted_access_key_ids = Vec::new(); + for table in SecretTable::ALL { + let mut keys = Vec::new(); + for_each_page(stores.management, table, |rows| { + for row in rows { + deleted_access_key_ids.push(row.access_key_id); + keys.push(row.key); + } + Ok(Vec::new()) + }) + .await?; + doomed.push((table, keys)); + } + let next_id = match &old_ring { + Some(Ok(ring)) => ring.next_dek_id().map_err(refused)?, + _ => 1, + }; + if !flags.yes { + let mut steps: Vec = doomed + .iter() + .map(|(table, keys)| format!("delete the {} rows of {}", keys.len(), table.name())) + .collect(); + if rows.catalog_key.is_some() { + steps.push("delete the encryption_key row".to_owned()); + } + if data_connection.is_some() { + steps + .push("write the data_database_connection_string row under the new DEK".to_owned()); + } + steps.push(format!( + "write a new key ring with DEK {next_id} under the KEK {}", + kek_id(&kek) + )); + if !deleted_access_key_ids.is_empty() { + steps.push(format!( + "the access keys and sessions deleted: {}", + deleted_access_key_ids.join(", ") + )); + } + return Ok(Outcome::Preview(Preview { + steps, + survey: None, + })); + } + + // Steps 2 to 4. The old ring stays until the last write. + for (table, keys) in &doomed { + delete_secret_rows(stores, *table, keys).await?; + } + if rows.catalog_key.is_some() { + delete_catalog_key(stores, "reset").await?; + } + let dek = new_dek(next_id, catalog_id).map_err(refuse)?; + if let Some(connection) = data_connection { + let sealed = dek + .encrypt_setting(connection) + .map_err(|reason| refuse(format!("encrypt the connection string: {reason}")))?; + stores + .settings + .set_setting(DATA_CONNECTION_SETTING, &sealed) + .await?; + } + let ring = seal(&kek, catalog_id, &[&dek], false, None)?; + // Conditional on the ring that this run read, when it read one: on + // Cassandra a plain write after a conditional one can lose to it by + // write time, and a `rewrap` can write the ring between the read and + // this write. `write_ring` refuses only for a changed ring; the deletes + // are done by now, so the refusal says what this run left. + write_ring(stores.settings, &ring, "reset", rows.ring.as_deref()) + .await + .map_err(|e| match e { + KeyCommandError::Refused(_) => refuse(format!( + "the key ring changed while `extenddb encryption-key reset` ran, so its ring \ + write did not happen. The access_keys and iam_sessions rows are deleted{}. The \ + key ring row holds the ring that the other command wrote.{} Run the command \ + again", + if rows.catalog_key.is_some() { + ", and so is the encryption_key row" + } else { + "" + }, + if data_connection.is_some() { + " The data_database_connection_string row is encrypted under a DEK that no \ + ring holds until a run finishes." + } else { + "" + }, + )), + other => other, + })?; + erase_free_space(stores, "reset").await?; + Ok(Outcome::Done(Summary { + kek_id: ring.kek.id, + dek_id: next_id, + key_names: vec![crate::key_pass::key_name(&dek)], + tables: SecretTable::ALL.map(|table| (table, TableCounts::default())), + data_connection_rewritten: data_connection.map(|_| true), + unopenable: Vec::new(), + deleted_access_key_ids, + deleted_catalog_key: rows.catalog_key.is_some(), + key_file: kek_file.path().to_owned(), + })) +} + +/// The DEK that `set-data-connection` (section 8.7) encrypts the connection +/// string under, from the ring text that the PostgreSQL method read with +/// `SELECT ... FOR SHARE`. Refused: no ring, a ring with +/// `switch_from_catalog_key` true, and a ring with two DEKs; and a ring that +/// the KEK does not open, in the order of section 7. +/// +/// # Errors +/// +/// The refusal's message. +pub fn data_connection_key( + ring_text: Option<&str>, + kek: &[u8; KEY_LEN], + catalog_id: &str, +) -> Result { + let text = ring_text.ok_or_else(|| { + "the catalog has no key ring, so its data_database_connection_string row stays in \ + plaintext: edit it as the admin guide says" + .to_owned() + })?; + let mut open = open_ring(text, Some(catalog_id), kek).map_err(|r| r.to_string())?; + if open.ring.switch_from_catalog_key { + return Err(KeyRefusal::UnfinishedSwitchWithKeyFile.to_string()); + } + if open.deks.len() > 1 { + return Err(KeyRefusal::UnfinishedRotation.to_string()); + } + Ok(open.deks.pop().expect("an open ring holds a DEK")) +} diff --git a/crates/storage/src/key_commands/rewrap.rs b/crates/storage/src/key_commands/rewrap.rs new file mode 100644 index 000000000..30d6a1c6c --- /dev/null +++ b/crates/storage/src/key_commands/rewrap.rs @@ -0,0 +1,214 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use crate::key_pass::{PassKeys, PassOptions, run_pass, survey}; +use crate::key_ring::{KeyRefusal, KeyRows, new_dek, open_ring}; + +use super::{ + KekFile, KeyCommandError, KeyStores, Outcome, Preview, RunFlags, Summary, catalog_id, + catalog_key, catalog_key_not_accepted, check_before_write, dek_id, delete_catalog_key, + erase_free_space, read_kek, refuse, refused, reread_kek, ring_row, seal, untouched, write_ring, +}; + +/// `extenddb encryption-key rewrap --key-file ` (section 8.2): +/// the same DEK wrapped under the new KEK, one ring write. Runs beside a +/// server. +/// +/// # Errors +/// +/// [`KeyCommandError`]. +pub async fn rewrap( + stores: KeyStores<'_>, + current: &dyn KekFile, + new: &dyn KekFile, + yes: bool, +) -> Result { + let current_kek = read_kek(current)?; + let new_kek = read_kek(new)?; + let rows = KeyRows::read(stores.settings).await?; + let text = ring_row(&rows)?; + // A rewrap to the file the ring already names has nothing to do. + if let Ok(open) = open_ring(text, rows.catalog_id.as_deref(), &new_kek) { + return Ok(Outcome::NothingToDo { + kek_id: open.ring.kek.id.clone(), + dek_id: open.ring.active_dek_id(), + }); + } + let open = open_ring(text, rows.catalog_id.as_deref(), ¤t_kek).map_err(refused)?; + if open.ring.switch_from_catalog_key { + return Err(refused(KeyRefusal::UnfinishedSwitchWithKeyFile)); + } + if rows.catalog_key.is_some() { + return Err(refused(KeyRefusal::CatalogKeyAfterSwitch)); + } + if open.deks.len() > 1 { + return Err(refused(KeyRefusal::UnfinishedRotation)); + } + if open.active().key_bytes().expose() == &*new_kek { + return Err(refuse( + "the new KEK equals the DEK of the key ring. Write a KEK of new random bytes", + )); + } + let catalog_id = catalog_id(&rows)?; + let ring = seal(&new_kek, catalog_id, &[open.active()], false, None)?; + let survey = survey( + stores.management, + stores.settings, + &PassKeys { + target: open.active(), + old: Vec::new(), + }, + ) + .await?; + if !yes { + return Ok(Outcome::Preview(Preview { + steps: vec![format!( + "write the key ring with DEK {} wrapped under the KEK {}", + dek_id(open.active()), + ring.kek.id + )], + survey: Some(survey), + })); + } + write_ring(stores.settings, &ring, "rewrap", Some(text)).await?; + Ok(Outcome::Done(Summary { + kek_id: ring.kek.id.clone(), + dek_id: dek_id(open.active()), + unopenable: survey.unopenable().into_iter().cloned().collect(), + key_names: survey.key_names, + tables: survey.tables, + data_connection_rewritten: untouched(survey.data_connection), + deleted_access_key_ids: Vec::new(), + deleted_catalog_key: false, + key_file: new.path().to_owned(), + })) +} + +/// `extenddb encryption-key rotate` (section 8.3), with the resume of a ring +/// that holds two DEKs and the `--accept-catalog-key` case of 8.5. +/// +/// # Errors +/// +/// [`KeyCommandError`]; a run that stops runs again with the same arguments. +pub async fn rotate( + stores: KeyStores<'_>, + kek: &dyn KekFile, + flags: RunFlags, +) -> Result { + let kek_file = kek; + let kek = read_kek(kek_file)?; + let rows = KeyRows::read(stores.settings).await?; + let text = ring_row(&rows)?; + let open = open_ring(text, rows.catalog_id.as_deref(), &kek).map_err(refused)?; + if open.ring.switch_from_catalog_key { + return Err(refused(KeyRefusal::UnfinishedSwitchWithKeyFile)); + } + let catalog_key = catalog_key(&rows)?; + if catalog_key.is_some() && !flags.accept_catalog_key { + return Err(catalog_key_not_accepted()); + } + let catalog_id = catalog_id(&rows)?; + + // Check the stored secrets with each DEK of the ring, and the accepted + // catalog key, before the first write. + let check = PassKeys { + target: open.active(), + old: open + .older() + .into_iter() + .chain(catalog_key.as_ref()) + .collect(), + }; + let survey = survey(stores.management, stores.settings, &check).await?; + let next_id = if open.older().is_some() { + None + } else { + Some(open.ring.next_dek_id().map_err(refused)?) + }; + if !flags.yes { + let mut steps = Vec::new(); + if let Some(next_id) = next_id { + steps.push(format!( + "write the key ring with a new DEK {next_id} beside DEK {}", + open.ring.active_dek_id() + )); + } + steps.push( + "re-encrypt each stored secret under the older keys under the new DEK".to_owned(), + ); + if catalog_key.is_some() { + steps.push("delete the encryption_key row".to_owned()); + } + steps.push("write the key ring with the new DEK alone".to_owned()); + return Ok(Outcome::Preview(Preview { + steps, + survey: Some(survey), + })); + } + check_before_write(&survey, flags, false)?; + + // Step 1: a fresh run adds the next DEK; a resumed run targets the + // highest id. `two_deks` is the ring text the last write expects. + let (fresh, two_deks) = if let Some(next_id) = next_id { + let dek = new_dek(next_id, catalog_id).map_err(refuse)?; + let ring = seal(&kek, catalog_id, &[open.active(), &dek], false, None)?; + write_ring(stores.settings, &ring, "rotate", Some(text)).await?; + (Some(dek), ring.to_json()) + } else { + (None, text.to_owned()) + }; + let (target, older) = match &fresh { + Some(dek) => (dek, open.active()), + None => ( + open.active(), + open.older().expect("a resumed rotate has two DEKs"), + ), + }; + + // Steps 2 and 3. + let pass = run_pass( + stores.management, + stores.settings, + &PassKeys { + target, + old: std::iter::once(older).chain(catalog_key.as_ref()).collect(), + }, + PassOptions { + keep_unopenable: flags.keep_unopenable, + plaintext_data_connection: false, + }, + ) + .await?; + reread_kek(kek_file, &open.ring)?; + if catalog_key.is_some() { + delete_catalog_key(stores, "rotate").await?; + } + let ring = seal(&kek, catalog_id, &[target], false, None)?; + // The last write is conditional on the two-DEK ring too: on Cassandra a + // plain write after a conditional one can lose to it by write time. + // `write_ring` refuses only for a changed ring, and the pass has written + // by now, so the refusal says what this run left. + write_ring(stores.settings, &ring, "rotate", Some(&two_deks)) + .await + .map_err(|e| match e { + KeyCommandError::Refused(_) => refuse(format!( + "the key ring changed after `extenddb encryption-key rotate` wrote its two \ + DEKs, so its last ring write did not happen. The pass put the stored secrets \ + under DEK {}; run the command again", + dek_id(target) + )), + other => other, + })?; + erase_free_space(stores, "rotate").await?; + Ok(Outcome::Done(Summary { + kek_id: ring.kek.id, + dek_id: dek_id(target), + key_names: pass.key_names, + tables: pass.tables, + data_connection_rewritten: pass.data_connection_rewritten, + unopenable: pass.unopenable, + deleted_access_key_ids: Vec::new(), + deleted_catalog_key: catalog_key.is_some(), + key_file: kek_file.path().to_owned(), + })) +} diff --git a/crates/storage/src/key_commands/switch.rs b/crates/storage/src/key_commands/switch.rs new file mode 100644 index 000000000..882a54bd3 --- /dev/null +++ b/crates/storage/src/key_commands/switch.rs @@ -0,0 +1,249 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use crate::key_pass::{PassKeys, PassOptions, run_pass, survey}; +use crate::key_ring::{ + KeyRefusal, KeyRows, RESTORE_STEPS, catalog_key_id, kek_id, new_dek, open_ring, +}; + +use super::{ + KekFile, KeyCommandError, KeyStores, Outcome, Preview, RunFlags, Summary, catalog_id, + catalog_key, catalog_key_is_retiring, catalog_key_not_accepted, check_before_write, dek_id, + delete_catalog_key, erase_free_space, read_kek, refuse, refused, reread_kek, seal, untouched, + write_ring, +}; + +/// `extenddb encryption-key switch --key-file ` (section 8.1), with the +/// resume of an earlier run and the `--accept-catalog-key` case of 8.5. +/// +/// # Errors +/// +/// [`KeyCommandError`]; a run that stops runs again with the same arguments. +pub async fn switch( + stores: KeyStores<'_>, + kek: &dyn KekFile, + flags: RunFlags, +) -> Result { + /// What the run does, decided from the key rows. + #[derive(Clone, Copy, PartialEq, Eq)] + enum Plan { + /// No ring: steps 2 to 7. + Fresh, + /// The ring's switch did not finish. With the catalog key row: + /// steps 4 to 7; without it, steps 6 and 7. + Resume { catalog_key: bool }, + /// A finished ring and `--accept-catalog-key`: steps 4, 5 and 7. + Accept, + } + + let kek_file = kek; + let kek = read_kek(kek_file)?; + let rows = KeyRows::read(stores.settings).await?; + let open = rows + .ring + .as_deref() + .map(|text| open_ring(text, rows.catalog_id.as_deref(), &kek)) + .transpose() + .map_err(refused)?; + if let Some(open) = &open + && open.deks.len() == 1 + && !open.ring.switch_from_catalog_key + && rows.catalog_key.is_none() + { + // A run that stopped at its rebuild rebuilds the file now. + if flags.yes { + erase_free_space(stores, "switch").await?; + } + return Ok(Outcome::NothingToDo { + kek_id: open.ring.kek.id.clone(), + dek_id: open.ring.active_dek_id(), + }); + } + if flags.key_file_configured { + return Err(refuse( + "the configuration sets [auth.encryption] key_file, which is set only after a \ + switch finishes. Unset it for this run (the line, or the \ + EXTENDDB__AUTH__ENCRYPTION__KEY_FILE override), then run the switch again", + )); + } + let catalog_id = catalog_id(&rows)?.to_owned(); + let catalog_key = catalog_key(&rows)?; + if catalog_key + .as_ref() + .is_some_and(|key| key.key_bytes().expose() == &*kek) + { + return Err(refuse( + "the KEK equals the catalog key, which every catalog copy taken before the switch \ + holds. Write a KEK of new random bytes: head -c 32 /dev/urandom | base64", + )); + } + if open.as_ref().is_some_and(|open| { + open.deks + .iter() + .any(|dek| dek.key_bytes().expose() == &*kek) + }) { + return Err(refuse( + "the KEK equals a DEK of the key ring. Write a KEK of new random bytes", + )); + } + let not_finished_only = + || refuse("--accept-catalog-key applies only to a catalog whose switch finished"); + let plan = match (&open, &catalog_key) { + (None, None) => { + return Err(refuse( + "the catalog has no encryption_key row to switch from. Run `extenddb init` first", + )); + } + (None, Some(_)) if flags.accept_catalog_key => return Err(not_finished_only()), + (None, Some(_)) => Plan::Fresh, + (Some(open), _) if open.ring.switch_from_catalog_key => { + if flags.accept_catalog_key { + return Err(not_finished_only()); + } + if open.deks.len() != 1 { + return Err(refused(KeyRefusal::DamagedRing { + reason: "a switch writes a ring with one DEK".to_owned(), + })); + } + match &catalog_key { + Some(key) if catalog_key_is_retiring(&open.ring, &kek, key) => { + Plan::Resume { catalog_key: true } + } + Some(_) => { + return Err(refuse(format!( + "the catalog's encryption_key row is not the catalog key that the \ + unfinished switch retires: it appeared after the switch started, and \ + no option accepts it. Run `extenddb encryption-key status`, and \ + {RESTORE_STEPS}" + ))); + } + None => Plan::Resume { catalog_key: false }, + } + } + (Some(open), Some(_)) if open.deks.len() == 1 => { + if !flags.accept_catalog_key { + return Err(catalog_key_not_accepted()); + } + Plan::Accept + } + (Some(_), _) => return Err(refused(KeyRefusal::UnfinishedRotation)), + }; + + // Step 2, and the preview: check the stored secrets with the keys the + // run holds before its first write. + let check = match (&plan, &open, &catalog_key) { + (Plan::Fresh, _, Some(key)) => PassKeys { + target: key, + old: Vec::new(), + }, + (_, Some(open), key) => PassKeys { + target: open.active(), + old: key.iter().collect(), + }, + _ => unreachable!("every plan but Fresh has a ring"), + }; + let survey = survey(stores.management, stores.settings, &check).await?; + // The plaintext connection string row is the form before a switch, and + // only a run that still holds the catalog key encrypts it. + let plaintext_data_connection = + matches!(plan, Plan::Fresh | Plan::Resume { catalog_key: true }); + if !flags.yes { + let mut steps = Vec::new(); + if plan == Plan::Fresh { + steps.push(format!( + "write the key ring with DEK 1 under the KEK {}", + kek_id(&kek) + )); + } + if plan != (Plan::Resume { catalog_key: false }) { + steps.push("re-encrypt each stored secret under the catalog key under the DEK".into()); + steps.push("delete the encryption_key row".into()); + } + if plan != Plan::Accept { + steps.push("mark the switch finished in the key ring".into()); + } + return Ok(Outcome::Preview(Preview { + steps, + survey: Some(survey), + })); + } + check_before_write(&survey, flags, plaintext_data_connection)?; + + // Step 3: the ring of an unfinished switch. + let fresh = match (&plan, &catalog_key) { + (Plan::Fresh, Some(key)) => { + let dek = new_dek(1, &catalog_id).map_err(refuse)?; + let ring = seal( + &kek, + &catalog_id, + &[&dek], + true, + Some(catalog_key_id(&kek, key)), + )?; + write_ring(stores.settings, &ring, "switch", None).await?; + Some((ring, dek)) + } + _ => None, + }; + let (ring, target) = match (&fresh, &open) { + (Some((ring, dek)), _) => (ring, dek), + (None, Some(open)) => (&open.ring, open.active()), + (None, None) => unreachable!("every plan but Fresh has a ring"), + }; + + // Steps 4 and 5: the pass, then the catalog key goes. + let summary_parts = match &catalog_key { + Some(key) if plan != (Plan::Resume { catalog_key: false }) => { + let pass = run_pass( + stores.management, + stores.settings, + &PassKeys { + target, + old: vec![key], + }, + PassOptions { + keep_unopenable: flags.keep_unopenable, + plaintext_data_connection, + }, + ) + .await?; + reread_kek(kek_file, ring)?; + delete_catalog_key(stores, "switch").await?; + ( + pass.key_names, + pass.tables, + pass.unopenable, + pass.data_connection_rewritten, + true, + ) + } + _ => ( + survey.key_names.clone(), + survey.tables.clone(), + survey.unopenable().into_iter().cloned().collect(), + untouched(survey.data_connection), + false, + ), + }; + + // Step 6: the switch is finished. A run with --accept-catalog-key writes + // no new DEK and no ring. + if plan != Plan::Accept { + let finished = seal(&kek, &catalog_id, &[target], false, None)?; + write_ring(stores.settings, &finished, "switch", None).await?; + } + erase_free_space(stores, "switch").await?; + let (key_names, tables, unopenable, data_connection_rewritten, deleted_catalog_key) = + summary_parts; + Ok(Outcome::Done(Summary { + kek_id: kek_id(&kek), + dek_id: dek_id(target), + key_names, + tables, + data_connection_rewritten, + unopenable, + deleted_access_key_ids: Vec::new(), + deleted_catalog_key, + key_file: kek_file.path().to_owned(), + })) +} diff --git a/crates/storage/src/key_conformance.rs b/crates/storage/src/key_conformance.rs new file mode 100644 index 000000000..371eca807 --- /dev/null +++ b/crates/storage/src/key_conformance.rs @@ -0,0 +1,521 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The encryption-key command and startup cases of RFC-0000 section 15 that a +//! store can show, as one check that each backend's tests run with their own +//! store, as [`crate::metrics_conformance`] does. +//! +//! The check needs a fresh catalog that holds its catalog key (after `init`) +//! and no key ring, behind a store that holds that key. It first checks the +//! three answers of [`SettingsStore::replace_setting`] on a row of its own. +//! It then seeds an account, a user with two access keys and a role with two +//! sessions, one of them expired, then puts one access key's ciphertext under +//! no key with +//! [`ManagementStore::write_secrets`]. It then runs, in order: the preview and +//! the refused and the kept run of `switch`, a second `switch`, the loader +//! with and without the KEK, a catalog key written beside the finished ring +//! with and without `--accept-catalog-key`, a hand-edited ring, `rotate`, +//! `rewrap`, and `reset` for the KEK that `rewrap` replaced. After each step +//! it reads the rows back through [`ManagementStore::read_secret_page`]. + +use time::OffsetDateTime; +use zeroize::Zeroizing; + +use crate::key_commands::{ + KekFile, KeyCommandError, KeyStores, Outcome, RunFlags, reset, rewrap, rotate, switch, +}; +use crate::key_ring::{KEY_RING_SETTING, KeyRefusal, kek_id, open_ring}; +use crate::management_store::{ManagementStore, SecretWrite, SettingsStore, StoredSecretRow}; +use crate::secret_keys::{ + CATALOG_ID_SETTING, CATALOG_KEY_SETTING, DATA_CONNECTION_SETTING, SecretKeys, SecretRow, + SecretTable, +}; +use crate::server_components::{KeySource, load_secret_keys}; + +/// What the backend under test does beyond the common contract. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Expectations { + /// The store reports a write timestamp + /// ([`crate::management_store::StoredSecretRow::write_timestamp`]), which + /// Cassandra does. + pub write_timestamps: bool, + /// The catalog holds a `data_database_connection_string` row in + /// plaintext, which PostgreSQL does. + pub data_connection: bool, +} + +const ROLE: &str = "ConformanceRole"; +const USER: &str = "conformance-user"; +const SESSION: &str = "conformance-session"; + +/// A KEK file in memory. +struct MemoryKek(&'static str, [u8; 32]); + +impl KekFile for MemoryKek { + fn path(&self) -> &str { + self.0 + } + + fn read(&self) -> Result, String> { + Ok(Zeroizing::new(self.1)) + } +} + +/// Every row of `table`, through the paged read. +async fn all_rows(store: &dyn ManagementStore, table: SecretTable) -> Vec { + let mut rows = Vec::new(); + crate::key_pass::for_each_page(store, table, |page| { + rows.extend(page); + Ok(Vec::new()) + }) + .await + .unwrap_or_else(|e| panic!("read_secret_page({table:?}): {e}")); + rows +} + +/// The one row of `table` with `access_key_id`. +async fn row_of( + store: &dyn ManagementStore, + table: SecretTable, + access_key_id: &str, +) -> Option { + all_rows(store, table) + .await + .into_iter() + .find(|row| row.access_key_id == access_key_id) +} + +/// The key of each of `ids` among `keys`, by index, or `None`. +async fn opener( + store: &dyn ManagementStore, + table: SecretTable, + access_key_id: &str, + keys: &[&SecretKeys], +) -> Option { + let row = row_of(store, table, access_key_id).await.expect("the row"); + keys.iter().position(|key| { + key.decrypt(&row.aad_row(), &row.secret_key_encrypted) + .is_ok() + }) +} + +/// The active DEK of the catalog's ring under `kek`. +async fn ring_dek(settings: &dyn SettingsStore, kek: &[u8; 32]) -> SecretKeys { + let text = settings + .get_setting(KEY_RING_SETTING) + .await + .expect("read the ring") + .expect("a ring"); + let catalog_id = settings + .get_setting(CATALOG_ID_SETTING) + .await + .expect("read the catalog id"); + let mut open = open_ring(&text, catalog_id.as_deref(), kek).expect("the ring opens"); + open.deks.pop().expect("a DEK") +} + +fn done(step: &str, outcome: Result) -> crate::key_commands::Summary { + match outcome { + Ok(Outcome::Done(summary)) => summary, + other => panic!("{step}: expected the command to finish, got {other:?}"), + } +} + +fn refused(step: &str, outcome: Result, part: &str) { + match outcome { + Err(e) if e.to_string().contains(part) => {} + other => panic!("{step}: expected a refusal naming {part:?}, got {other:?}"), + } +} + +/// Runs the check against a fresh catalog behind `management` and `settings`, +/// which hold no `encryption_key_ring` row. `management` holds the catalog +/// key, so that its `create_access_key` writes. +/// +/// # Panics +/// +/// When a case's result differs from the expected one, or a store call fails. +pub async fn run( + management: &dyn ManagementStore, + settings: &dyn SettingsStore, + expect: Expectations, +) { + let stores = KeyStores { + management, + settings, + }; + let kek = MemoryKek("/etc/extenddb/kek", [0x4b; 32]); + let new_kek = MemoryKek("/etc/extenddb/kek.new", [0x6f; 32]); + let yes = RunFlags { + yes: true, + ..RunFlags::default() + }; + + // ── replace_setting, on a row that no command reads ─────────────── + const ROW: &str = "conformance_replace_setting"; + for (held, expected, replaced, after) in [ + (None, "a", false, None), + (Some("a"), "b", false, Some("a")), + (Some("a"), "a", true, Some("c")), + ] { + if let Some(held) = held { + settings.set_setting(ROW, held).await.expect("set_setting"); + } + let answer = settings + .replace_setting(ROW, expected, "c") + .await + .expect("replace_setting"); + let read = settings.get_setting(ROW).await.expect("get_setting"); + assert_eq!( + (answer, read.as_deref()), + (replaced, after), + "replace_setting of {held:?}, expecting {expected:?}" + ); + } + management + .delete_setting(ROW) + .await + .expect("delete_setting"); + + // ── Seed ─────────────────────────────────────────────────────── + let catalog_key = SecretKeys::catalog_key( + &settings + .get_setting(CATALOG_KEY_SETTING) + .await + .expect("read the catalog key") + .expect("a fresh catalog holds its catalog key"), + ) + .expect("a valid catalog key"); + let account = format!( + "{:012}", + OffsetDateTime::now_utc().unix_timestamp_nanos() % 1_000_000_000_000 + ); + management + .create_account(&account, "conformance") + .await + .expect("create_account"); + management + .create_user(&account, USER, None) + .await + .expect("create_user"); + management + .create_role( + &account, + ROLE, + &serde_json::json!({"Version": "2012-10-17", "Statement": []}), + ) + .await + .expect("create_role"); + let kept = management + .create_access_key(&account, USER) + .await + .expect("create_access_key") + .access_key_id; + let unopenable = management + .create_access_key(&account, USER) + .await + .expect("create_access_key") + .access_key_id; + let expires = |seconds: i64| OffsetDateTime::from_unix_timestamp(seconds).expect("a time"); + let live_until = OffsetDateTime::now_utc().unix_timestamp() + 3600; + let sessions = [ + ("ASIACONFORMANCE0001", live_until), + ("ASIACONFORMANCE0002", 1_000_000_000), + ]; + for (n, (access_key_id, expires_at)) in sessions.iter().enumerate() { + let row = SecretRow::session(access_key_id, &account, ROLE, SESSION, *expires_at); + management + .store_session( + &format!("conformance-token-{account}-{n}"), + access_key_id, + &catalog_key + .encrypt(&row, "conformance-secret") + .expect("encrypt"), + &account, + ROLE, + SESSION, + &None, + &None, + expires(*expires_at), + ) + .await + .expect("store_session"); + } + + // The paged read gives back each AAD field as written. + let session = row_of(management, SecretTable::IamSessions, sessions[0].0) + .await + .expect("the session row"); + assert_eq!( + ( + session.account_id.as_str(), + session.principal_name.as_str(), + session.session_name.as_deref(), + session.expires_at, + ), + (account.as_str(), ROLE, Some(SESSION), Some(live_until)), + "the session row's AAD fields" + ); + assert_eq!(session.write_timestamp.is_some(), expect.write_timestamps); + let key_row = row_of(management, SecretTable::AccessKeys, &kept) + .await + .expect("the access key row"); + assert_eq!( + ( + key_row.account_id.as_str(), + key_row.principal_name.as_str(), + key_row.session_name.as_deref(), + key_row.expires_at, + ), + (account.as_str(), USER, None, None), + "the access key row's AAD fields" + ); + + // One access key's secret under no key: a key the run does not hold. + let lost = row_of(management, SecretTable::AccessKeys, &unopenable) + .await + .expect("the row"); + let nobody = SecretKeys::dek_for_tests([0xee; 32], 9, "nobody"); + management + .write_secrets( + SecretTable::AccessKeys, + &[SecretWrite { + key: lost.key.clone(), + secret_key_encrypted: nobody.encrypt(&lost.aad_row(), "lost").expect("encrypt"), + write_timestamp: lost.write_timestamp, + }], + ) + .await + .expect("write_secrets"); + assert_eq!( + opener(management, SecretTable::AccessKeys, &unopenable, &[&nobody]).await, + Some(0), + "write_secrets wrote the new ciphertext" + ); + + // ── switch ───────────────────────────────────────────────────── + match switch(stores, &kek, RunFlags::default()).await { + Ok(Outcome::Preview(_)) => {} + other => panic!("switch preview: {other:?}"), + } + refused( + "switch with a secret under no key", + switch(stores, &kek, yes).await, + &unopenable, + ); + assert_eq!( + settings.get_setting(KEY_RING_SETTING).await.expect("read"), + None, + "a refused switch writes nothing" + ); + let summary = done( + "switch --keep-unopenable", + switch( + stores, + &kek, + RunFlags { + keep_unopenable: true, + ..yes + }, + ) + .await, + ); + assert_eq!( + summary + .unopenable + .iter() + .map(|s| s.access_key_id.as_str()) + .collect::>(), + [unopenable.as_str()] + ); + assert_eq!( + settings + .get_setting(CATALOG_KEY_SETTING) + .await + .expect("read"), + None, + "delete_setting deleted the catalog key" + ); + let dek = ring_dek(settings, &kek.1).await; + for (table, id) in [ + (SecretTable::AccessKeys, kept.as_str()), + (SecretTable::IamSessions, sessions[0].0), + (SecretTable::IamSessions, sessions[1].0), + ] { + assert_eq!( + opener(management, table, id, &[&dek]).await, + Some(0), + "{id} is under the DEK after the switch" + ); + } + if expect.data_connection { + let row = settings + .get_setting(DATA_CONNECTION_SETTING) + .await + .expect("read") + .expect("the connection string row"); + assert!( + dek.decrypt_setting(&row).is_ok(), + "the connection string row is under the DEK" + ); + assert_eq!(summary.data_connection_rewritten, Some(true)); + } + match switch(stores, &kek, yes).await { + Ok(Outcome::NothingToDo { kek_id: id, .. }) => assert_eq!(id, kek_id(&kek.1)), + other => panic!("a second switch: {other:?}"), + } + + // ── The loader ───────────────────────────────────────────────── + let loaded = load_secret_keys(settings, KeySource::Kek(Zeroizing::new(kek.1).into())) + .await + .expect("the server starts with the KEK") + .expect("a key"); + assert_eq!(loaded.dek_id(), dek.dek_id()); + let without_kek = load_secret_keys(settings, KeySource::CatalogKey) + .await + .expect_err("refused without key_file"); + assert!( + without_kek.to_string().contains( + &KeyRefusal::RingNeedsKeyFile { + kek_id: kek_id(&kek.1) + } + .to_string() + ) + ); + + // ── A catalog key beside the finished ring (8.5) ─────────────── + let forged_key = "QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUE="; + settings + .set_setting(CATALOG_KEY_SETTING, forged_key) + .await + .expect("set_setting"); + let forged = SecretKeys::catalog_key(forged_key).expect("a key"); + let row = row_of(management, SecretTable::AccessKeys, &kept) + .await + .expect("the row"); + management + .write_secrets( + SecretTable::AccessKeys, + &[SecretWrite { + key: row.key.clone(), + secret_key_encrypted: forged.encrypt(&row.aad_row(), "forged").expect("encrypt"), + write_timestamp: row.write_timestamp, + }], + ) + .await + .expect("write_secrets"); + let start = load_secret_keys(settings, KeySource::Kek(Zeroizing::new(kek.1).into())) + .await + .expect_err("refused beside a catalog key"); + assert!( + start + .to_string() + .contains(&KeyRefusal::CatalogKeyAfterSwitch.to_string()) + ); + refused( + "switch beside a catalog key", + switch(stores, &kek, yes).await, + "--accept-catalog-key", + ); + done( + "switch --accept-catalog-key", + switch( + stores, + &kek, + RunFlags { + accept_catalog_key: true, + keep_unopenable: true, + ..yes + }, + ) + .await, + ); + assert_eq!( + opener(management, SecretTable::AccessKeys, &kept, &[&dek]).await, + Some(0) + ); + assert_eq!( + settings + .get_setting(CATALOG_KEY_SETTING) + .await + .expect("read"), + None + ); + + // ── A hand-edited ring ───────────────────────────────────────── + let ring = settings + .get_setting(KEY_RING_SETTING) + .await + .expect("read") + .expect("a ring"); + let flipped = ring.replace( + "\"switch_from_catalog_key\":false", + "\"switch_from_catalog_key\":true", + ); + assert_ne!(flipped, ring); + settings + .set_setting(KEY_RING_SETTING, &flipped) + .await + .expect("set_setting"); + let start = load_secret_keys(settings, KeySource::Kek(Zeroizing::new(kek.1).into())) + .await + .expect_err("refused on a changed ring"); + assert!(start.to_string().contains("has damage or a changed field")); + settings + .set_setting(KEY_RING_SETTING, &ring) + .await + .expect("set_setting"); + + // ── rotate, rewrap, reset ────────────────────────────────────── + let summary = done( + "rotate", + rotate( + stores, + &kek, + RunFlags { + keep_unopenable: true, + ..yes + }, + ) + .await, + ); + assert_eq!(summary.dek_id, 2); + let rotated = ring_dek(settings, &kek.1).await; + for (table, id) in [ + (SecretTable::AccessKeys, kept.as_str()), + (SecretTable::IamSessions, sessions[1].0), + ] { + assert_eq!( + opener(management, table, id, &[&rotated]).await, + Some(0), + "{id} is under the new DEK" + ); + } + done("rewrap", rewrap(stores, &kek, &new_kek, true).await); + assert_eq!(ring_dek(settings, &new_kek.1).await.dek_id(), Some(2)); + // The KEK that rewrap replaced is a lost KEK for this ring. + let summary = done( + "reset", + reset( + stores, + &kek, + yes, + true, + expect + .data_connection + .then_some("postgres://extenddb:pw@localhost:5432/extenddb_data"), + ) + .await, + ); + assert_eq!(summary.dek_id, 3); + for table in SecretTable::ALL { + let left: Vec = all_rows(management, table) + .await + .into_iter() + .map(|row| row.access_key_id) + .filter(|id| *id == kept || *id == unopenable || id.starts_with("ASIACONFORMANCE")) + .collect(); + assert!(left.is_empty(), "reset left {left:?} in {table:?}"); + } + assert_eq!(ring_dek(settings, &kek.1).await.dek_id(), Some(3)); +} diff --git a/crates/storage/src/key_pass.rs b/crates/storage/src/key_pass.rs new file mode 100644 index 000000000..5a1463c11 --- /dev/null +++ b/crates/storage/src/key_pass.rs @@ -0,0 +1,532 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The pass over the stored secrets (RFC-0000 section 8.4), and the survey +//! that `status`, the previews and the check before a first write read. +//! +//! No stored byte records which key encrypted a secret, so the pass finds +//! each secret's key by trial: the target first, then each old key in turn. +//! A secret that opens under the target is done. A secret that opens under an +//! old key is re-encrypted under the target, with the AAD of section 5. Step 3 +//! reads every row again and stops when a secret still opens under an old +//! key: a store write that matches no row reports success, and so does a +//! Cassandra update whose write timestamp is not above the row's. A row that +//! is gone passes. +//! +//! The driver runs over [`ManagementStore`] and [`SettingsStore`] only, as +//! the pass of migration 2 does ([`crate::policy_migration`]). + +use std::collections::HashSet; + +use zeroize::Zeroizing; + +use crate::management_store::{ + ManagementStore, OpError, SecretPage, SecretWrite, SettingsStore, StoredSecretRow, +}; +use crate::secret_keys::{DATA_CONNECTION_SETTING, SecretKeys, SecretTable}; + +/// The most rows of one page read and one batch write. +pub const PAGE_SIZE: usize = 1000; + +/// The keys of one run: the target, then the old keys in the order the +/// trial tries them. +pub struct PassKeys<'a> { + /// The key every stored secret is under when the pass finishes. + pub target: &'a SecretKeys, + /// The keys the pass re-encrypts from: the catalog key in a switch, the + /// older DEK in a rotate, and both in a rotate with `--accept-catalog-key`. + pub old: Vec<&'a SecretKeys>, +} + +impl PassKeys<'_> { + /// The name of each key of the run: `[0]` for [`Opener::Target`], then + /// one per [`Opener::Old`] at `[i + 1]`: "the catalog key" or "DEK 2". + #[must_use] + pub fn names(&self) -> Vec { + std::iter::once(self.target) + .chain(self.old.iter().copied()) + .map(key_name) + .collect() + } +} + +/// "the catalog key", or "DEK ". +#[must_use] +pub fn key_name(keys: &SecretKeys) -> String { + match keys.dek_id() { + None => "the catalog key".to_owned(), + Some(id) => format!("DEK {id}"), + } +} + +/// Which key of a [`PassKeys`] opens a stored secret. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Opener { + /// [`PassKeys::target`]. + Target, + /// [`PassKeys::old`] at this index. + Old(usize), + /// No key of the run. + None, +} + +/// Find the key that opens `row`'s secret, target first, and wipe the +/// plaintext at once. +#[must_use] +pub fn open_by_trial(keys: &PassKeys<'_>, row: &StoredSecretRow) -> Opener { + trial(keys, row).0 +} + +/// [`open_by_trial`], keeping the plaintext of a secret under an old key, +/// which the pass re-encrypts. +fn trial(keys: &PassKeys<'_>, row: &StoredSecretRow) -> (Opener, Option>) { + let aad_row = row.aad_row(); + if keys + .target + .decrypt(&aad_row, &row.secret_key_encrypted) + .is_ok() + { + return (Opener::Target, None); + } + for (index, key) in keys.old.iter().enumerate() { + if let Ok(plaintext) = key.decrypt(&aad_row, &row.secret_key_encrypted) { + return (Opener::Old(index), Some(plaintext)); + } + } + (Opener::None, None) +} + +/// Each row of `table`, page by page; `each` returns the writes for its page, +/// which go out as one batch. +pub(crate) async fn for_each_page( + store: &dyn ManagementStore, + table: SecretTable, + mut each: impl FnMut(Vec) -> Result, PassError>, +) -> Result<(), PassError> { + let mut page: Option = None; + loop { + let SecretPage { rows, next } = store + .read_secret_page(table, page.as_deref(), PAGE_SIZE) + .await + .map_err(PassError::Store)?; + let writes = each(rows)?; + if !writes.is_empty() { + store + .write_secrets(table, &writes) + .await + .map_err(PassError::Store)?; + } + match next { + Some(next) => page = Some(next), + None => return Ok(()), + } + } +} + +fn listing(row: &StoredSecretRow, opener: Opener) -> SecretListing { + SecretListing { + table: row.table, + access_key_id: row.access_key_id.clone(), + account_id: row.account_id.clone(), + principal_name: row.principal_name.clone(), + created_at: row.created_at, + opener, + } +} + +/// `n` access key IDs as one line. +pub(crate) fn access_key_ids(listings: &[SecretListing]) -> String { + listings + .iter() + .map(|s| s.access_key_id.as_str()) + .collect::>() + .join(", ") +} + +/// One stored secret in a listing: never the secret, and never the row's +/// primary key. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SecretListing { + /// The table that holds the row. + pub table: SecretTable, + /// The access key ID. + pub access_key_id: String, + /// The account of the owner. + pub account_id: String, + /// The user or role that owns the secret. + pub principal_name: String, + /// When the row was created, when the backend stores it. + pub created_at: Option, + /// The key that opens the secret. + pub opener: Opener, +} + +/// The counts of one table. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TableCounts { + /// Rows under the target. + pub target: u64, + /// Rows under each old key, by the index of [`PassKeys::old`]. + pub old: Vec, + /// Rows that no key of the run opens. + pub unopenable: u64, + /// Rows the pass re-encrypted under the target. + pub rewritten: u64, +} + +impl TableCounts { + fn new(keys: &PassKeys<'_>) -> Self { + Self { + old: vec![0; keys.old.len()], + ..Self::default() + } + } + + fn count(&mut self, opener: Opener) { + match opener { + Opener::Target => self.target += 1, + Opener::Old(index) => self.old[index] += 1, + Opener::None => self.unopenable += 1, + } + } +} + +fn table_counts(keys: &PassKeys<'_>) -> [(SecretTable, TableCounts); 2] { + SecretTable::ALL.map(|table| (table, TableCounts::new(keys))) +} + +/// The state of the PostgreSQL `data_database_connection_string` row. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DataConnection { + /// The catalog has no such row: every backend but PostgreSQL. + Absent, + /// The row opens under this key of the run. + Opens(Opener), + /// The row opens under no key and is a connection string in plaintext: + /// the form before a switch (section 12). + Plaintext, + /// The row opens under no key and is not a connection string. + Unopenable, +} + +/// What a read-only survey of the stored secrets found. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Survey { + /// The name of each key of the run: `[0]` for [`Opener::Target`], then + /// one per [`Opener::Old`] at `[i + 1]` ([`PassKeys::names`]). + pub key_names: Vec, + /// The counts of `access_keys` and `iam_sessions`, in [`SecretTable::ALL`] order. + pub tables: [(SecretTable, TableCounts); 2], + /// Each stored secret under a key other than the target, unopenable + /// ones included. + pub not_target: Vec, + /// The connection string row. + pub data_connection: DataConnection, +} + +impl Survey { + /// The secrets that no key of the run opens. + #[must_use] + pub fn unopenable(&self) -> Vec<&SecretListing> { + self.not_target + .iter() + .filter(|s| s.opener == Opener::None) + .collect() + } +} + +/// Open every `access_keys` and `iam_sessions` secret, and the connection +/// string row, with the keys of the run, and wipe each plaintext at once. +/// Writes nothing. `status`, the previews, and the check before the first +/// write of `switch --yes` and `rotate --yes` read this. +/// +/// # Errors +/// +/// A store error. +pub async fn survey( + store: &dyn ManagementStore, + settings: &dyn SettingsStore, + keys: &PassKeys<'_>, +) -> Result { + let mut tables = table_counts(keys); + let mut not_target = Vec::new(); + for (table, counts) in &mut tables { + let read = for_each_page(store, *table, |rows| { + for row in &rows { + let opener = open_by_trial(keys, row); + counts.count(opener); + if opener != Opener::Target { + not_target.push(listing(row, opener)); + } + } + Ok(Vec::new()) + }) + .await; + match read { + Ok(()) => {} + Err(PassError::Store(e)) => return Err(e), + Err(other) => return Err(OpError::Internal(other.to_string())), + } + } + let (data_connection, _) = data_connection(settings, keys).await?; + Ok(Survey { + key_names: keys.names(), + tables, + not_target, + data_connection, + }) +} + +/// The state of the connection string row, and its plaintext when it opens +/// under an old key or is in the plaintext form. +async fn data_connection( + settings: &dyn SettingsStore, + keys: &PassKeys<'_>, +) -> Result<(DataConnection, Option>), OpError> { + let Some(value) = settings + .get_setting(DATA_CONNECTION_SETTING) + .await? + .map(Zeroizing::new) + else { + return Ok((DataConnection::Absent, None)); + }; + if keys.target.decrypt_setting(&value).is_ok() { + return Ok((DataConnection::Opens(Opener::Target), None)); + } + for (index, key) in keys.old.iter().enumerate() { + if let Ok(plaintext) = key.decrypt_setting(&value) { + return Ok((DataConnection::Opens(Opener::Old(index)), Some(plaintext))); + } + } + if is_connection_string(&value) { + Ok((DataConnection::Plaintext, Some(value))) + } else { + Ok((DataConnection::Unopenable, None)) + } +} + +/// Whether `value` is a PostgreSQL connection string in the URL form that +/// `init` and migration 1 write. +fn is_connection_string(value: &str) -> bool { + ["postgres://", "postgresql://"] + .iter() + .any(|scheme| value.len() > scheme.len() && value.starts_with(scheme)) +} + +/// The options of a pass. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PassOptions { + /// `--keep-unopenable`: leave the secrets that no key opens as they are + /// and list them, instead of stopping. + pub keep_unopenable: bool, + /// A switch: a connection string row that does not open under the + /// target is the plaintext form, which the pass encrypts (section 12). + /// Every other run refuses that row. + pub plaintext_data_connection: bool, +} + +/// What a pass did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PassSummary { + /// The name of each key of the run ([`PassKeys::names`]). + pub key_names: Vec, + /// The counts of each table after the pass, in [`SecretTable::ALL`] + /// order: each secret the pass re-encrypted counts under the target. + pub tables: [(SecretTable, TableCounts); 2], + /// The secrets that no key opens, kept as they are. + pub unopenable: Vec, + /// `None` without a connection string row, else whether the pass + /// rewrote it. + pub data_connection_rewritten: Option, +} + +/// Why a pass stopped. Every key is kept. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PassError { + /// A store call failed. + Store(OpError), + /// The cipher failed on an encrypt. + Cipher(String), + /// Secrets that no key opens, without `--keep-unopenable`. Found before + /// the first write. + Unopenable(Vec), + /// Step 3: secrets that still open under an old key after their write, + /// or that no key opens any more. + NotRewritten(Vec), + /// The connection string row does not open, or its plaintext form does + /// not parse. + DataConnection(String), +} + +impl std::fmt::Display for PassError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Store(e) => write!(f, "storage error: {}", e.message()), + Self::Cipher(reason) => write!(f, "encrypt a stored secret: {reason}"), + Self::Unopenable(listings) => write!( + f, + "{} stored secrets open under no key of this run: {}. Run \ + `extenddb encryption-key status`, or pass --keep-unopenable to leave them as \ + they are", + listings.len(), + access_key_ids(listings) + ), + Self::NotRewritten(listings) => write!( + f, + "{} stored secrets do not open under the target key after their write: {}. \ + A store write reported success and changed nothing. Every key is kept; run \ + the command again", + listings.len(), + access_key_ids(listings) + ), + Self::DataConnection(reason) => f.write_str(reason), + } + } +} + +impl std::error::Error for PassError {} + +/// Run the pass of section 8.4: open each row by trial, re-encrypt under the +/// target each secret that opens under an old key, in batches of +/// [`PAGE_SIZE`] by primary key, then read every row again (step 3). On +/// PostgreSQL it also handles the connection string row by the rules of +/// section 12. +/// +/// The caller holds the migration lock, ran the check before its first +/// write ([`survey`]), and after this returns re-reads the KEK file before +/// any old key goes. +/// +/// # Errors +/// +/// [`PassError`]; a run that stops runs again with the same arguments. +pub async fn run_pass( + store: &dyn ManagementStore, + settings: &dyn SettingsStore, + keys: &PassKeys<'_>, + options: PassOptions, +) -> Result { + // Steps 1 and 2: trial, then one batch write per page. + let mut tables = table_counts(keys); + let mut unopenable = Vec::new(); + let mut kept: HashSet<(SecretTable, String)> = HashSet::new(); + for (table, counts) in &mut tables { + for_each_page(store, *table, |rows| { + let mut writes = Vec::new(); + for row in &rows { + let (opener, plaintext) = trial(keys, row); + counts.count(opener); + match (opener, plaintext) { + (Opener::Old(_), Some(plaintext)) => { + let sealed = keys + .target + .encrypt(&row.aad_row(), &plaintext) + .map_err(PassError::Cipher)?; + counts.rewritten += 1; + writes.push(SecretWrite { + key: row.key.clone(), + secret_key_encrypted: sealed, + write_timestamp: row.write_timestamp, + }); + } + (Opener::None, _) => { + unopenable.push(listing(row, opener)); + kept.insert((row.table, row.key.clone())); + } + _ => {} + } + } + if !options.keep_unopenable && !unopenable.is_empty() { + return Err(PassError::Unopenable(std::mem::take(&mut unopenable))); + } + Ok(writes) + }) + .await?; + } + let data_connection_rewritten = rewrite_data_connection(settings, keys, options).await?; + + // Step 3: every row again. A row that is gone passes. + let mut not_rewritten = Vec::new(); + for table in SecretTable::ALL { + for_each_page(store, table, |rows| { + for row in &rows { + match open_by_trial(keys, row) { + Opener::Target => {} + Opener::None if kept.contains(&(row.table, row.key.clone())) => {} + opener => not_rewritten.push(listing(row, opener)), + } + } + Ok(Vec::new()) + }) + .await?; + } + if !not_rewritten.is_empty() { + return Err(PassError::NotRewritten(not_rewritten)); + } + if data_connection_rewritten.is_some() + && data_connection(settings, keys) + .await + .map_err(PassError::Store)? + .0 + != DataConnection::Opens(Opener::Target) + { + return Err(PassError::DataConnection( + "the data_database_connection_string row does not open under the target key after \ + its write. Every key is kept; run the command again" + .to_owned(), + )); + } + // The counts after the pass. Step 3 read every row again and found each + // one under the target or kept as unopenable, so each secret that steps + // 1 and 2 re-encrypted is under the target now, and none is under an old + // key. + for (_, counts) in &mut tables { + counts.target += counts.rewritten; + counts.old.fill(0); + } + Ok(PassSummary { + key_names: keys.names(), + tables, + unopenable, + data_connection_rewritten, + }) +} + +/// Steps 1 and 2 for the connection string row: `None` without the row, +/// else whether the pass rewrote it. +async fn rewrite_data_connection( + settings: &dyn SettingsStore, + keys: &PassKeys<'_>, + options: PassOptions, +) -> Result, PassError> { + let (state, plaintext) = data_connection(settings, keys) + .await + .map_err(PassError::Store)?; + let plaintext = match (state, plaintext) { + (DataConnection::Absent, _) => return Ok(None), + (DataConnection::Opens(Opener::Target), _) => return Ok(Some(false)), + (DataConnection::Plaintext, _) if !options.plaintext_data_connection => { + return Err(PassError::DataConnection( + "the data_database_connection_string row is not encrypted under a DEK of the \ + key ring. Run `extenddb encryption-key set-data-connection` to write it" + .to_owned(), + )); + } + (_, Some(plaintext)) => plaintext, + (_, None) => { + return Err(PassError::DataConnection( + "the data_database_connection_string row opens under no key of this run and is \ + not a connection string. Run `extenddb encryption-key status`" + .to_owned(), + )); + } + }; + let sealed = keys + .target + .encrypt_setting(&plaintext) + .map_err(PassError::Cipher)?; + settings + .set_setting(DATA_CONNECTION_SETTING, &sealed) + .await + .map_err(PassError::Store)?; + Ok(Some(true)) +} diff --git a/crates/storage/src/key_ring.rs b/crates/storage/src/key_ring.rs new file mode 100644 index 000000000..dcdb09e76 --- /dev/null +++ b/crates/storage/src/key_ring.rs @@ -0,0 +1,627 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The key ring (RFC-0000 section 4): the `encryption_key_ring` settings row +//! of a deployment with a KEK file. +//! +//! ```json +//! {"version":1,"kek":{"source":"file","id":"3f9a0c51e2d47b86"},"keys":[{"id":2,"wrapped":""}],"switch_from_catalog_key":false,"retiring_catalog_key_id":null} +//! ``` +//! +//! Each `wrapped` value is a DEK sealed under the KEK by the secret cipher. Its +//! AAD covers every other field of the ring and the sorted list of DEK ids, +//! so a changed field, an added or deleted entry, or a wrapped DEK copied from +//! another ring makes every DEK fail to unwrap. Every write of the ring +//! re-seals each DEK ([`KeyRing::seal`]). The DEK with the highest id is the +//! active one, and the order of `keys` carries no meaning. + +use std::fmt; +use std::sync::Arc; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as BASE64; +use serde::{Deserialize, Serialize}; +use zeroize::Zeroizing; + +use crate::management_store::{OpError, SettingsStore}; +use crate::secret_cipher::{self, KEY_LEN}; +use crate::secret_keys::{ + AadKind, CATALOG_ID_SETTING, CATALOG_KEY_SETTING, KeyBytes, SecretKeys, encode_aad, +}; + +/// The settings row that holds the key ring. +pub const KEY_RING_SETTING: &str = "encryption_key_ring"; + +/// The ring format this release writes and reads. +pub const RING_VERSION: u64 = 1; + +/// The message of a KEK id, under HMAC-SHA256 keyed with the KEK. +const KEK_ID_MESSAGE: &[u8] = b"extenddb key-encryption-key id"; + +/// Where the KEK comes from. This release knows one source. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum KekSource { + /// The file that `[auth.encryption] key_file` names. + File, +} + +impl KekSource { + /// The source's value in the ring and in the AAD. + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Self::File => "file", + } + } +} + +/// A key id: the first 8 bytes, in lowercase hex, of HMAC-SHA256 keyed with +/// a KEK. It identifies a key and does not reveal it. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +#[serde(transparent)] +pub struct KeyId(String); + +impl KeyId { + /// Parse 16 lowercase hex characters. + /// + /// # Errors + /// + /// For any other text, the empty string included. + pub fn parse(text: &str) -> Result { + if text.len() == 16 + && text + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + Ok(Self(text.to_owned())) + } else { + Err(format!( + "a key id is 16 lowercase hex characters, not {text:?}" + )) + } + } + + /// The 16 hex characters. + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for KeyId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl<'de> Deserialize<'de> for KeyId { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Self::parse(&text).map_err(serde::de::Error::custom) + } +} + +/// The id of a KEK: HMAC-SHA256 keyed with the KEK over +/// `extenddb key-encryption-key id`. +#[must_use] +pub fn kek_id(kek: &[u8; KEY_LEN]) -> KeyId { + key_id(kek, KEK_ID_MESSAGE) +} + +/// The id of a catalog key under a KEK: HMAC-SHA256 keyed with the KEK over +/// the 32 decoded bytes of the catalog key. `retiring_catalog_key_id` holds it +/// during a switch. +#[must_use] +pub fn catalog_key_id(kek: &[u8; KEY_LEN], catalog_key: &SecretKeys) -> KeyId { + key_id(kek, catalog_key.key_bytes().expose()) +} + +fn key_id(kek: &[u8; KEY_LEN], message: &[u8]) -> KeyId { + let tag = aws_lc_rs::hmac::sign( + &aws_lc_rs::hmac::Key::new(aws_lc_rs::hmac::HMAC_SHA256, kek), + message, + ); + let tag = &tag.as_ref()[..8]; + KeyId(tag.iter().map(|b| format!("{b:02x}")).collect()) +} + +/// Parse the contents of a KEK file (section 2): 32 bytes in standard base64 +/// with padding, which is 44 characters, and at most one trailing newline. +/// +/// The key is decoded into the one allocation that holds it until the last +/// [`Kek`] drops. +/// +/// # Errors +/// +/// For anything else. The reason of a file that does not decode is the one +/// the secret cipher gives for a damaged catalog key, which names the kind of +/// error and its offset and never a character of the file. +pub fn parse_kek_file(contents: &[u8]) -> Result { + let text = contents.strip_suffix(b"\n").unwrap_or(contents); + if text.len() != 44 { + return Err(format!( + "a KEK file holds 44 characters of base64 and at most one trailing newline; \ + this one holds {} bytes", + contents.len() + )); + } + let text = std::str::from_utf8(text).map_err(|e| { + format!( + "decode encryption key: not text at offset {}", + e.valid_up_to() + ) + })?; + let mut kek = Arc::new(Zeroizing::new([0; KEY_LEN])); + secret_cipher::decode_key_into(text, Arc::get_mut(&mut kek).expect("a new Arc"))?; + Ok(kek) +} + +/// A KEK, in one heap allocation that is wiped when the last reference +/// drops. A move or a clone copies a pointer and leaves no copy of the key. +pub type Kek = Arc>; + +/// The KEK entry of a ring. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct KekRef { + /// Where the KEK comes from. + pub source: KekSource, + /// The KEK's id ([`kek_id`]). + pub id: KeyId, +} + +/// One wrapped DEK of a ring. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WrappedDek { + /// The DEK id. Ids start at 1, and each DEK replacement takes the next. + pub id: u64, + /// The DEK sealed under the KEK, in base64. + pub wrapped: String, +} + +/// The `encryption_key_ring` row. +/// +/// The parser refuses a field that the format does not have and a value of +/// another type. Every field is required; `retiring_catalog_key_id` is null +/// or a key id, never an empty string. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct KeyRing { + /// The ring format, [`RING_VERSION`]. + pub version: u64, + /// The KEK that wraps every DEK. + pub kek: KekRef, + /// One DEK, or two during an unfinished DEK replacement. + pub keys: Vec, + /// True from the start of a switch until the switch finishes. + pub switch_from_catalog_key: bool, + /// The id of the catalog key that an unfinished switch retires. + #[serde(deserialize_with = "Option::deserialize")] + pub retiring_catalog_key_id: Option, +} + +impl KeyRing { + /// Parse the text of the `encryption_key_ring` row. + /// + /// # Errors + /// + /// For text that is not a ring of this release: an unknown or missing + /// field, a value of another type, another version, no DEK or more than + /// two, a DEK id of 0, or two entries with one id. + pub fn parse(text: &str) -> Result { + let ring: Self = serde_json::from_str(text).map_err(|e| format!("{e}"))?; + ring.check_shape()?; + Ok(ring) + } + + /// The version, and one or two DEKs with distinct ids from 1. + fn check_shape(&self) -> Result<(), String> { + if self.version != RING_VERSION { + return Err(format!( + "version {} is not the ring version {RING_VERSION} of this release", + self.version + )); + } + let ids = self.dek_ids(); + if ids.is_empty() || ids.len() > 2 { + return Err(format!("a ring holds one or two DEKs, not {}", ids.len())); + } + if ids[0] == 0 || ids.windows(2).any(|w| w[0] == w[1]) { + return Err("DEK ids start at 1 and each appears once".to_owned()); + } + Ok(()) + } + + /// The row text. + #[must_use] + pub fn to_json(&self) -> String { + serde_json::to_string(self).expect("a key ring serializes") + } + + /// The DEK ids, in increasing order. + #[must_use] + pub fn dek_ids(&self) -> Vec { + let mut ids: Vec = self.keys.iter().map(|k| k.id).collect(); + ids.sort_unstable(); + ids + } + + /// The id of the active DEK, the highest. + #[must_use] + pub fn active_dek_id(&self) -> u64 { + self.keys.iter().map(|k| k.id).max().unwrap_or(0) + } + + /// The id of the DEK that a rotation or a reset writes next, one above + /// the active DEK's. The ring row carries the active id, so a row that + /// was written by hand can hold `u64::MAX`, which has no successor. + /// + /// # Errors + /// + /// [`KeyRefusal::DamagedRing`] when the active id is `u64::MAX`. + pub fn next_dek_id(&self) -> Result { + let active = self.active_dek_id(); + active + .checked_add(1) + .ok_or_else(|| KeyRefusal::DamagedRing { + reason: format!( + "the active DEK's id is {active}, the largest id a ring holds, so this run \ + has no id for a new DEK" + ), + }) + } + + /// The AAD of DEK `id` in a ring of this state. + fn dek_aad(&self, catalog_id: &str, id: u64) -> String { + let ids = self + .dek_ids() + .iter() + .map(u64::to_string) + .collect::>() + .join(","); + encode_aad( + AadKind::Dek, + &[ + &self.version.to_string(), + catalog_id, + self.kek.source.name(), + self.kek.id.as_str(), + &ids, + &id.to_string(), + if self.switch_from_catalog_key { + "true" + } else { + "false" + }, + self.retiring_catalog_key_id + .as_ref() + .map_or("", KeyId::as_str), + ], + ) + } + + /// Unwrap every DEK under `kek`, in increasing id order. + /// + /// The caller compares [`kek_id`] with `kek.id` first. No other field of + /// the ring is authentic until this returns `Ok`. + /// + /// # Errors + /// + /// The ids of the DEKs that fail to unwrap, when any does. + pub fn unwrap( + &self, + kek: &[u8; KEY_LEN], + catalog_id: &str, + ) -> Result, Vec> { + let mut deks = Vec::with_capacity(self.keys.len()); + let mut failed = Vec::new(); + let mut entries: Vec<&WrappedDek> = self.keys.iter().collect(); + entries.sort_unstable_by_key(|k| k.id); + for entry in entries { + let opened = BASE64 + .decode(&entry.wrapped) + .map_err(|_| ()) + .and_then(|sealed| { + secret_cipher::open(kek, &sealed, &self.dek_aad(catalog_id, entry.id)) + .map_err(|_| ()) + }) + .and_then(|plain| { + let mut key = Zeroizing::new([0; KEY_LEN]); + if plain.len() != KEY_LEN { + return Err(()); + } + key.copy_from_slice(&plain); + Ok(key) + }); + match opened { + // The store is sized for every key a run holds at once + // (`serve_slots` and `COMMAND_SLOTS` in the server crate), + // so a full store here is a sizing defect, not a ring fault. + Ok(key) => deks.push(SecretKeys::dek( + KeyBytes::new(key).expect("a free slot of the locked key store for a DEK"), + entry.id, + catalog_id, + )), + Err(()) => failed.push(entry.id), + } + } + if failed.is_empty() { + Ok(deks) + } else { + Err(failed) + } + } + + /// Build a ring that holds `deks`, each wrapped under `kek` with the AAD + /// of the new state. + /// + /// # Errors + /// + /// When `deks` is empty or holds more than two keys, when a key is not a + /// DEK of `catalog_id`, or on a cipher error. + pub fn seal( + kek: &[u8; KEY_LEN], + catalog_id: &str, + deks: &[&SecretKeys], + switch_from_catalog_key: bool, + retiring_catalog_key_id: Option, + ) -> Result { + let mut ring = Self { + version: RING_VERSION, + kek: KekRef { + source: KekSource::File, + id: kek_id(kek), + }, + keys: Vec::with_capacity(deks.len()), + switch_from_catalog_key, + retiring_catalog_key_id, + }; + for dek in deks { + if dek.catalog_id() != Some(catalog_id) { + return Err("a ring holds only DEKs of its own catalog".to_owned()); + } + let id = dek.dek_id().ok_or("the catalog key is not a DEK")?; + ring.keys.push(WrappedDek { + id, + wrapped: String::new(), + }); + } + ring.check_shape()?; + // Every id is in `ring.keys` now, so each AAD holds the whole list. + let wrapped = deks + .iter() + .zip(&ring.keys) + .map(|(dek, entry)| { + secret_cipher::seal( + kek, + dek.key_bytes().expose(), + &ring.dek_aad(catalog_id, entry.id), + ) + .map(|sealed| BASE64.encode(sealed)) + }) + .collect::, _>>()?; + for (entry, wrapped) in ring.keys.iter_mut().zip(wrapped) { + entry.wrapped = wrapped; + } + Ok(ring) + } +} + +/// A new DEK with id `id` for catalog `catalog_id`, from the generator that +/// `init` uses for the catalog key. +/// +/// # Errors +/// +/// When the random number generator fails. +pub fn new_dek(id: u64, catalog_id: &str) -> Result { + Ok(SecretKeys::dek(KeyBytes::generate()?, id, catalog_id)) +} + +/// The key rows of a catalog, as the loader and the commands read them. +pub struct KeyRows { + /// The `encryption_key` row: the catalog key in base64. Wiped on drop. + pub catalog_key: Option>, + /// The `encryption_key_ring` row. + pub ring: Option, + /// The `catalog_id` row. + pub catalog_id: Option, +} + +impl KeyRows { + /// Read the three rows through [`SettingsStore::get_setting`]. + /// + /// # Errors + /// + /// A store error. + pub async fn read(settings: &dyn SettingsStore) -> Result { + Ok(Self { + catalog_key: settings + .get_setting(CATALOG_KEY_SETTING) + .await? + .map(Zeroizing::new), + ring: settings.get_setting(KEY_RING_SETTING).await?, + catalog_id: settings.get_setting(CATALOG_ID_SETTING).await?, + }) + } +} + +/// A ring whose every DEK unwrapped under the KEK: all its fields are +/// authentic. +pub struct OpenRing { + /// The ring as stored. + pub ring: KeyRing, + /// Its DEKs, in increasing id order. The last is the active one. + pub deks: Vec, +} + +impl OpenRing { + /// The active DEK, the one with the highest id. + #[must_use] + pub fn active(&self) -> &SecretKeys { + self.deks.last().expect("an open ring holds a DEK") + } + + /// The older DEK of a ring that holds two. + #[must_use] + pub fn older(&self) -> Option<&SecretKeys> { + (self.deks.len() == 2).then(|| &self.deks[0]) + } +} + +/// Open the ring row with `kek` in the order of section 7: parse it, compare +/// the KEK ids, then unwrap every DEK. No other field is read before all of +/// them unwrap. +/// +/// # Errors +/// +/// [`KeyRefusal::KekMismatch`] or [`KeyRefusal::DamagedRing`]. +pub fn open_ring( + ring_text: &str, + catalog_id: Option<&str>, + kek: &[u8; KEY_LEN], +) -> Result { + let ring = KeyRing::parse(ring_text).map_err(|reason| KeyRefusal::DamagedRing { + reason: format!("the ring does not parse: {reason}"), + })?; + let configured = kek_id(kek); + if ring.kek.id != configured { + return Err(KeyRefusal::KekMismatch { + ring: ring.kek.id.clone(), + configured, + }); + } + let catalog_id = catalog_id.ok_or_else(|| KeyRefusal::DamagedRing { + reason: "the catalog has no catalog_id row, which the ring's AAD holds".to_owned(), + })?; + let deks = ring + .unwrap(kek, catalog_id) + .map_err(|failed| KeyRefusal::DamagedRing { + reason: match failed.as_slice() { + [id] => format!("DEK {id} fails to unwrap"), + ids => format!("DEKs {} fail to unwrap", join_ids(ids)), + }, + })?; + Ok(OpenRing { ring, deks }) +} + +/// Ids as `1, 2`. +pub(crate) fn join_ids(ids: &[u64]) -> String { + ids.iter() + .map(u64::to_string) + .collect::>() + .join(", ") +} + +/// Where the refusals send an operator for a restore (RFC-0000 section 11). +/// The text names the heading of that section, so an operator can search +/// the manual for it. +pub(crate) const RESTORE_STEPS: &str = + "see \"Restore a damaged or missing key ring\" in docs/manuals/14-backup-and-restore.md"; + +/// Where the refusal of a ring under another KEK sends an operator whose +/// KEK is gone: the steps that run `reset` (RFC-0000 section 11). +pub(crate) const LOST_KEK_STEPS: &str = + "see \"The KEK of a catalog copy is lost\" in docs/manuals/14-backup-and-restore.md"; + +/// A key state that the server and the commands refuse (RFC-0000 section 7). +/// Its `Display` is the message, which names the next step. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeyRefusal { + /// No `key_file`, and a ring whose switch did not finish. + UnfinishedSwitchWithoutKeyFile, + /// No `key_file`, and a finished ring. + RingNeedsKeyFile { + /// The ring's KEK id, not authenticated. + kek_id: KeyId, + }, + /// `key_file` set, a catalog key row and no ring. + CatalogKeyWithoutRing, + /// `key_file` set, and neither key row. + NoRing, + /// The ring names another KEK. + KekMismatch { + /// The ring's KEK id. + ring: KeyId, + /// The id of the KEK the run was given. + configured: KeyId, + }, + /// The ring does not parse, or a DEK fails to unwrap. + DamagedRing { + /// What failed. + reason: String, + }, + /// `key_file` set, and a ring whose switch did not finish. + UnfinishedSwitchWithKeyFile, + /// A catalog key row beside a finished ring. + CatalogKeyAfterSwitch, + /// A ring with two DEKs. + UnfinishedRotation, +} + +impl fmt::Display for KeyRefusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnfinishedSwitchWithoutKeyFile => write!( + f, + "the catalog's encryption_key_ring row says that a switch to a KEK file did not \ + finish. Run `extenddb encryption-key switch --key-file --yes` with the KEK \ + file of that switch: it checks the ring and resumes the switch. If no switch of \ + yours stopped, {RESTORE_STEPS} first" + ), + Self::RingNeedsKeyFile { kek_id } => write!( + f, + "the catalog's stored secrets are under a key ring wrapped by the KEK with id \ + {kek_id}. Set [auth.encryption] key_file to the file that holds that KEK" + ), + Self::CatalogKeyWithoutRing => write!( + f, + "[auth.encryption] key_file is set, but the catalog has no encryption_key_ring \ + row and holds an encryption_key row. key_file is set only after a switch \ + finishes, so the ring was deleted or key_file was set too early. Run \ + `extenddb encryption-key status`, and {RESTORE_STEPS}" + ), + Self::NoRing => write!( + f, + "[auth.encryption] key_file is set, but the catalog has no encryption_key_ring \ + row. Restore a catalog copy that holds it: {RESTORE_STEPS}" + ), + Self::KekMismatch { ring, configured } => write!( + f, + "the catalog's key ring is wrapped by the KEK with id {ring}, and the key file \ + holds the KEK with id {configured}. After an `extenddb encryption-key rewrap`, \ + set key_file to the new file. If key_file names the KEK that your last \ + `encryption-key` run wrote the ring under and you restored no catalog copy \ + since that run, a writer to the catalog database put this ring row back: \ + {RESTORE_STEPS}. Otherwise find the KEK with id {ring} and set key_file to it; \ + if that KEK is lost, {LOST_KEK_STEPS}" + ), + Self::DamagedRing { reason } => write!( + f, + "the catalog's key ring has damage or a changed field: {reason}. Run \ + `extenddb encryption-key status`, and {RESTORE_STEPS}" + ), + Self::UnfinishedSwitchWithKeyFile => write!( + f, + "the catalog's key ring says that a switch to a KEK file did not finish, and \ + [auth.encryption] key_file is already set, which is done only after a switch \ + finishes. key_file was set while a stopped switch was unfinished, or the ring \ + row was written back from a catalog copy taken during a switch. Run \ + `extenddb encryption-key status`, and {RESTORE_STEPS}" + ), + Self::CatalogKeyAfterSwitch => write!( + f, + "the catalog holds an encryption_key row beside a finished switch to a KEK \ + file: a catalog key appeared after the switch. Run \ + `extenddb encryption-key status`, which lists the stored secrets under that key" + ), + Self::UnfinishedRotation => write!( + f, + "the catalog's key ring holds two DEKs: a DEK replacement did not finish. \ + `extenddb encryption-key rotate` lists the stored secrets under the older DEK, \ + and `extenddb encryption-key rotate --yes` resumes it" + ), + } + } +} diff --git a/crates/storage/src/key_tests/commands.rs b/crates/storage/src/key_tests/commands.rs new file mode 100644 index 000000000..d2c18820d --- /dev/null +++ b/crates/storage/src/key_tests/commands.rs @@ -0,0 +1,614 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::pass::{FakeKek, Under, access_key_row, catalog_with, openers, session_row}; +use super::*; + +// ── The commands (sections 8.1 to 8.3, 8.5, 8.6) ─────────────────────── + +/// The key of each row after a command: the active DEK of the ring that +/// `kek` opens, else the fixed keys of [`Under`]. +pub(super) fn openers_after(catalog: &FakeCatalog, ids: &[&str], kek: &[u8; 32]) -> Vec { + let ring = catalog + .get(KEY_RING_SETTING) + .and_then(|text| open_ring(&text, Some(CATALOG_ID), kek).ok()); + ids.iter() + .map(|id| { + let (table, row) = if id.starts_with("ASIA") { + (SecretTable::IamSessions, session_row(id)) + } else { + (SecretTable::AccessKeys, access_key_row(id)) + }; + let stored = catalog.stored(table, id).expect("row"); + if ring + .as_ref() + .is_some_and(|open| open.active().decrypt(&row, &stored).is_ok()) + { + return Under::RingActive; + } + openers(catalog, &[id])[0] + }) + .collect() +} + +#[tokio::test] +async fn command_cases() { + use crate::key_commands::{KeyStores, Outcome, RunFlags, reset, rewrap, rotate, switch}; + use crate::secret_keys::DATA_CONNECTION_SETTING; + + const CONNECTION: &str = "postgres://extenddb:pw@db.internal:5432/extenddb_data"; + let catalog_key_bytes: [u8; 32] = std::array::from_fn(|i| i as u8); + let retiring = Some(catalog_key_id(&KEK, &catalog_key())); + let ring = |kek: &[u8; 32], ids: &[u64], switch: bool, retiring: Option| { + ring_text(kek, ids, switch, retiring) + }; + + #[derive(Clone, Copy)] + enum Cmd { + Switch, + Rotate, + Rewrap([u8; 32]), + Reset { discard: bool }, + } + #[derive(Debug)] + enum Expect { + NothingToDo, + Preview, + Done, + Refused(&'static str), + } + struct Case { + name: &'static str, + catalog_key: bool, + ring: Option, + connection: Option<&'static str>, + rows: Vec<(&'static str, Under)>, + cmd: Cmd, + kek: FakeKek, + flags: RunFlags, + expect: Expect, + /// The key of each row after the run; empty when the rows are gone. + after: Vec, + /// The DEK ids and the flag of the ring after the run. + ring_after: Option<(Vec, bool)>, + catalog_key_after: bool, + } + let yes = RunFlags { + yes: true, + ..RunFlags::default() + }; + let kek = || FakeKek::new(KEK); + let mixed = vec![ + ("AKIAKEY000000000001", Under::CatalogKey), + ("ASIASESSION00000001", Under::CatalogKey), + ]; + let cases = vec![ + Case { + name: "switch: the preview writes nothing", + catalog_key: true, + ring: None, + connection: None, + rows: mixed.clone(), + cmd: Cmd::Switch, + kek: kek(), + flags: RunFlags::default(), + expect: Expect::Preview, + after: vec![Under::CatalogKey, Under::CatalogKey], + ring_after: None, + catalog_key_after: true, + }, + Case { + name: "switch: a fresh run", + catalog_key: true, + ring: None, + connection: Some(CONNECTION), + rows: mixed.clone(), + cmd: Cmd::Switch, + kek: kek(), + flags: yes, + expect: Expect::Done, + after: vec![Under::RingActive, Under::RingActive], + ring_after: Some((vec![1], false)), + catalog_key_after: false, + }, + Case { + name: "switch: a second run has nothing to do", + catalog_key: false, + ring: Some(ring(&KEK, &[1], false, None)), + connection: None, + rows: vec![("AKIAKEY000000000001", Under::Dek(1))], + cmd: Cmd::Switch, + kek: kek(), + flags: yes, + expect: Expect::NothingToDo, + after: vec![Under::RingActive], + ring_after: Some((vec![1], false)), + catalog_key_after: false, + }, + Case { + name: "switch: refused while key_file is set", + catalog_key: true, + ring: None, + connection: None, + rows: mixed.clone(), + cmd: Cmd::Switch, + kek: kek(), + flags: RunFlags { + key_file_configured: true, + ..yes + }, + expect: Expect::Refused("Unset it for this run"), + after: vec![Under::CatalogKey, Under::CatalogKey], + ring_after: None, + catalog_key_after: true, + }, + Case { + name: "switch: a KEK equal to the catalog key", + catalog_key: true, + ring: None, + connection: None, + rows: vec![], + cmd: Cmd::Switch, + kek: FakeKek::new(catalog_key_bytes), + flags: yes, + expect: Expect::Refused("the KEK equals the catalog key"), + after: vec![], + ring_after: None, + catalog_key_after: true, + }, + Case { + name: "switch: a secret under no key stops the run before its first write", + catalog_key: true, + ring: None, + connection: None, + rows: vec![ + ("AKIAKEY000000000001", Under::CatalogKey), + ("AKIANOKEY0000000001", Under::NoKey), + ], + cmd: Cmd::Switch, + kek: kek(), + flags: yes, + expect: Expect::Refused( + "1 stored secrets open under no key of this run: AKIANOKEY0000000001", + ), + after: vec![Under::CatalogKey, Under::NoKey], + ring_after: None, + catalog_key_after: true, + }, + Case { + name: "switch: --keep-unopenable keeps a secret under no key", + catalog_key: true, + ring: None, + connection: None, + rows: vec![ + ("AKIAKEY000000000001", Under::CatalogKey), + ("AKIANOKEY0000000001", Under::NoKey), + ], + cmd: Cmd::Switch, + kek: kek(), + flags: RunFlags { + keep_unopenable: true, + ..yes + }, + expect: Expect::Done, + after: vec![Under::RingActive, Under::NoKey], + ring_after: Some((vec![1], false)), + catalog_key_after: false, + }, + Case { + name: "switch: the KEK file is gone before the catalog key goes", + catalog_key: true, + ring: None, + connection: None, + rows: mixed.clone(), + cmd: Cmd::Switch, + kek: FakeKek { + gone_after: Some(1), + ..kek() + }, + flags: yes, + expect: Expect::Refused("cannot be read again before the old key is deleted"), + after: vec![Under::RingActive, Under::RingActive], + ring_after: Some((vec![1], true)), + catalog_key_after: true, + }, + Case { + name: "switch: a stopped run resumes", + catalog_key: true, + ring: Some(ring(&KEK, &[1], true, retiring.clone())), + connection: None, + rows: vec![ + ("AKIAKEY000000000001", Under::Dek(1)), + ("ASIASESSION00000001", Under::CatalogKey), + ], + cmd: Cmd::Switch, + kek: kek(), + flags: yes, + expect: Expect::Done, + after: vec![Under::RingActive, Under::RingActive], + ring_after: Some((vec![1], false)), + catalog_key_after: false, + }, + Case { + name: "switch: stopped between the catalog key delete and the last ring write", + catalog_key: false, + ring: Some(ring(&KEK, &[1], true, retiring.clone())), + connection: None, + rows: vec![("AKIAKEY000000000001", Under::Dek(1))], + cmd: Cmd::Switch, + kek: kek(), + flags: yes, + expect: Expect::Done, + after: vec![Under::RingActive], + ring_after: Some((vec![1], false)), + catalog_key_after: false, + }, + Case { + name: "switch: a catalog key that the unfinished switch does not retire", + catalog_key: true, + ring: Some(ring( + &KEK, + &[1], + true, + Some(KeyId::parse("00112233aabbccdd").unwrap()), + )), + connection: None, + rows: vec![("AKIAKEY000000000001", Under::CatalogKey)], + cmd: Cmd::Switch, + kek: kek(), + flags: yes, + expect: Expect::Refused("not the catalog key that the unfinished switch retires"), + after: vec![Under::CatalogKey], + ring_after: Some((vec![1], true)), + catalog_key_after: true, + }, + Case { + name: "switch: a catalog key beside a finished ring, without --accept-catalog-key", + catalog_key: true, + ring: Some(ring(&KEK, &[1], false, None)), + connection: None, + rows: vec![("AKIAFORGED000000001", Under::CatalogKey)], + cmd: Cmd::Switch, + kek: kek(), + flags: yes, + expect: Expect::Refused("--accept-catalog-key"), + after: vec![Under::CatalogKey], + ring_after: Some((vec![1], false)), + catalog_key_after: true, + }, + Case { + name: "switch: a catalog key beside a finished ring, with --accept-catalog-key", + catalog_key: true, + ring: Some(ring(&KEK, &[1], false, None)), + connection: None, + rows: vec![ + ("AKIAFORGED000000001", Under::CatalogKey), + ("AKIAKEY000000000001", Under::Dek(1)), + ], + cmd: Cmd::Switch, + kek: kek(), + flags: RunFlags { + accept_catalog_key: true, + ..yes + }, + expect: Expect::Done, + after: vec![Under::RingActive, Under::RingActive], + ring_after: Some((vec![1], false)), + catalog_key_after: false, + }, + Case { + name: "rotate: a fresh run", + catalog_key: false, + ring: Some(ring(&KEK, &[1], false, None)), + connection: Some("under DEK 1"), + rows: vec![ + ("AKIAKEY000000000001", Under::Dek(1)), + ("ASIASESSION00000001", Under::Dek(1)), + ], + cmd: Cmd::Rotate, + kek: kek(), + flags: yes, + expect: Expect::Done, + after: vec![Under::RingActive, Under::RingActive], + ring_after: Some((vec![2], false)), + catalog_key_after: false, + }, + Case { + name: "rotate: a stopped run resumes, with the ring's entries in either order", + catalog_key: false, + ring: Some(edit_ring(&ring(&KEK, &[1, 2], false, None), |r| { + r["keys"].as_array_mut().unwrap().reverse(); + })), + connection: None, + rows: vec![ + ("AKIAKEY000000000001", Under::Dek(2)), + ("ASIASESSION00000001", Under::Dek(1)), + ], + cmd: Cmd::Rotate, + kek: kek(), + flags: yes, + expect: Expect::Done, + after: vec![Under::RingActive, Under::RingActive], + ring_after: Some((vec![2], false)), + catalog_key_after: false, + }, + Case { + name: "rotate: refused on a ring whose DEK id has no successor", + catalog_key: false, + ring: Some(ring(&KEK, &[u64::MAX], false, None)), + connection: None, + rows: vec![("AKIAKEY000000000001", Under::Dek(u64::MAX))], + cmd: Cmd::Rotate, + kek: kek(), + flags: yes, + expect: Expect::Refused("has no id for a new DEK"), + after: vec![Under::RingActive], + ring_after: Some((vec![u64::MAX], false)), + catalog_key_after: false, + }, + Case { + name: "rotate: a catalog key beside the ring, with --accept-catalog-key", + catalog_key: true, + ring: Some(ring(&KEK, &[1], false, None)), + connection: None, + rows: vec![ + ("AKIAFORGED000000001", Under::CatalogKey), + ("AKIAKEY000000000001", Under::Dek(1)), + ], + cmd: Cmd::Rotate, + kek: kek(), + flags: RunFlags { + accept_catalog_key: true, + ..yes + }, + expect: Expect::Done, + after: vec![Under::RingActive, Under::RingActive], + ring_after: Some((vec![2], false)), + catalog_key_after: false, + }, + Case { + name: "rotate: refused on the ring of an unfinished switch", + catalog_key: true, + ring: Some(ring(&KEK, &[1], true, retiring.clone())), + connection: None, + rows: vec![], + cmd: Cmd::Rotate, + kek: kek(), + flags: yes, + expect: Expect::Refused("a switch to a KEK file did not finish"), + after: vec![], + ring_after: Some((vec![1], true)), + catalog_key_after: true, + }, + Case { + name: "rotate: refused under another KEK, naming both ids", + catalog_key: false, + ring: Some(ring(&OTHER_KEK, &[1], false, None)), + connection: None, + rows: vec![], + cmd: Cmd::Rotate, + kek: kek(), + flags: yes, + expect: Expect::Refused("is wrapped by the KEK with id"), + after: vec![], + ring_after: None, + catalog_key_after: false, + }, + Case { + name: "rewrap: the DEK under a new KEK", + catalog_key: false, + ring: Some(ring(&KEK, &[1], false, None)), + connection: None, + rows: vec![("AKIAKEY000000000001", Under::Dek(1))], + cmd: Cmd::Rewrap(OTHER_KEK), + kek: kek(), + flags: yes, + expect: Expect::Done, + after: vec![Under::RingActive], + ring_after: Some((vec![1], false)), + catalog_key_after: false, + }, + Case { + name: "rewrap: a second run has nothing to do", + catalog_key: false, + ring: Some(ring(&OTHER_KEK, &[1], false, None)), + connection: None, + rows: vec![], + cmd: Cmd::Rewrap(OTHER_KEK), + kek: kek(), + flags: yes, + expect: Expect::NothingToDo, + after: vec![], + ring_after: None, + catalog_key_after: false, + }, + Case { + name: "reset: refused without --discard-secrets", + catalog_key: false, + ring: Some(ring(&OTHER_KEK, &[1], false, None)), + connection: None, + rows: vec![("AKIAKEY000000000001", Under::Dek(1))], + cmd: Cmd::Reset { discard: false }, + kek: kek(), + flags: yes, + expect: Expect::Refused("Pass --discard-secrets"), + after: vec![Under::Dek(1)], + ring_after: None, + catalog_key_after: false, + }, + Case { + name: "reset: a lost KEK", + catalog_key: false, + ring: Some(ring(&OTHER_KEK, &[1], false, None)), + connection: Some(CONNECTION), + rows: vec![ + ("AKIAKEY000000000001", Under::Dek(1)), + ("ASIASESSION00000001", Under::Dek(1)), + ], + cmd: Cmd::Reset { discard: true }, + kek: kek(), + flags: yes, + expect: Expect::Done, + after: vec![], + ring_after: Some((vec![2], false)), + catalog_key_after: false, + }, + Case { + name: "reset: run again after a stop before its ring write", + catalog_key: false, + ring: Some(ring(&OTHER_KEK, &[1], false, None)), + connection: None, + rows: vec![], + cmd: Cmd::Reset { discard: true }, + kek: kek(), + flags: yes, + expect: Expect::Done, + after: vec![], + ring_after: Some((vec![2], false)), + catalog_key_after: false, + }, + Case { + name: "reset: the KEK is not lost", + catalog_key: false, + ring: Some(ring(&KEK, &[1], false, None)), + connection: None, + rows: vec![("AKIAKEY000000000001", Under::Dek(1))], + cmd: Cmd::Reset { discard: true }, + kek: kek(), + flags: yes, + expect: Expect::NothingToDo, + after: vec![Under::RingActive], + ring_after: Some((vec![1], false)), + catalog_key_after: false, + }, + Case { + name: "reset: refused on a catalog that uses the catalog key", + catalog_key: true, + ring: None, + connection: None, + rows: vec![("AKIAKEY000000000001", Under::CatalogKey)], + cmd: Cmd::Reset { discard: true }, + kek: kek(), + flags: yes, + expect: Expect::Refused("so no KEK is lost"), + after: vec![Under::CatalogKey], + ring_after: None, + catalog_key_after: true, + }, + ]; + + for case in cases { + let mut settings = vec![(CATALOG_ID_SETTING, CATALOG_ID.to_owned())]; + if case.catalog_key { + settings.push((CATALOG_KEY_SETTING, CATALOG_KEY_B64.to_owned())); + } + if let Some(ring) = &case.ring { + settings.push((KEY_RING_SETTING, ring.clone())); + } + let connection = case.connection.map(|connection| { + if connection == "under DEK 1" { + dek(1).encrypt_setting(CONNECTION).unwrap() + } else { + connection.to_owned() + } + }); + if let Some(connection) = &connection { + settings.push((DATA_CONNECTION_SETTING, connection.clone())); + } + let settings: Vec<(&str, &str)> = settings.iter().map(|(k, v)| (*k, v.as_str())).collect(); + let store = catalog_with(&case.rows, &settings); + let stores = KeyStores { + management: &store, + settings: &store, + }; + let new_kek = match case.cmd { + Cmd::Rewrap(bytes) => FakeKek::new(bytes), + _ => FakeKek::new(KEK), + }; + let outcome = match case.cmd { + Cmd::Switch => switch(stores, &case.kek, case.flags).await, + Cmd::Rotate => rotate(stores, &case.kek, case.flags).await, + Cmd::Rewrap(_) => rewrap(stores, &case.kek, &new_kek, case.flags.yes).await, + Cmd::Reset { discard } => { + reset( + stores, + &case.kek, + case.flags, + discard, + case.connection.map(|_| CONNECTION), + ) + .await + } + }; + match (&case.expect, &outcome) { + (Expect::NothingToDo, Ok(Outcome::NothingToDo { .. })) + | (Expect::Preview, Ok(Outcome::Preview(_))) + | (Expect::Done, Ok(Outcome::Done(_))) => {} + (Expect::Refused(part), Err(e)) if e.to_string().contains(part) => {} + (expected, got) => panic!("{}: expected {expected:?}, got {got:?}", case.name), + } + + // The state after the run. + let final_kek = match case.cmd { + Cmd::Rewrap(bytes) if matches!(case.expect, Expect::Done) => bytes, + Cmd::Rewrap(bytes) if matches!(case.expect, Expect::NothingToDo) => bytes, + _ => KEK, + }; + let ids: Vec<&str> = case.rows.iter().map(|(id, _)| *id).collect(); + if case.after.is_empty() { + assert!( + store.rows.lock().unwrap().is_empty() || ids.is_empty(), + "{}: the rows are gone", + case.name + ); + } else { + assert_eq!( + openers_after(&store, &ids, &final_kek), + case.after, + "{}", + case.name + ); + } + if let Some((dek_ids, switching)) = &case.ring_after { + let open = open_ring( + &store.get(KEY_RING_SETTING).expect("a ring"), + Some(CATALOG_ID), + &final_kek, + ) + .unwrap_or_else(|r| panic!("{}: {r}", case.name)); + assert_eq!(open.ring.dek_ids(), *dek_ids, "{}", case.name); + assert_eq!( + open.ring.switch_from_catalog_key, *switching, + "{}", + case.name + ); + if !switching { + assert_eq!(open.ring.retiring_catalog_key_id, None, "{}", case.name); + } + if let (Some(_), Ok(Outcome::Done(summary))) = (&connection, &outcome) { + let stored = store.get(DATA_CONNECTION_SETTING).unwrap(); + assert_eq!( + *open + .active() + .decrypt_setting(&stored) + .expect("the row opens"), + *CONNECTION, + "{}", + case.name + ); + assert_eq!( + summary.data_connection_rewritten, + Some(true), + "{}", + case.name + ); + } + } + assert_eq!( + store.get(CATALOG_KEY_SETTING).is_some(), + case.catalog_key_after, + "{}", + case.name + ); + } +} diff --git a/crates/storage/src/key_tests/loader.rs b/crates/storage/src/key_tests/loader.rs new file mode 100644 index 000000000..3db38a373 --- /dev/null +++ b/crates/storage/src/key_tests/loader.rs @@ -0,0 +1,175 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +// ── The startup loader (section 7) ───────────────────────────────────── + +#[tokio::test] +async fn startup_loader() { + let finished = ring_text(&KEK, &[1], false, None); + let unfinished = ring_text(&KEK, &[1], true, Some(catalog_key_id(&KEK, &catalog_key()))); + let flipped = edit_ring(&finished, |r| r["switch_from_catalog_key"] = json!(true)); + let rotating = ring_text(&KEK, &[1, 2], false, None); + let third = ring_text(&KEK, &[3], false, None); + let refused = |r: KeyRefusal| Err(format!("Backend initialization failed: {r}")); + let kek = || KeySource::Kek(Zeroizing::new(KEK).into()); + + // (case, settings rows, key source, Ok(DEK id of the loaded key, None for + // the catalog key) or Err(the BackendError text)) + #[allow(clippy::type_complexity)] + let cases: Vec<( + &str, + Vec<(&str, &str)>, + KeySource, + Result, String>, + )> = vec![ + ( + "the catalog key, no ring, no key_file", + vec![(CATALOG_KEY_SETTING, CATALOG_KEY_B64)], + KeySource::CatalogKey, + Ok(None), + ), + ( + "neither row, no key_file", + vec![], + KeySource::CatalogKey, + Err(BackendError::MissingEncryptionKey.to_string()), + ), + ( + "a damaged catalog key", + vec![(CATALOG_KEY_SETTING, "AAAA")], + KeySource::CatalogKey, + Err( + BackendError::InvalidEncryptionKey("encryption key must be 32 bytes".to_owned()) + .to_string(), + ), + ), + ( + "an unfinished switch, no key_file", + vec![ + (CATALOG_KEY_SETTING, CATALOG_KEY_B64), + (KEY_RING_SETTING, &unfinished), + (CATALOG_ID_SETTING, CATALOG_ID), + ], + KeySource::CatalogKey, + refused(KeyRefusal::UnfinishedSwitchWithoutKeyFile), + ), + ( + "a finished ring, no key_file", + vec![ + (KEY_RING_SETTING, &finished), + (CATALOG_ID_SETTING, CATALOG_ID), + ], + KeySource::CatalogKey, + refused(KeyRefusal::RingNeedsKeyFile { + kek_id: kek_id(&KEK), + }), + ), + ( + "a ring that does not parse, no key_file", + vec![(KEY_RING_SETTING, "{}")], + KeySource::CatalogKey, + refused(KeyRefusal::DamagedRing { + reason: "the ring does not parse: missing field `version` at line 1 column 2" + .to_owned(), + }), + ), + ( + "the catalog key, no ring, key_file set", + vec![(CATALOG_KEY_SETTING, CATALOG_KEY_B64)], + kek(), + refused(KeyRefusal::CatalogKeyWithoutRing), + ), + ( + "neither row, key_file set", + vec![], + kek(), + refused(KeyRefusal::NoRing), + ), + ( + "a ring under another KEK", + vec![ + (KEY_RING_SETTING, &finished), + (CATALOG_ID_SETTING, CATALOG_ID), + ], + KeySource::Kek(Zeroizing::new(OTHER_KEK).into()), + refused(KeyRefusal::KekMismatch { + ring: kek_id(&KEK), + configured: kek_id(&OTHER_KEK), + }), + ), + ( + "a ring whose DEK fails to unwrap, catalog key present too", + vec![ + (CATALOG_KEY_SETTING, CATALOG_KEY_B64), + (KEY_RING_SETTING, &flipped), + (CATALOG_ID_SETTING, CATALOG_ID), + ], + kek(), + refused(KeyRefusal::DamagedRing { + reason: "DEK 1 fails to unwrap".to_owned(), + }), + ), + ( + "a ring and no catalog_id row", + vec![(KEY_RING_SETTING, &finished)], + kek(), + refused(KeyRefusal::DamagedRing { + reason: "the catalog has no catalog_id row, which the ring's AAD holds".to_owned(), + }), + ), + ( + "an unfinished switch, key_file set", + vec![ + (CATALOG_KEY_SETTING, CATALOG_KEY_B64), + (KEY_RING_SETTING, &unfinished), + (CATALOG_ID_SETTING, CATALOG_ID), + ], + kek(), + refused(KeyRefusal::UnfinishedSwitchWithKeyFile), + ), + ( + "a catalog key beside a finished ring", + vec![ + (CATALOG_KEY_SETTING, CATALOG_KEY_B64), + (KEY_RING_SETTING, &finished), + (CATALOG_ID_SETTING, CATALOG_ID), + ], + kek(), + refused(KeyRefusal::CatalogKeyAfterSwitch), + ), + ( + "a ring with two DEKs", + vec![ + (KEY_RING_SETTING, &rotating), + (CATALOG_ID_SETTING, CATALOG_ID), + ], + kek(), + refused(KeyRefusal::UnfinishedRotation), + ), + ( + "a ring with one DEK and no catalog key", + vec![(KEY_RING_SETTING, &third), (CATALOG_ID_SETTING, CATALOG_ID)], + kek(), + Ok(Some(3)), + ), + ]; + for (case, rows, source, expected) in cases { + let catalog = FakeCatalog::with_settings(&rows); + let loaded = load_secret_keys(&catalog, source) + .await + .map(|keys| keys.expect("a key").dek_id()) + .map_err(|e| e.to_string()); + assert_eq!(loaded, expected, "{case}"); + } + + // No key: nothing is read, whatever the catalog holds. + let catalog = FakeCatalog::with_settings(&[(KEY_RING_SETTING, "{}")]); + assert!( + load_secret_keys(&catalog, KeySource::None) + .await + .expect("no key") + .is_none() + ); +} diff --git a/crates/storage/src/key_tests/mod.rs b/crates/storage/src/key_tests/mod.rs new file mode 100644 index 000000000..fef5b7f8b --- /dev/null +++ b/crates/storage/src/key_tests/mod.rs @@ -0,0 +1,367 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Tests of the AAD encoding, the key ring, the startup loader, the pass and +//! the encryption-key commands (RFC-0000 sections 4, 5, 7 and 8), over an +//! in-memory catalog. + +mod commands; +mod loader; +mod pass; +mod ring; +mod status; +mod stops; + +use std::collections::BTreeMap; +use std::sync::Mutex; + +use futures::future::BoxFuture; +use serde_json::{Value, json}; +use time::OffsetDateTime; +use zeroize::Zeroizing; + +use crate::key_ring::{ + KEY_RING_SETTING, KeyId, KeyRefusal, KeyRing, LOST_KEK_STEPS, RESTORE_STEPS, catalog_key_id, + kek_id, new_dek, open_ring, +}; +use crate::management_store::{ + AccessKeyCreated, AccountDetail, GroupDetail, GroupListEntry, ManagementStore, OpError, + OpResult, RoleDetail, RoleListEntry, SecretPage, SecretWrite, SettingsStore, StoredSecretRow, + UserDetail, UserListEntry, +}; +use crate::secret_keys::{ + AadKind, CATALOG_ID_SETTING, CATALOG_KEY_SETTING, SecretKeys, SecretRow, SecretTable, + encode_aad, +}; +use crate::server_components::{BackendError, KeySource, load_secret_keys}; + +pub(crate) const CATALOG_ID: &str = "0f3c2a1e-8b7d-4c6e-9f10-112233445566"; +pub(crate) const CATALOG_KEY_B64: &str = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="; +pub(crate) const KEK: [u8; 32] = [0x4b; 32]; +pub(crate) const OTHER_KEK: [u8; 32] = [0x6f; 32]; + +// ── The in-memory catalog ────────────────────────────────────────────── + +/// A catalog in memory: the settings rows and the rows of the two secret +/// tables, keyed by primary key. +#[derive(Default)] +pub(crate) struct FakeCatalog { + pub(crate) settings: Mutex>, + pub(crate) rows: Mutex>, + /// Writes that report success and change nothing, as a store method that + /// matches no row does. + pub(crate) lossy_writes: Mutex, + /// Deletes that report success and leave the row, as a Cassandra + /// `DELETE` whose timestamp is below the row's own write time does. + pub(crate) lossy_deletes: Mutex, + /// For each `replace_setting` in order, the text that another writer + /// puts in its row first, between a command's read and its write. + pub(crate) written_before_replace: Mutex>>, + /// The `erase_free_space` calls, and whether they fail. + pub(crate) erased: Mutex, + pub(crate) erase_fails: Mutex, +} + +impl FakeCatalog { + pub(crate) fn with_settings(settings: &[(&str, &str)]) -> Self { + let catalog = Self::default(); + for (key, value) in settings { + catalog.set(key, value); + } + catalog + } + + pub(crate) fn set(&self, key: &str, value: &str) { + self.settings + .lock() + .unwrap() + .insert(key.to_owned(), value.to_owned()); + } + + pub(crate) fn get(&self, key: &str) -> Option { + self.settings.lock().unwrap().get(key).cloned() + } + + /// Add a row whose stored secret is `stored`. + pub(crate) fn add_stored(&self, row: &SecretRow<'_>, stored: Vec) { + let key = format!("{}#{}", row.table.name(), row.access_key_id); + self.rows.lock().unwrap().insert( + (row.table, key.clone()), + StoredSecretRow { + table: row.table, + key, + access_key_id: row.access_key_id.to_owned(), + account_id: row.account_id.to_owned(), + principal_name: row.principal_name.to_owned(), + session_name: row.session_name.map(str::to_owned), + expires_at: row.expires_at, + created_at: Some(OffsetDateTime::UNIX_EPOCH), + secret_key_encrypted: stored, + write_timestamp: None, + }, + ); + } + + pub(crate) fn stored(&self, table: SecretTable, access_key_id: &str) -> Option> { + let key = format!("{}#{access_key_id}", table.name()); + self.rows + .lock() + .unwrap() + .get(&(table, key)) + .map(|r| r.secret_key_encrypted.clone()) + } +} + +fn no_data() -> BoxFuture<'static, OpResult> { + Box::pin(async { + Err(OpError::Internal( + "the fake catalog holds no IAM data".to_owned(), + )) + }) +} + +macro_rules! no_data_calls { + ($($name:ident($($arg:ty),*) -> $out:ty;)*) => { + $( + fn $name(&self, $(_: $arg),*) -> BoxFuture<'_, OpResult<$out>> { + no_data() + } + )* + }; +} + +impl ManagementStore for FakeCatalog { + no_data_calls! { + delete_account(&str) -> (); + list_all_accounts() -> Vec<(String, String)>; + default_account_id() -> Option; + list_all_accounts_full() -> Vec<(String, String, OffsetDateTime)>; + list_accounts_for(&str) -> Vec<(String, String)>; + get_account_detail(&str) -> Option; + dashboard_counts() -> (i64, i64); + delete_user(&str, &str) -> (); + list_users(&str) -> Vec; + get_user_detail(&str, &str) -> Option; + verify_iam_user_password(&str, &str, &str) -> bool; + change_user_password(&str, &str, &str) -> (); + tag_user(&str, &str, &[(String, String)]) -> (); + untag_user(&str, &str, &[String]) -> (); + list_user_tags(&str, &str) -> Vec<(String, String)>; + create_group(&str, &str) -> (); + delete_group(&str, &str) -> (); + list_groups(&str) -> Vec; + get_group_detail(&str, &str) -> Option; + add_group_member(&str, &str, &str) -> (); + remove_group_member(&str, &str, &str) -> (); + delete_role(&str, &str) -> (); + list_roles(&str) -> Vec; + get_role_detail(&str, &str) -> Option; + get_role_trust_policy(&str, &str) -> Option; + tag_role(&str, &str, &[(String, String)]) -> (); + untag_role(&str, &str, &[String]) -> (); + list_role_tags(&str, &str) -> Vec<(String, String)>; + put_policy(&str, &str, &str, &str, &Value) -> (); + delete_policy(&str, &str, &str, &str) -> (); + list_policies(&str, &str, &str) -> Vec<(String, Value, OffsetDateTime)>; + set_user_boundary(&str, &str, &Value) -> (); + get_user_boundary(&str, &str) -> Option; + delete_user_boundary(&str, &str) -> (); + set_role_boundary(&str, &str, &Value) -> (); + get_role_boundary(&str, &str) -> Option; + delete_role_boundary(&str, &str) -> (); + delete_access_key(&str, &str, &str) -> (); + list_access_keys(&str, &str) -> Vec<(String, bool, OffsetDateTime)>; + import_access_key(&str, &str, &str, &str) -> (); + fetch_caller_tags(&str, &str) -> Vec<(String, String)>; + } + + // The calls the conformance check seeds its rows with. + + fn create_account(&self, _: &str, _: &str) -> BoxFuture<'_, OpResult<()>> { + Box::pin(async { Ok(()) }) + } + + fn create_user(&self, _: &str, _: &str, _: Option<&str>) -> BoxFuture<'_, OpResult<()>> { + Box::pin(async { Ok(()) }) + } + + fn create_role(&self, _: &str, _: &str, _: &Value) -> BoxFuture<'_, OpResult<()>> { + Box::pin(async { Ok(()) }) + } + + fn create_access_key( + &self, + account_id: &str, + user_name: &str, + ) -> BoxFuture<'_, OpResult> { + let created = AccessKeyCreated { + access_key_id: format!("AKIAFAKE{:012}", self.rows.lock().unwrap().len()), + secret_access_key: "fake-secret".to_owned(), + }; + let keys = SecretKeys::catalog_key(&self.get(CATALOG_KEY_SETTING).expect("a catalog key")) + .expect("catalog key"); + let row = SecretRow::access_key(&created.access_key_id, account_id, user_name); + self.add_stored( + &row, + keys.encrypt(&row, &created.secret_access_key).unwrap(), + ); + Box::pin(async move { Ok(created) }) + } + + #[allow(clippy::too_many_arguments)] + fn store_session( + &self, + _session_token: &str, + access_key_id: &str, + secret_key_encrypted: &[u8], + account_id: &str, + role_name: &str, + session_name: &str, + _: &Option, + _: &Option, + expires_at: OffsetDateTime, + ) -> BoxFuture<'_, OpResult<()>> { + let row = SecretRow::session( + access_key_id, + account_id, + role_name, + session_name, + expires_at.unix_timestamp(), + ); + self.add_stored(&row, secret_key_encrypted.to_vec()); + Box::pin(async { Ok(()) }) + } + + fn read_secret_page( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> BoxFuture<'_, OpResult> { + let rows = self.rows.lock().unwrap(); + let mut page_rows: Vec = rows + .iter() + .filter(|((t, key), _)| *t == table && page.is_none_or(|after| key.as_str() > after)) + .map(|(_, row)| row.clone()) + .take(page_size + 1) + .collect(); + let next = (page_rows.len() > page_size).then(|| { + page_rows.truncate(page_size); + page_rows.last().map(|r| r.key.clone()).unwrap_or_default() + }); + Box::pin(async move { + Ok(SecretPage { + rows: page_rows, + next, + }) + }) + } + + fn write_secrets( + &self, + table: SecretTable, + writes: &[SecretWrite], + ) -> BoxFuture<'_, OpResult<()>> { + if !*self.lossy_writes.lock().unwrap() { + let mut rows = self.rows.lock().unwrap(); + for write in writes { + if let Some(row) = rows.get_mut(&(table, write.key.clone())) { + row.secret_key_encrypted = write.secret_key_encrypted.clone(); + } + } + } + Box::pin(async { Ok(()) }) + } + + fn delete_secrets(&self, table: SecretTable, keys: &[String]) -> BoxFuture<'_, OpResult<()>> { + if !*self.lossy_deletes.lock().unwrap() { + let mut rows = self.rows.lock().unwrap(); + for key in keys { + rows.remove(&(table, key.clone())); + } + } + Box::pin(async { Ok(()) }) + } + + fn delete_setting(&self, key: &str) -> BoxFuture<'_, OpResult<()>> { + if !*self.lossy_deletes.lock().unwrap() { + self.settings.lock().unwrap().remove(key); + } + Box::pin(async { Ok(()) }) + } + + fn erase_free_space(&self) -> BoxFuture<'_, OpResult<()>> { + *self.erased.lock().unwrap() += 1; + let fails = *self.erase_fails.lock().unwrap(); + Box::pin(async move { + if fails { + Err(OpError::Internal("database or disk is full".to_owned())) + } else { + Ok(()) + } + }) + } +} + +impl SettingsStore for FakeCatalog { + fn get_setting(&self, key: &str) -> BoxFuture<'_, OpResult>> { + let value = self.get(key); + Box::pin(async move { Ok(value) }) + } + + fn set_setting(&self, key: &str, value: &str) -> BoxFuture<'_, OpResult<()>> { + self.set(key, value); + Box::pin(async { Ok(()) }) + } + + fn replace_setting( + &self, + key: &str, + expected: &str, + value: &str, + ) -> BoxFuture<'_, OpResult> { + if let Some(Some(other)) = self.written_before_replace.lock().unwrap().pop_front() { + self.set(key, &other); + } + let replaced = self.get(key).as_deref() == Some(expected); + if replaced { + self.set(key, value); + } + Box::pin(async move { Ok(replaced) }) + } + + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { + let all = self.settings.lock().unwrap().clone().into_iter().collect(); + Box::pin(async move { Ok(all) }) + } +} + +// ── Helpers ──────────────────────────────────────────────────────────── + +pub(crate) fn dek(id: u64) -> SecretKeys { + SecretKeys::dek_for_tests([id as u8; 32], id, CATALOG_ID) +} + +pub(crate) fn catalog_key() -> SecretKeys { + SecretKeys::catalog_key(CATALOG_KEY_B64).expect("catalog key") +} + +/// The text of a ring of `ids` under `kek`. +pub(crate) fn ring_text( + kek: &[u8; 32], + ids: &[u64], + switch: bool, + retiring: Option, +) -> String { + let deks: Vec = ids.iter().map(|id| dek(*id)).collect(); + let refs: Vec<&SecretKeys> = deks.iter().collect(); + KeyRing::seal(kek, CATALOG_ID, &refs, switch, retiring) + .expect("seal") + .to_json() +} + +fn edit_ring(text: &str, edit: impl FnOnce(&mut Value)) -> String { + let mut value: Value = serde_json::from_str(text).expect("ring json"); + edit(&mut value); + value.to_string() +} diff --git a/crates/storage/src/key_tests/pass.rs b/crates/storage/src/key_tests/pass.rs new file mode 100644 index 000000000..db6909635 --- /dev/null +++ b/crates/storage/src/key_tests/pass.rs @@ -0,0 +1,349 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +// ── The pass (section 8.4) ───────────────────────────────────────────── + +/// A KEK file in memory. `gone_after` reads, it is gone. +pub(crate) struct FakeKek { + pub(crate) path: &'static str, + pub(crate) bytes: [u8; 32], + pub(crate) gone_after: Option, + pub(crate) reads: Mutex, +} + +impl FakeKek { + pub(crate) fn new(bytes: [u8; 32]) -> Self { + Self { + path: "/run/credentials/extenddb.service/extenddb-kek", + bytes, + gone_after: None, + reads: Mutex::new(0), + } + } +} + +impl crate::key_commands::KekFile for FakeKek { + fn path(&self) -> &str { + self.path + } + + fn read(&self) -> Result, String> { + let mut reads = self.reads.lock().unwrap(); + *reads += 1; + if self.gone_after.is_some_and(|after| *reads > after) { + return Err(format!("{}: no such file", self.path)); + } + Ok(Zeroizing::new(self.bytes)) + } +} + +/// Which key a row's secret is under, in the pass and command cases. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Under { + CatalogKey, + Dek(u64), + NoKey, + /// The active DEK of the catalog's ring after the run, which a switch or + /// a rotate draws at random. + RingActive, +} + +impl Under { + pub(crate) fn seal(self, row: &SecretRow<'_>, secret: &str) -> Vec { + match self { + Self::CatalogKey => catalog_key().encrypt(row, secret).expect("encrypt"), + Self::Dek(id) => dek(id).encrypt(row, secret).expect("encrypt"), + Self::NoKey => SecretKeys::dek_for_tests([0xee; 32], 9, CATALOG_ID) + .encrypt(row, secret) + .expect("encrypt"), + Self::RingActive => unreachable!("a case seeds no row under the ring after the run"), + } + } + + pub(crate) fn opens(self, row: &SecretRow<'_>, stored: &[u8]) -> bool { + match self { + Self::CatalogKey => catalog_key().decrypt(row, stored).is_ok(), + Self::Dek(id) => dek(id).decrypt(row, stored).is_ok(), + Self::NoKey | Self::RingActive => false, + } + } +} + +const SESSION_EXPIRED: i64 = 1_000_000_000; + +pub(crate) fn access_key_row(id: &str) -> SecretRow<'_> { + SecretRow::access_key(id, "111122223333", "bob") +} + +pub(crate) fn session_row(id: &str) -> SecretRow<'_> { + SecretRow::session(id, "111122223333", "Admin", "s1", SESSION_EXPIRED) +} + +/// A catalog with one row per `(access key ID, key)`, sessions for `ASIA`. +pub(crate) fn catalog_with(rows: &[(&str, Under)], settings: &[(&str, &str)]) -> FakeCatalog { + let catalog = FakeCatalog::with_settings(settings); + for (id, under) in rows { + let row = if id.starts_with("ASIA") { + session_row(id) + } else { + access_key_row(id) + }; + catalog.add_stored(&row, under.seal(&row, &format!("secret-of-{id}"))); + } + catalog +} + +/// The key each row's secret opens under now. +pub(crate) fn openers(catalog: &FakeCatalog, ids: &[&str]) -> Vec { + ids.iter() + .map(|id| { + let (table, row) = if id.starts_with("ASIA") { + (SecretTable::IamSessions, session_row(id)) + } else { + (SecretTable::AccessKeys, access_key_row(id)) + }; + let stored = catalog.stored(table, id).expect("row"); + [ + Under::CatalogKey, + Under::Dek(1), + Under::Dek(2), + Under::Dek(3), + ] + .into_iter() + .find(|under| under.opens(&row, &stored)) + .unwrap_or(Under::NoKey) + }) + .collect() +} + +#[tokio::test] +async fn pass_cases() { + use crate::key_pass::{PassError, PassKeys, PassOptions, run_pass}; + use crate::secret_keys::DATA_CONNECTION_SETTING; + + const CONNECTION: &str = "postgres://extenddb:pw@db.internal:5432/extenddb_data"; + let target = dek(2); + let old_dek = dek(1); + let catalog = catalog_key(); + let under_old_dek = old_dek.encrypt_setting(CONNECTION).expect("seal"); + + struct Case { + name: &'static str, + rows: Vec<(&'static str, Under)>, + connection: Option, + options: PassOptions, + lossy: bool, + /// Ok(rows rewritten) or Err(the access key IDs the error lists, or + /// the connection string error). + expect: Result, + /// The key each row is under after the run. + after: Vec, + } + let keep = PassOptions { + keep_unopenable: true, + plaintext_data_connection: false, + }; + let switching = PassOptions { + keep_unopenable: false, + plaintext_data_connection: true, + }; + let cases = vec![ + Case { + name: "a secret under the catalog key, and a session under the old DEK", + rows: vec![ + ("AKIACATALOGKEY00001", Under::CatalogKey), + ("ASIAOLDDEK000000001", Under::Dek(1)), + ], + connection: None, + options: PassOptions::default(), + lossy: false, + expect: Ok(2), + after: vec![Under::Dek(2), Under::Dek(2)], + }, + Case { + name: "an expired session is re-encrypted like any other", + rows: vec![("ASIAEXPIRED00000001", Under::CatalogKey)], + connection: None, + options: PassOptions::default(), + lossy: false, + expect: Ok(1), + after: vec![Under::Dek(2)], + }, + Case { + name: "a resumed run: one secret done, one not", + rows: vec![ + ("AKIADONE00000000001", Under::Dek(2)), + ("AKIANOTDONE00000001", Under::Dek(1)), + ], + connection: None, + options: PassOptions::default(), + lossy: false, + expect: Ok(1), + after: vec![Under::Dek(2), Under::Dek(2)], + }, + Case { + name: "nothing to do", + rows: vec![("AKIADONE00000000001", Under::Dek(2))], + connection: Some(target.encrypt_setting(CONNECTION).unwrap()), + options: PassOptions::default(), + lossy: false, + expect: Ok(0), + after: vec![Under::Dek(2)], + }, + Case { + name: "a secret under no key stops the run", + rows: vec![("AKIANOKEY0000000001", Under::NoKey)], + connection: None, + options: PassOptions::default(), + lossy: false, + expect: Err("AKIANOKEY0000000001".to_owned()), + after: vec![Under::NoKey], + }, + Case { + name: "a secret under no key is kept with --keep-unopenable", + rows: vec![ + ("AKIANOKEY0000000001", Under::NoKey), + ("AKIACATALOGKEY00001", Under::CatalogKey), + ], + connection: None, + options: keep, + lossy: false, + expect: Ok(1), + after: vec![Under::NoKey, Under::Dek(2)], + }, + Case { + name: "a write that changed nothing", + rows: vec![ + ("AKIADONE00000000001", Under::Dek(2)), + ("ASIALOST00000000001", Under::Dek(1)), + ], + connection: None, + options: PassOptions::default(), + lossy: true, + expect: Err("ASIALOST00000000001".to_owned()), + after: vec![Under::Dek(2), Under::Dek(1)], + }, + Case { + name: "the plaintext connection string row during a switch", + rows: vec![], + connection: Some(CONNECTION.to_owned()), + options: switching, + lossy: false, + expect: Ok(0), + after: vec![], + }, + Case { + name: "the plaintext connection string row outside a switch", + rows: vec![], + connection: Some(CONNECTION.to_owned()), + options: PassOptions::default(), + lossy: false, + expect: Err("is not encrypted under a DEK of the key ring".to_owned()), + after: vec![], + }, + Case { + name: "the connection string row under the old DEK", + rows: vec![], + connection: Some(under_old_dek.clone()), + options: PassOptions::default(), + lossy: false, + expect: Ok(0), + after: vec![], + }, + Case { + name: "a connection string row that no key opens", + rows: vec![], + connection: Some("bm90IGEgY2lwaGVydGV4dA==".to_owned()), + options: switching, + lossy: false, + expect: Err("opens under no key of this run".to_owned()), + after: vec![], + }, + ]; + for case in cases { + let store = catalog_with(&case.rows, &[]); + if let Some(connection) = &case.connection { + store.set(DATA_CONNECTION_SETTING, connection); + } + *store.lossy_writes.lock().unwrap() = case.lossy; + let keys = PassKeys { + target: &target, + old: vec![&catalog, &old_dek], + }; + let result = run_pass(&store, &store, &keys, case.options).await; + match (&case.expect, result) { + (Ok(rewritten), Ok(summary)) => { + let total: u64 = summary.tables.iter().map(|(_, c)| c.rewritten).sum(); + assert_eq!(total, *rewritten, "{}", case.name); + if case.connection.is_some() { + let stored = store.get(DATA_CONNECTION_SETTING).unwrap(); + assert_eq!( + *target + .decrypt_setting(&stored) + .expect("the row opens under the target"), + *CONNECTION, + "{}", + case.name + ); + } + assert_eq!( + summary.data_connection_rewritten, + case.connection + .as_ref() + .map(|before| target.decrypt_setting(before).is_err()), + "{}", + case.name + ); + } + (Err(listed), Err(PassError::Unopenable(l) | PassError::NotRewritten(l))) => { + let ids: Vec<&str> = l.iter().map(|s| s.access_key_id.as_str()).collect(); + assert_eq!(ids, [listed.as_str()], "{}", case.name); + } + (Err(part), Err(PassError::DataConnection(reason))) => { + assert!(reason.contains(part.as_str()), "{}: {reason}", case.name); + } + (expected, got) => panic!("{}: expected {expected:?}, got {got:?}", case.name), + } + let ids: Vec<&str> = case.rows.iter().map(|(id, _)| *id).collect(); + assert_eq!(openers(&store, &ids), case.after, "{}", case.name); + } +} + +#[tokio::test] +async fn pass_reads_every_page() { + use crate::key_pass::{PAGE_SIZE, PassKeys, PassOptions, run_pass}; + + let ids: Vec = (0..=PAGE_SIZE) + .map(|n| format!("AKIAPAGE{n:011}")) + .collect(); + let rows: Vec<(&str, Under)> = ids + .iter() + .map(|id| (id.as_str(), Under::CatalogKey)) + .collect(); + let store = catalog_with(&rows, &[]); + let (target, catalog) = (dek(1), catalog_key()); + let summary = run_pass( + &store, + &store, + &PassKeys { + target: &target, + old: vec![&catalog], + }, + PassOptions::default(), + ) + .await + .expect("pass"); + assert_eq!(summary.tables[0].1.rewritten, (PAGE_SIZE + 1) as u64); + // The summary gives the counts after the pass: every row is under the + // target and none is under the catalog key. + assert_eq!(summary.tables[0].1.target, (PAGE_SIZE + 1) as u64); + assert_eq!(summary.tables[0].1.old, vec![0]); + let id_refs: Vec<&str> = ids.iter().map(String::as_str).collect(); + assert!( + openers(&store, &id_refs) + .into_iter() + .all(|under| under == Under::Dek(1)) + ); +} diff --git a/crates/storage/src/key_tests/ring.rs b/crates/storage/src/key_tests/ring.rs new file mode 100644 index 000000000..b7720d5af --- /dev/null +++ b/crates/storage/src/key_tests/ring.rs @@ -0,0 +1,458 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +// ── AAD encoding ─────────────────────────────────────────────────────── + +#[test] +fn aad_encoding() { + // (case, AAD under test, expected text) + let session = SecretRow::session( + "ASIAEXAMPLE|0000001", + "111122223333", + "Admin", + "s1", + 1_763_294_400, + ); + let access_key = SecretRow::access_key("AKIAEXAMPLE|0000001", "111122223333", "bob"); + let cases: &[(&str, String, &str)] = &[ + ( + "the RFC's wrapped DEK example, with a null retiring id", + encode_aad( + AadKind::Dek, + &[ + "1", + "0f3c2a1e-8b7d-4c6e-9f10-112233445566", + "file", + "3f9a0c51e2d47b86", + "2", + "2", + "false", + "", + ], + ), + "extenddb-dek-v1|1:1|36:0f3c2a1e-8b7d-4c6e-9f10-112233445566|4:file|\ + 16:3f9a0c51e2d47b86|1:2|1:2|5:false|0:", + ), + ( + "a session under a DEK: a | inside the access key ID", + dek(1).aad(&session), + "extenddb-secret-v1|36:0f3c2a1e-8b7d-4c6e-9f10-112233445566|12:iam_sessions|\ + 19:ASIAEXAMPLE|0000001|12:111122223333|5:Admin|2:s1|10:1763294400", + ), + ( + "an access key under a DEK: empty session name and expiry", + dek(1).aad(&access_key), + "extenddb-secret-v1|36:0f3c2a1e-8b7d-4c6e-9f10-112233445566|11:access_keys|\ + 19:AKIAEXAMPLE|0000001|12:111122223333|3:bob|0:|0:", + ), + ( + "an access key under the catalog key: the access key ID alone", + catalog_key().aad(&access_key), + "AKIAEXAMPLE|0000001", + ), + ( + "the connection string row", + encode_aad( + AadKind::Setting, + &[CATALOG_ID, "data_database_connection_string"], + ), + "extenddb-setting-v1|36:0f3c2a1e-8b7d-4c6e-9f10-112233445566|\ + 31:data_database_connection_string", + ), + ( + "every field empty", + encode_aad(AadKind::Secret, &["", ""]), + "extenddb-secret-v1|0:|0:", + ), + ]; + for (case, aad, expected) in cases { + assert_eq!(aad, expected, "{case}"); + } + + // With a plain separator these two rows would share an AAD: a `|` + // moves from the access key ID into the account ID. + let left = SecretRow::access_key("AKIAAAAA|1", "2", "bob"); + let right = SecretRow::access_key("AKIAAAAA", "1|2", "bob"); + assert_ne!(dek(1).aad(&left), dek(1).aad(&right)); + let stored = dek(1).encrypt(&left, "secret").expect("encrypt"); + assert_eq!( + dek(1).decrypt(&right, &stored).unwrap_err(), + "decrypt: authentication failed" + ); + assert_eq!(*dek(1).decrypt(&left, &stored).expect("decrypt"), "secret"); +} + +/// The AAD binds a stored secret to each field of its row: the same +/// ciphertext under the same DEK does not open for a row that differs in any +/// one field, and opens for the row it was sealed for. +#[test] +fn a_secret_does_not_open_for_a_row_moved_in_any_field() { + let row = SecretRow { + table: SecretTable::IamSessions, + access_key_id: "ASIAEXAMPLE0000001", + account_id: "111122223333", + principal_name: "Admin", + session_name: Some("s1"), + expires_at: Some(1_763_294_400), + }; + let key = dek(1); + let stored = key.encrypt(&row, "secret").expect("encrypt"); + assert_eq!(*key.decrypt(&row, &stored).expect("decrypt"), "secret"); + // (field, the row with only that field changed) + let moved: [(&str, SecretRow<'_>); 6] = [ + ( + "table", + SecretRow { + table: SecretTable::AccessKeys, + ..row + }, + ), + ( + "access key ID", + SecretRow { + access_key_id: "ASIAEXAMPLE0000002", + ..row + }, + ), + ( + "account", + SecretRow { + account_id: "444455556666", + ..row + }, + ), + ( + "principal", + SecretRow { + principal_name: "Other", + ..row + }, + ), + ( + "session name", + SecretRow { + session_name: Some("s2"), + ..row + }, + ), + ( + "expiry", + SecretRow { + expires_at: Some(1_763_294_401), + ..row + }, + ), + ]; + for (field, other) in moved { + match key.decrypt(&other, &stored) { + Ok(_) => panic!("{field}: the secret opens for the moved row"), + Err(e) => assert_eq!(e, "decrypt: authentication failed", "{field}"), + } + } + // The catalog id: the same DEK bytes and id in another catalog. + let elsewhere = SecretKeys::dek_for_tests([1; 32], 1, "another-catalog"); + match elsewhere.decrypt(&row, &stored) { + Ok(_) => panic!("catalog id: the secret opens in another catalog"), + Err(e) => assert_eq!(e, "decrypt: authentication failed", "catalog id"), + } +} + +// ── The key ring ─────────────────────────────────────────────────────── + +#[test] +fn ring_tampering() { + let one = ring_text(&KEK, &[2], false, None); + let two = ring_text(&KEK, &[1, 2], false, None); + let other_catalog = { + let other = SecretKeys::dek_for_tests([2; 32], 2, "another-catalog"); + KeyRing::seal(&KEK, "another-catalog", &[&other], false, None) + .expect("seal") + .to_json() + }; + let retiring = Some(KeyId::parse("00112233aabbccdd").expect("id")); + let damaged = |reason: &str| { + Expect::Refused(KeyRefusal::DamagedRing { + reason: reason.to_owned(), + }) + }; + enum Expect { + /// The ring opens, and its active DEK is 2. + Opens, + /// The parser refuses it; the reason contains this text. + Unparsed(&'static str), + Refused(KeyRefusal), + } + use Expect::{Opens, Unparsed}; + + let cases: Vec<(&str, String, Expect)> = vec![ + ("an untouched ring", one.clone(), Opens), + ( + "a flipped switch_from_catalog_key", + edit_ring(&one, |r| r["switch_from_catalog_key"] = json!(true)), + damaged("DEK 2 fails to unwrap"), + ), + ( + "a changed retiring_catalog_key_id", + edit_ring(&one, |r| { + r["retiring_catalog_key_id"] = json!("00112233aabbccdd") + }), + damaged("DEK 2 fails to unwrap"), + ), + ( + "a retiring id removed from an unfinished switch", + edit_ring(&ring_text(&KEK, &[2], true, retiring.clone()), |r| { + r["retiring_catalog_key_id"] = Value::Null + }), + damaged("DEK 2 fails to unwrap"), + ), + ( + "an added DEK entry", + edit_ring(&one, |r| { + let mut entry = r["keys"][0].clone(); + entry["id"] = json!(3); + r["keys"].as_array_mut().unwrap().push(entry); + }), + damaged("DEKs 2, 3 fail to unwrap"), + ), + ( + "a deleted DEK entry", + edit_ring(&two, |r| { + r["keys"].as_array_mut().unwrap().remove(0); + }), + damaged("DEK 2 fails to unwrap"), + ), + ( + "a wrapped DEK copied from another catalog's ring", + edit_ring(&one, |r| { + let other: Value = serde_json::from_str(&other_catalog).unwrap(); + r["keys"][0]["wrapped"] = other["keys"][0]["wrapped"].clone(); + }), + damaged("DEK 2 fails to unwrap"), + ), + ( + "a changed DEK id", + edit_ring(&one, |r| r["keys"][0]["id"] = json!(5)), + damaged("DEK 5 fails to unwrap"), + ), + ( + "an unknown field", + edit_ring(&one, |r| r["comment"] = json!("x")), + Unparsed("unknown field `comment`"), + ), + ( + "an unknown field in a DEK entry", + edit_ring(&one, |r| r["keys"][0]["created"] = json!(1)), + Unparsed("unknown field `created`"), + ), + ( + "a version that is a string", + edit_ring(&one, |r| r["version"] = json!("1")), + Unparsed("invalid type: string \"1\", expected u64"), + ), + ( + "a DEK id that is a string", + edit_ring(&one, |r| r["keys"][0]["id"] = json!("2")), + Unparsed("invalid type: string \"2\", expected u64"), + ), + ( + "a DEK id that is a float", + edit_ring(&one, |r| r["keys"][0]["id"] = json!(2.0)), + Unparsed("invalid type: floating point `2.0`, expected u64"), + ), + ( + "a flag that is a string", + edit_ring(&one, |r| r["switch_from_catalog_key"] = json!("false")), + Unparsed("expected a boolean"), + ), + ( + "an empty-string retiring id", + edit_ring(&one, |r| r["retiring_catalog_key_id"] = json!("")), + Unparsed("a key id is 16 lowercase hex characters, not \"\""), + ), + ( + "a missing retiring id", + edit_ring(&one, |r| { + r.as_object_mut().unwrap().remove("retiring_catalog_key_id"); + }), + Unparsed("missing field `retiring_catalog_key_id`"), + ), + ( + "an unknown KEK source", + edit_ring(&one, |r| r["kek"]["source"] = json!("pkcs11")), + Unparsed("unknown variant `pkcs11`"), + ), + ( + "a KEK id in upper case", + edit_ring(&one, |r| { + let id = r["kek"]["id"].as_str().unwrap().to_uppercase(); + r["kek"]["id"] = json!(id); + }), + Unparsed("a key id is 16 lowercase hex characters"), + ), + ( + "another version", + edit_ring(&one, |r| r["version"] = json!(2)), + Unparsed("version 2 is not the ring version 1 of this release"), + ), + ( + "two entries with one id", + edit_ring(&one, |r| { + let entry = r["keys"][0].clone(); + r["keys"].as_array_mut().unwrap().push(entry); + }), + Unparsed("DEK ids start at 1 and each appears once"), + ), + ( + "no DEK", + edit_ring(&one, |r| r["keys"] = json!([])), + Unparsed("a ring holds one or two DEKs, not 0"), + ), + ( + "a ring under another KEK", + ring_text(&OTHER_KEK, &[2], false, None), + Expect::Refused(KeyRefusal::KekMismatch { + ring: kek_id(&OTHER_KEK), + configured: kek_id(&KEK), + }), + ), + ("a two-DEK ring", two.clone(), Opens), + ( + "a two-DEK ring with its entries in the other order", + edit_ring(&two, |r| r["keys"].as_array_mut().unwrap().reverse()), + Opens, + ), + ]; + for (case, text, expected) in cases { + let opened = open_ring(&text, Some(CATALOG_ID), &KEK); + match (expected, opened) { + (Opens, Ok(open)) => assert_eq!(open.active().dek_id(), Some(2), "{case}"), + (Unparsed(part), Err(KeyRefusal::DamagedRing { reason })) => assert!( + reason.starts_with("the ring does not parse: ") && reason.contains(part), + "{case}: {reason}" + ), + (Expect::Refused(expected), Err(refusal)) => assert_eq!(refusal, expected, "{case}"), + (_, opened) => panic!("{case}: {:?}", opened.map(|o| o.ring)), + } + } +} + +/// Each section of the backup manual that a refusal names is a heading of +/// that manual. A ring under another KEK sends a ring row written back from +/// a copy to the restore steps, and a lost KEK to the steps that run `reset`. +#[test] +fn the_restore_sections_the_refusals_name_are_headings_of_the_manual() { + let manual = std::fs::read_to_string( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../docs/manuals/14-backup-and-restore.md"), + ) + .expect("read the backup manual"); + for pointer in [RESTORE_STEPS, LOST_KEK_STEPS] { + let heading = pointer.split('"').nth(1).expect("a quoted heading"); + assert!( + manual.lines().any(|line| line == format!("### {heading}")), + "no heading {heading:?} in the backup manual" + ); + } + let mismatch = KeyRefusal::KekMismatch { + ring: kek_id(&OTHER_KEK), + configured: kek_id(&KEK), + } + .to_string(); + assert!(mismatch.contains(RESTORE_STEPS), "{mismatch}"); + assert!(mismatch.ends_with(LOST_KEK_STEPS), "{mismatch}"); +} + +#[test] +fn ring_round_trip_and_ids() { + let text = ring_text( + &KEK, + &[1, 2], + true, + Some(catalog_key_id(&KEK, &catalog_key())), + ); + let ring = KeyRing::parse(&text).expect("parse"); + assert_eq!(ring.to_json(), text); + assert_eq!(ring.dek_ids(), [1, 2]); + assert_eq!(ring.active_dek_id(), 2); + assert_eq!(ring.next_dek_id().expect("a next id"), 3); + assert!(text.starts_with(&format!( + "{{\"version\":1,\"kek\":{{\"source\":\"file\",\"id\":\"{}\"}},\"keys\":[{{\"id\":1,", + kek_id(&KEK) + ))); + assert_ne!(kek_id(&KEK), kek_id(&OTHER_KEK)); + assert_ne!( + catalog_key_id(&KEK, &catalog_key()), + catalog_key_id(&OTHER_KEK, &catalog_key()) + ); + // The DEK bytes survive the wrap: a secret under the DEK opens under + // the unwrapped one. + let row = SecretRow::access_key("AKIAEXAMPLE0000001", "111122223333", "bob"); + let stored = dek(2).encrypt(&row, "secret").expect("encrypt"); + let open = open_ring(&text, Some(CATALOG_ID), &KEK).expect("open"); + assert_eq!( + *open.active().decrypt(&row, &stored).expect("decrypt"), + "secret" + ); + assert_eq!(open.older().and_then(SecretKeys::dek_id), Some(1)); + // A new DEK differs from every other. + let (a, b) = ( + new_dek(3, CATALOG_ID).unwrap(), + new_dek(3, CATALOG_ID).unwrap(), + ); + assert_eq!( + a.decrypt(&row, &b.encrypt(&row, "s").unwrap()).unwrap_err(), + "decrypt: authentication failed" + ); +} + +#[test] +fn kek_file_format() { + let good = "S0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0s="; + // (contents, expected error, or None when the file parses to KEK) + let cases: &[(String, Option<&str>)] = &[ + (good.to_owned(), None), + (format!("{good}\n"), None), + ( + format!("{good}\n\n"), + Some( + "a KEK file holds 44 characters of base64 and at most one trailing newline; this one holds 46 bytes", + ), + ), + ( + format!(" {good}"), + Some( + "a KEK file holds 44 characters of base64 and at most one trailing newline; this one holds 45 bytes", + ), + ), + ( + format!("{good}\r\n"), + Some( + "a KEK file holds 44 characters of base64 and at most one trailing newline; this one holds 46 bytes", + ), + ), + ( + "S0tL-0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0s=".to_owned(), + Some("decode encryption key: invalid symbol at offset 4"), + ), + ( + "S0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tL".to_owned(), + Some( + "a KEK file holds 44 characters of base64 and at most one trailing newline; this one holds 48 bytes", + ), + ), + ( + // 31 bytes. + "S0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSw==".to_owned(), + Some("encryption key must be 32 bytes"), + ), + ]; + for (contents, expected) in cases { + let parsed = crate::key_ring::parse_kek_file(contents.as_bytes()); + match expected { + None => assert_eq!(**parsed.expect("parse"), KEK, "{contents:?}"), + Some(expected) => assert_eq!(&parsed.unwrap_err(), expected, "{contents:?}"), + } + } +} diff --git a/crates/storage/src/key_tests/status.rs b/crates/storage/src/key_tests/status.rs new file mode 100644 index 000000000..500306928 --- /dev/null +++ b/crates/storage/src/key_tests/status.rs @@ -0,0 +1,163 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::pass::{FakeKek, Under, catalog_with}; +use super::*; + +/// The backend check runs on the in-memory catalog, so a change to it is +/// seen here before a backend runs it. +#[cfg(feature = "test-util")] +#[tokio::test] +async fn the_backend_check_passes_on_the_fake_catalog() { + use crate::key_conformance::{Expectations, run}; + use crate::secret_keys::DATA_CONNECTION_SETTING; + + let store = FakeCatalog::with_settings(&[ + (CATALOG_KEY_SETTING, CATALOG_KEY_B64), + (CATALOG_ID_SETTING, CATALOG_ID), + ( + DATA_CONNECTION_SETTING, + "postgres://extenddb:pw@localhost:5432/extenddb_data", + ), + ]); + run( + &store, + &store, + Expectations { + write_timestamps: false, + data_connection: true, + }, + ) + .await; +} + +#[tokio::test] +async fn status_cases() { + use crate::key_commands::{KeyStores, status}; + + let finished = ring_text(&KEK, &[1], false, None); + // (case, catalog key row, ring row, KEK given, failed DEK ids, the + // access key IDs listed as under a key other than the target, or None + // when no key opens the secrets) + #[allow(clippy::type_complexity)] + let cases: Vec<( + &str, + bool, + Option<&str>, + Option<[u8; 32]>, + Vec, + Option>, + )> = vec![ + ( + "the catalog key alone", + true, + None, + None, + vec![], + Some(vec!["AKIAUNDERDEK0000001"]), + ), + ( + "a ring and its KEK, and a catalog key beside it", + true, + Some(&finished), + Some(KEK), + vec![], + Some(vec!["AKIACATALOGKEY00001"]), + ), + ( + "a ring under another KEK", + false, + Some(&finished), + Some(OTHER_KEK), + vec![1], + None, + ), + ( + "a ring and no KEK", + false, + Some(&finished), + None, + vec![], + None, + ), + ]; + for (case, with_catalog_key, ring, kek, failed, listed) in cases { + let mut settings = vec![(CATALOG_ID_SETTING, CATALOG_ID)]; + if with_catalog_key { + settings.push((CATALOG_KEY_SETTING, CATALOG_KEY_B64)); + } + if let Some(ring) = ring { + settings.push((KEY_RING_SETTING, ring)); + } + let store = catalog_with( + &[ + ("AKIACATALOGKEY00001", Under::CatalogKey), + ("AKIAUNDERDEK0000001", Under::Dek(1)), + ], + &settings, + ); + let kek_file = kek.map(FakeKek::new); + let report = status( + KeyStores { + management: &store, + settings: &store, + }, + kek_file + .as_ref() + .map(|k| k as &dyn crate::key_commands::KekFile), + ) + .await + .unwrap_or_else(|e| panic!("{case}: {e}")); + assert_eq!(report.catalog_key_present, with_catalog_key, "{case}"); + assert_eq!( + report.ring.as_ref().map(|r| r.failed_dek_ids.clone()), + ring.map(|_| failed.clone()), + "{case}" + ); + assert_eq!( + report.survey.as_ref().map(|s| s + .not_target + .iter() + .map(|l| l.access_key_id.as_str()) + .collect::>()), + listed, + "{case}" + ); + } +} + +#[test] +fn data_connection_key_cases() { + use crate::key_commands::data_connection_key; + + let finished = ring_text(&KEK, &[1], false, None); + let switching = ring_text(&KEK, &[1], true, Some(catalog_key_id(&KEK, &catalog_key()))); + let rotating = ring_text(&KEK, &[1, 2], false, None); + // (case, ring row, KEK, Ok(DEK id) or Err(part of the refusal)) + #[allow(clippy::type_complexity)] + let cases: &[(&str, Option<&str>, [u8; 32], Result)] = &[ + ("a finished ring", Some(&finished), KEK, Ok(1)), + ("no ring", None, KEK, Err("has no key ring")), + ( + "an unfinished switch", + Some(&switching), + KEK, + Err("did not finish"), + ), + ("two DEKs", Some(&rotating), KEK, Err("holds two DEKs")), + ( + "another KEK", + Some(&finished), + OTHER_KEK, + Err("is wrapped by the KEK with id"), + ), + ]; + for (case, ring, kek, expected) in cases { + let got = data_connection_key(*ring, kek, CATALOG_ID).map(|k| k.dek_id().unwrap()); + match (expected, got) { + (Ok(id), Ok(got)) => assert_eq!(*id, got, "{case}"), + (Err(part), Err(message)) => assert!(message.contains(part), "{case}: {message}"), + (expected, got) => panic!("{case}: expected {expected:?}, got {got:?}"), + } + } +} diff --git a/crates/storage/src/key_tests/stops.rs b/crates/storage/src/key_tests/stops.rs new file mode 100644 index 000000000..9b91c55a8 --- /dev/null +++ b/crates/storage/src/key_tests/stops.rs @@ -0,0 +1,387 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::commands::openers_after; +use super::pass::{FakeKek, Under, catalog_with}; +use super::*; + +// ── Runs that stop: a ring changed after the read, a delete that does not land ── + +/// `rewrap` runs outside the migration lock, so a `rotate` can write the ring +/// between the read and the write of either command. Both ring writes are +/// conditional on the text read, and a ring that changed stops the run +/// before it writes anything. +#[tokio::test] +async fn a_ring_that_changed_after_the_read_stops_the_run() { + use crate::key_commands::{KeyStores, RunFlags, rewrap, rotate}; + + let read = ring_text(&KEK, &[1], false, None); + // The ring that a concurrent rotate writes first. + let other = ring_text(&KEK, &[1, 2], false, None); + for command in ["rewrap", "rotate"] { + let store = catalog_with( + &[("AKIAKEY000000000001", Under::Dek(1))], + &[(CATALOG_ID_SETTING, CATALOG_ID), (KEY_RING_SETTING, &read)], + ); + store + .written_before_replace + .lock() + .unwrap() + .push_back(Some(other.clone())); + let stores = KeyStores { + management: &store, + settings: &store, + }; + let kek = FakeKek::new(KEK); + let outcome = match command { + "rewrap" => rewrap(stores, &kek, &FakeKek::new(OTHER_KEK), true).await, + _ => { + let yes = RunFlags { + yes: true, + ..RunFlags::default() + }; + rotate(stores, &kek, yes).await + } + }; + let message = outcome + .err() + .unwrap_or_else(|| panic!("{command}: the run should stop")) + .to_string(); + assert!( + message.contains(&format!( + "the key ring changed while `extenddb encryption-key {command}` ran, so nothing \ + was written" + )), + "{command}: {message}" + ); + assert_eq!( + store.get(KEY_RING_SETTING), + Some(other.clone()), + "{command}" + ); + assert_eq!( + openers_after(&store, &["AKIAKEY000000000001"], &KEK), + vec![Under::Dek(1)], + "{command}: the secret is not re-encrypted" + ); + } +} + +/// The last ring write of `rotate` is conditional on its two-DEK ring too. +/// A ring that changed after the first write stops the run with the DEK +/// that the pass put the stored secrets under. +#[tokio::test] +async fn a_ring_that_changed_before_the_last_rotate_write_stops_the_run() { + use crate::key_commands::{KeyStores, RunFlags, rotate}; + + let read = ring_text(&KEK, &[1], false, None); + let other = ring_text(&KEK, &[1], false, None); + let store = catalog_with( + &[("AKIAKEY000000000001", Under::Dek(1))], + &[(CATALOG_ID_SETTING, CATALOG_ID), (KEY_RING_SETTING, &read)], + ); + store + .written_before_replace + .lock() + .unwrap() + .extend([None, Some(other.clone())]); + let stores = KeyStores { + management: &store, + settings: &store, + }; + let yes = RunFlags { + yes: true, + ..RunFlags::default() + }; + let message = rotate(stores, &FakeKek::new(KEK), yes) + .await + .expect_err("the run should stop") + .to_string(); + assert!( + message.contains( + "the key ring changed after `extenddb encryption-key rotate` wrote its two DEKs, so \ + its last ring write did not happen. The pass put the stored secrets under DEK 2" + ), + "{message}" + ); + assert_eq!(store.get(KEY_RING_SETTING), Some(other)); +} + +/// `reset` writes its ring only while the row holds the ring it read. A ring +/// that changed after the read stops the run before its ring write, and +/// names what the run left. +#[tokio::test] +async fn a_ring_that_changed_before_the_reset_write_stops_the_run() { + use crate::key_commands::{KeyStores, RunFlags, reset}; + + let lost = ring_text(&[0x5b; 32], &[1], false, None); + let other = ring_text(&[0x5c; 32], &[1], false, None); + let store = catalog_with( + &[("AKIAKEY000000000001", Under::Dek(1))], + &[(CATALOG_ID_SETTING, CATALOG_ID), (KEY_RING_SETTING, &lost)], + ); + store + .written_before_replace + .lock() + .unwrap() + .push_back(Some(other.clone())); + let stores = KeyStores { + management: &store, + settings: &store, + }; + let yes = RunFlags { + yes: true, + ..RunFlags::default() + }; + let message = reset(stores, &FakeKek::new(KEK), yes, true, None) + .await + .expect_err("the run should stop") + .to_string(); + assert!( + message.contains( + "the key ring changed while `extenddb encryption-key reset` ran, so its ring write \ + did not happen" + ), + "{message}" + ); + assert_eq!(store.get(KEY_RING_SETTING), Some(other)); +} + +/// A store's `Ok` from a delete does not prove the row is gone: on Cassandra +/// a `DELETE` whose timestamp is below the row's own write time leaves the +/// row. Each command that deletes the `encryption_key` row reads it back, +/// and `reset` reads a page of each secret table back, so a lost delete +/// stops the run instead of reporting a key that is still readable as gone. +#[tokio::test] +async fn a_delete_that_does_not_land_stops_the_run() { + use crate::key_commands::{KeyStores, RunFlags, reset, rotate, switch}; + + enum Cmd { + Switch, + Rotate, + Reset, + } + struct Case { + name: &'static str, + cmd: Cmd, + ring: Option, + rows: Vec<(&'static str, Under)>, + flags: RunFlags, + message: &'static str, + } + let yes = RunFlags { + yes: true, + ..RunFlags::default() + }; + let cases = vec![ + Case { + name: "switch: the encryption_key row stays", + cmd: Cmd::Switch, + ring: None, + rows: vec![("AKIAKEY000000000001", Under::CatalogKey)], + flags: yes, + message: "encryption_key row is still there after the delete", + }, + Case { + name: "rotate: the encryption_key row stays", + cmd: Cmd::Rotate, + ring: Some(ring_text(&KEK, &[1], false, None)), + rows: vec![("AKIAKEY000000000001", Under::CatalogKey)], + flags: RunFlags { + accept_catalog_key: true, + ..yes + }, + message: "encryption_key row is still there after the delete", + }, + Case { + name: "reset: a row of access_keys stays", + cmd: Cmd::Reset, + ring: Some(ring_text(&[0x5b; 32], &[1], false, None)), + rows: vec![("AKIAKEY000000000001", Under::Dek(1))], + flags: yes, + message: "access_keys table still holds a row after the delete", + }, + Case { + name: "reset with no secret row: the encryption_key row stays", + cmd: Cmd::Reset, + ring: Some(ring_text(&[0x5b; 32], &[1], false, None)), + rows: vec![], + flags: yes, + message: "encryption_key row is still there after the delete", + }, + ]; + + for case in cases { + let mut settings = vec![ + (CATALOG_ID_SETTING, CATALOG_ID.to_owned()), + (CATALOG_KEY_SETTING, CATALOG_KEY_B64.to_owned()), + ]; + if let Some(ring) = &case.ring { + settings.push((KEY_RING_SETTING, ring.clone())); + } + let settings: Vec<(&str, &str)> = settings.iter().map(|(k, v)| (*k, v.as_str())).collect(); + let store = catalog_with(&case.rows, &settings); + *store.lossy_deletes.lock().unwrap() = true; + let stores = KeyStores { + management: &store, + settings: &store, + }; + let kek = FakeKek::new(KEK); + let outcome = match case.cmd { + Cmd::Switch => switch(stores, &kek, case.flags).await, + Cmd::Rotate => rotate(stores, &kek, case.flags).await, + Cmd::Reset => reset(stores, &kek, case.flags, true, None).await, + }; + let message = outcome + .err() + .unwrap_or_else(|| panic!("{}: the run should stop", case.name)) + .to_string(); + assert!(message.contains(case.message), "{}: {message}", case.name); + assert!( + store.get(CATALOG_KEY_SETTING).is_some(), + "{}: the catalog key is kept", + case.name + ); + assert_eq!( + store.rows.lock().unwrap().len(), + case.rows.len(), + "{}: every row is kept", + case.name + ); + // The ring the run would have written last is not there: a switch + // leaves its unfinished ring, and a rotate its two-DEK ring, both of + // which the command resumes. + let finished = store + .get(KEY_RING_SETTING) + .map(|text| open_ring(&text, Some(CATALOG_ID), &KEK).map(|open| open.ring.dek_ids())); + match (&case.cmd, finished) { + (Cmd::Switch, Some(Ok(ids))) => { + assert_eq!(ids, vec![1], "{}: the unfinished ring stays", case.name); + } + (Cmd::Rotate, Some(Ok(ids))) => { + assert_eq!(ids, vec![1, 2], "{}: the two-DEK ring stays", case.name); + } + // `reset` runs with a KEK the old ring does not name, so the old + // ring stays and does not open with this run's KEK. + (Cmd::Reset, Some(Err(_))) => {} + (_, other) => panic!("{}: the ring after the run is {other:?}", case.name), + } + } +} + +/// The rebuild that erases replaced ciphertexts (SQLite's `VACUUM`) runs +/// after the last write. A failed rebuild says that every row is written and +/// that a run of the same command again rebuilds the file, and that run, +/// with nothing else to do, rebuilds it; a preview does not. +#[tokio::test] +async fn a_failed_rebuild_is_named_and_a_run_again_rebuilds_the_file() { + use crate::key_commands::{KeyStores, RunFlags, reset, rotate, switch}; + + let yes = RunFlags { + yes: true, + ..RunFlags::default() + }; + let finished = ring_text(&KEK, &[1], false, None); + struct Case<'a> { + name: &'a str, + command: &'a str, + catalog_key: bool, + ring: Option<&'a str>, + flags: RunFlags, + fails: bool, + /// The message of a run that stops, or `None` for a run that ends. + message: Option<&'a str>, + rebuilds: usize, + } + let nothing_to_do = |name, command, flags, rebuilds| Case { + name, + command, + catalog_key: false, + ring: Some(&finished), + flags, + fails: false, + message: None, + rebuilds, + }; + let cases = [ + Case { + name: "a fresh switch", + command: "switch", + catalog_key: true, + ring: None, + flags: yes, + fails: true, + message: Some("`extenddb encryption-key switch` wrote every row, and then the rebuild"), + rebuilds: 1, + }, + Case { + name: "a rotate", + command: "rotate", + catalog_key: false, + ring: Some(&finished), + flags: yes, + fails: true, + message: Some("`extenddb encryption-key rotate` wrote every row, and then the rebuild"), + rebuilds: 1, + }, + nothing_to_do("a switch with nothing to do", "switch", yes, 1), + nothing_to_do( + "a switch preview with nothing to do", + "switch", + RunFlags::default(), + 0, + ), + nothing_to_do("a reset with nothing to do", "reset", yes, 1), + ]; + for Case { + name, + command, + catalog_key, + ring, + flags, + fails, + message, + rebuilds, + } in cases + { + let mut settings = vec![(CATALOG_ID_SETTING, CATALOG_ID)]; + if catalog_key { + settings.push((CATALOG_KEY_SETTING, CATALOG_KEY_B64)); + } + if let Some(ring) = ring { + settings.push((KEY_RING_SETTING, ring)); + } + let under = if catalog_key { + Under::CatalogKey + } else { + Under::Dek(1) + }; + let store = catalog_with(&[("AKIAKEY000000000001", under)], &settings); + *store.erase_fails.lock().unwrap() = fails; + let stores = KeyStores { + management: &store, + settings: &store, + }; + let kek = FakeKek::new(KEK); + let outcome = match command { + "switch" => switch(stores, &kek, flags).await, + "rotate" => rotate(stores, &kek, flags).await, + _ => reset(stores, &kek, flags, true, None).await, + }; + match message { + Some(message) => { + let error = outcome + .err() + .unwrap_or_else(|| panic!("{name}: the run should stop")) + .to_string(); + assert!(error.contains(message), "{name}: {error}"); + assert!( + error.contains("database or disk is full"), + "{name}: {error}" + ); + } + None => assert!(outcome.is_ok(), "{name}: {:?}", outcome.err()), + } + assert_eq!(*store.erased.lock().unwrap(), rebuilds, "{name}"); + } +} diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 1d72dbbf7..8773caea0 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -20,6 +20,14 @@ pub mod hooks; #[doc(hidden)] #[cfg(feature = "test-util")] pub mod iam_leftovers_conformance; +pub mod key_commands; +#[doc(hidden)] +#[cfg(feature = "test-util")] +pub mod key_conformance; +pub mod key_pass; +pub mod key_ring; +#[cfg(test)] +mod key_tests; pub mod management_store; pub mod management_store_factory; #[doc(hidden)] @@ -31,6 +39,7 @@ pub mod password; pub mod policy_migration; pub mod restore_engine; pub mod secret_cipher; +pub mod secret_keys; pub mod server_components; pub mod settings_store; pub mod snapshot; @@ -58,7 +67,7 @@ pub use snapshot::{SnapshotEngine, SnapshotInfo, TableSnapshot}; pub use transact::{IdempotencyKey, TransactGetOp, TransactWriteOp}; pub use server_components::{ - BackendError, ServerComponents, ServerComponentsFactory, create_server_components, + BackendError, KeySource, ServerComponents, ServerComponentsFactory, create_server_components, }; pub use hooks::{CancellationToken, ServerRuntimeHooks, WorkerContext, sleep_or_shutdown}; @@ -779,12 +788,15 @@ pub trait CatalogStore: + Send + Sync { - /// Get the cached encryption key (if available). + /// The key holder that this store and its credential store share, or + /// `None` for a store built with no key. AssumeRole encrypts the session + /// secret with it before [`management_store::ManagementStore::store_session`]. /// - /// Returns None if encryption key is not cached. This is used by - /// `cmd_serve` to construct the auth provider without re-querying - /// the settings table. - fn cached_encryption_key(&self) -> Option; + /// The default is `None`; every backend that serves returns its key + /// holder. + fn secret_keys(&self) -> Option<&secret_keys::SecretKeys> { + None + } } #[cfg(test)] diff --git a/crates/storage/src/management_store/mod.rs b/crates/storage/src/management_store/mod.rs index be1efa488..a043f015c 100755 --- a/crates/storage/src/management_store/mod.rs +++ b/crates/storage/src/management_store/mod.rs @@ -26,11 +26,13 @@ mod types; pub use types::{ AccessKeyCreated, AccountDetail, AdminEntry, GroupDetail, MetricsFilter, MetricsRow, OpError, - OpResult, RoleDetail, SessionPolicyEntry, UserDetail, + OpResult, RoleDetail, SecretPage, SecretWrite, SessionPolicyEntry, StoredSecretRow, UserDetail, }; use futures::future::BoxFuture; +use crate::secret_keys::SecretTable; + // Type aliases for complex return types in management traits. /// User info: `(account_id, user_name, user_arn, has_password, created_at)`. pub type UserListEntry = (String, String, String, bool, time::OffsetDateTime); @@ -58,13 +60,49 @@ pub trait SettingsStore: Send + Sync { /// Set a setting value (upsert). fn set_setting(&self, key: &str, value: &str) -> BoxFuture<'_, OpResult<()>>; + /// Set the row `key` to `value` only while it holds `expected`: `true` + /// when it held `expected` and now holds `value`, `false` when it held + /// anything else or no row. The encryption-key commands write the key + /// ring with it, because `rewrap` runs outside the migration lock. + /// + /// The default refuses: only the backends' catalog stores hold a ring. + fn replace_setting( + &self, + key: &str, + expected: &str, + value: &str, + ) -> BoxFuture<'_, OpResult> { + let _ = (key, expected, value); + Box::pin(async { + Err(OpError::Internal( + "replace_setting is not supported by this store".to_owned(), + )) + }) + } + /// List all settings as `(key, value)` pairs, ordered by key. fn list_settings(&self) -> BoxFuture<'_, OpResult>>; - /// P119: Get the cached encryption key if available. Returns `None` by - /// default; backends that cache the key at startup override this. - fn cached_encryption_key(&self) -> Option { - None + /// `encryption-key set-data-connection` (RFC-0000 section 8.7): in one + /// transaction, read the key ring `FOR SHARE`, open its DEK with `kek` + /// ([`crate::key_commands::data_connection_key`]), parse + /// `connection_string` as a PostgreSQL connection string, encrypt it with + /// section 12's AAD and write the `data_database_connection_string` row. + /// Refuses a catalog without a ring, a ring with `switch_from_catalog_key` + /// true, and a ring with two DEKs. + /// + /// The default refuses: only PostgreSQL stores this row. + fn set_data_connection( + &self, + kek: &[u8; 32], + connection_string: &str, + ) -> BoxFuture<'_, OpResult<()>> { + let _ = (kek, connection_string); + Box::pin(async { + Err(OpError::Validation( + "set-data-connection is for PostgreSQL catalogs".to_owned(), + )) + }) } } @@ -579,4 +617,48 @@ pub trait ManagementStore: Send + Sync { account_id: &str, resource: &str, ) -> BoxFuture<'_, OpResult>>; + + // ── Encryption-key commands (RFC-0000 section 8.4) ───────────── + + /// Read one page of the rows of `table` (`access_keys` or + /// `iam_sessions`), expired sessions included, in the backend's primary + /// key order. `page` is `None` for the first page, else the + /// [`SecretPage::next`] of the previous page. `page_size` is the most + /// rows a page holds. Cassandra reads at `ALL` and selects + /// `WRITETIME(secret_key_encrypted)`. + fn read_secret_page( + &self, + table: SecretTable, + page: Option<&str>, + page_size: usize, + ) -> BoxFuture<'_, OpResult>; + + /// Write each ciphertext of `rows` into the row of `table` with that + /// primary key, as one batch: one transaction of single-row updates on + /// SQLite, one `UPDATE ... FROM (VALUES ...)` on PostgreSQL, one + /// `update_one` per row with no upsert on MongoDB, and one `UPDATE` per + /// row at `ALL` with `USING TIMESTAMP` above the row's write time on + /// Cassandra. A row that is gone stays gone, and is not an error. + fn write_secrets( + &self, + table: SecretTable, + rows: &[SecretWrite], + ) -> BoxFuture<'_, OpResult<()>>; + + /// Delete the rows of `table` with the primary keys `keys`, as one batch + /// (`encryption-key reset`, section 8.6). A row that is gone is not an + /// error. + fn delete_secrets(&self, table: SecretTable, keys: &[String]) -> BoxFuture<'_, OpResult<()>>; + + /// Delete the settings row `key`. A row that is absent is not an error. + /// SQLite runs it under `PRAGMA secure_delete = ON`; Cassandra at `ALL`. + fn delete_setting(&self, key: &str) -> BoxFuture<'_, OpResult<()>>; + + /// Rewrite the catalog's files so that their free space holds no old + /// copy of a row that a command replaced or deleted. `switch`, `rotate` + /// and `reset` call it after their last write. SQLite runs `VACUUM` + /// under `PRAGMA secure_delete = ON`; the default does nothing. + fn erase_free_space(&self) -> BoxFuture<'_, OpResult<()>> { + Box::pin(async { Ok(()) }) + } } diff --git a/crates/storage/src/management_store/types.rs b/crates/storage/src/management_store/types.rs index 4d5b2fbf4..8fd686fe7 100755 --- a/crates/storage/src/management_store/types.rs +++ b/crates/storage/src/management_store/types.rs @@ -56,6 +56,94 @@ impl OpError { /// Result alias for management operations. pub type OpResult = Result; +/// One `access_keys` or `iam_sessions` row as the encryption-key commands +/// read it ([`super::ManagementStore::read_secret_page`]): the fields of its +/// AAD, its owner and creation time for the listings, and its ciphertext. +#[derive(Clone, PartialEq, Eq)] +pub struct StoredSecretRow { + /// The table that holds the row. + pub table: crate::secret_keys::SecretTable, + /// The row's primary key in the backend's own form, which + /// [`super::ManagementStore::write_secrets`] and + /// [`super::ManagementStore::delete_secrets`] take back. Opaque to the + /// commands, and never printed: for a session it can hold the token. + pub key: String, + /// The access key ID. + pub access_key_id: String, + /// The account of the user or role. + pub account_id: String, + /// The user name of an access key, the role name of a session. + pub principal_name: String, + /// The session name, for a session. + pub session_name: Option, + /// The session's `expires_at` in whole Unix seconds, for a session. + pub expires_at: Option, + /// When the row was created, when the backend stores it. + pub created_at: Option, + /// `nonce(12) || ciphertext || tag(16)`. + pub secret_key_encrypted: Vec, + /// Cassandra only: `WRITETIME(secret_key_encrypted)` in microseconds. + pub write_timestamp: Option, +} + +impl StoredSecretRow { + /// The fields of this row's AAD. + #[must_use] + pub fn aad_row(&self) -> crate::secret_keys::SecretRow<'_> { + crate::secret_keys::SecretRow { + table: self.table, + access_key_id: &self.access_key_id, + account_id: &self.account_id, + principal_name: &self.principal_name, + session_name: self.session_name.as_deref(), + expires_at: self.expires_at, + } + } +} + +impl std::fmt::Debug for StoredSecretRow { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("StoredSecretRow") + .field("table", &self.table) + .field("access_key_id", &self.access_key_id) + .field("account_id", &self.account_id) + .field("principal_name", &self.principal_name) + .field("session_name", &self.session_name) + .field("expires_at", &self.expires_at) + .finish_non_exhaustive() + } +} + +/// One page of [`StoredSecretRow`]s. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SecretPage { + /// The rows of the page. + pub rows: Vec, + /// The token of the next page, or `None` after the last page. + pub next: Option, +} + +/// One ciphertext to write back by primary key +/// ([`super::ManagementStore::write_secrets`]). +#[derive(Clone, PartialEq, Eq)] +pub struct SecretWrite { + /// [`StoredSecretRow::key`] of the row. + pub key: String, + /// The new `nonce(12) || ciphertext || tag(16)`. + pub secret_key_encrypted: Vec, + /// [`StoredSecretRow::write_timestamp`] of the read. Cassandra writes + /// with `USING TIMESTAMP` above it. + pub write_timestamp: Option, +} + +impl std::fmt::Debug for SecretWrite { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SecretWrite") + .field("write_timestamp", &self.write_timestamp) + .finish_non_exhaustive() + } +} + /// A stored session's policy, returned by /// [`super::ManagementStore::list_session_policies`] for the policy migration. /// diff --git a/crates/storage/src/migrations/catalog.rs b/crates/storage/src/migrations/catalog.rs index 4c85389c8..1c367c2bb 100644 --- a/crates/storage/src/migrations/catalog.rs +++ b/crates/storage/src/migrations/catalog.rs @@ -16,6 +16,8 @@ use super::ledger::LedgerRow; use super::registry::MigrationId; use super::status::{CatalogStatus, MigrationError, RunReport}; use super::table::{Kind, Migration, StoreKind}; +use crate::management_store::{ManagementStore, SettingsStore}; +use crate::server_components::KeySource; /// One migration of a backend's table, as `migrate --list` prints it. #[derive(Debug, Clone, PartialEq, Eq)] @@ -98,8 +100,10 @@ impl std::fmt::Debug for HeldLock { /// The deployment a command works on, with the values the command's flags /// gave (parsed by the command, or resolved by `init`'s bootstrapper). A -/// backend reads these fields and never the command line. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +/// backend reads these fields and never the command line. `Debug` prints +/// neither connection string: `location` and `data_connection` can carry a +/// password. +#[derive(Clone, Default, PartialEq, Eq)] pub struct Target { /// The deployment's storage location as the config file gives it /// (`[storage.]`): on SQLite the database file, on PostgreSQL @@ -115,6 +119,15 @@ pub struct Target { /// The data store's connection string, which `init` records with /// migration 1. Only `init` sets it. pub data_connection: Option, + /// The key the command read (`[auth.encryption] key_file`, or the + /// catalog key). On PostgreSQL the backend opens the data connection + /// string row of a catalog with a key ring with it (RFC-0000 section 12). + /// Default [`KeySource::CatalogKey`]. Its `Debug` prints no key bytes. + pub key_source: KeySource, + /// `encryption-key switch` only: the backend accepts a plaintext + /// `data_database_connection_string` row while the ring's + /// `switch_from_catalog_key` is true. Every other caller leaves it false. + pub plaintext_data_connection: bool, } impl Target { @@ -128,6 +141,22 @@ impl Target { } } +impl std::fmt::Debug for Target { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Target") + .field("location", &"") + .field("data_store", &self.data_store) + .field("admin", &self.admin) + .field( + "data_connection", + &self.data_connection.as_ref().map(|_| ""), + ) + .field("key_source", &self.key_source) + .field("plaintext_data_connection", &self.plaintext_data_connection) + .finish() + } +} + /// An admin role and its password. `Debug` prints no password. #[derive(Clone, Default, PartialEq, Eq)] pub struct AdminRole { @@ -144,6 +173,16 @@ impl std::fmt::Debug for AdminRole { } } +/// The catalog's stores under a held migration lock +/// ([`CatalogMigrations::locked_stores`]), for `switch`, `rotate` and +/// `reset` (RFC-0000 section 8, common rules). +pub trait LockedStores: Send + Sync { + /// The rows of `access_keys` and `iam_sessions`. + fn management(&self) -> &dyn ManagementStore; + /// The settings rows. + fn settings(&self) -> &dyn SettingsStore; +} + /// A backend's catalog migrations, for the deployment a [`Target`] names. #[async_trait] pub trait CatalogMigrations: Send + Sync { @@ -202,6 +241,16 @@ pub trait CatalogMigrations: Send + Sync { self.status(target).await } + /// The catalog status for a command that runs beside a server and reads + /// and writes rows of the catalog store only (`encryption-key rewrap` and + /// `set-data-connection`). Takes no lock and writes nothing. The status + /// as [`CatalogMigrations::status`] reads it by default; PostgreSQL reads + /// the catalog database alone, so the data connection string row, which + /// a catalog with a key ring keeps encrypted, is not read. + async fn catalog_store_status(&self, target: &Target) -> Result { + self.status(target).await + } + /// The catalog store's ledger rows, in id order, for `verify` to print /// their notes. Read-only; empty for a store with no ledger. async fn catalog_ledger(&self, target: &Target) -> Result, MigrationError>; @@ -231,6 +280,25 @@ pub trait CatalogMigrations: Send + Sync { drop(lock); } + /// Open the catalog's stores under `lock`, holding no key, for the + /// encryption-key commands that run while every server is stopped + /// (RFC-0000 section 8, common rules). On Cassandra and MongoDB the + /// stores check the lease before each request, as the stores of a + /// migration do. `data_connection` is the PostgreSQL connection string + /// that `reset` read from standard input, which takes the place of the + /// row (section 8.6). The default refuses, so every backend compiles + /// until it overrides it. + async fn locked_stores( + &self, + lock: &HeldLock, + data_connection: Option<&str>, + ) -> Result, MigrationError> { + let _ = (lock, data_connection); + Err(MigrationError::Refused( + "this storage backend does not open its stores under the migration lock".to_owned(), + )) + } + /// Notes about the deployment that its status does not show, for the /// preview and `verify` to print and `migrate --yes` to check before it /// takes the lock ([`before_lock`]). On PostgreSQL: tables and sequences @@ -469,11 +537,15 @@ mod tests { user: "admin".to_owned(), password: Some("s3cret".to_owned()), }), - ..Target::at("db") + data_connection: Some("postgres://app:d4ta@db/data".to_owned()), + ..Target::at("postgres://admin:c4talog@db/catalog") }; let shown = format!("{target:?}"); assert!(shown.contains("admin"), "{shown}"); - assert!(!shown.contains("s3cret"), "{shown}"); + assert!(shown.contains("data_connection: Some("), "{shown}"); + for secret in ["s3cret", "c4talog", "d4ta", "postgres://"] { + assert!(!shown.contains(secret), "{shown}"); + } } #[test] diff --git a/crates/storage/src/migrations/mod.rs b/crates/storage/src/migrations/mod.rs index aca1136e2..44ca4aa33 100644 --- a/crates/storage/src/migrations/mod.rs +++ b/crates/storage/src/migrations/mod.rs @@ -39,9 +39,9 @@ pub mod m0002_resource_tag_condition_keys; pub use backend::{MigrationBackend, Step, StoreRef}; pub use catalog::{ - AdminRole, CatalogMigrations, HeldLock, Listed, RunKind, StatusNote, Target, before_lock, - binary_catalog_label, forget_locked, installed, policy_rewrite_lines, policy_rewrite_pending, - run_locked, run_with_status, + AdminRole, CatalogMigrations, HeldLock, Listed, LockedStores, RunKind, StatusNote, Target, + before_lock, binary_catalog_label, forget_locked, installed, policy_rewrite_lines, + policy_rewrite_pending, run_locked, run_with_status, }; #[cfg(any(test, feature = "test-util"))] pub use checksum::check_released; diff --git a/crates/storage/src/secret_cipher.rs b/crates/storage/src/secret_cipher.rs index 453636630..c4c2190e8 100644 --- a/crates/storage/src/secret_cipher.rs +++ b/crates/storage/src/secret_cipher.rs @@ -1,16 +1,18 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! AES-256-GCM encryption of the secrets stored for access keys and sessions. +//! AES-256-GCM encryption of the stored secrets. //! -//! Every storage backend stores a secret as `nonce(12) || ciphertext || tag(16)`, -//! encrypted under the catalog encryption key: 32 bytes, base64 with the -//! standard alphabet, held in the catalog's `settings` table (a collection on -//! `MongoDB`). The access key id is the additional authenticated data (AAD), so -//! a stored secret decrypts only for the key id it was written with. There is -//! no decryption without the AAD: a ciphertext written without it fails -//! authentication like any corrupted value. An empty AAD is refused, because -//! AES-GCM treats an empty AAD and no AAD the same way. +//! Every storage backend stores a secret as `nonce(12) || ciphertext || tag(16)`. +//! The key is the catalog key (the `encryption_key` row of the catalog +//! `settings` table: 32 bytes, base64 with the standard alphabet) or, with a +//! KEK file, the DEK of the key ring ([`crate::key_ring`]), which this cipher +//! also wraps under the KEK. The additional authenticated data (AAD) binds each +//! ciphertext to its context: the access key id under the catalog key, and the +//! row fields of [`crate::secret_keys`] under a DEK. There is no decryption +//! without the AAD: a ciphertext written without it fails authentication like +//! any corrupted value. An empty AAD is refused, because AES-GCM treats an +//! empty AAD and no AAD the same way. //! //! The cipher is AWS-LC through `aws-lc-rs`, which draws a fresh random 96-bit //! nonce for each encryption. @@ -21,7 +23,7 @@ use base64::engine::general_purpose::STANDARD as BASE64; use zeroize::Zeroizing; /// Length of the decoded encryption key. -const KEY_LEN: usize = 32; +pub const KEY_LEN: usize = 32; /// Length of the GCM authentication tag that follows the ciphertext. const TAG_LEN: usize = 16; @@ -36,19 +38,7 @@ const TAG_LEN: usize = 16; /// decode to 32 bytes, or the encryption fails. pub fn encrypt_secret(plaintext: &str, key_b64: &str, aad: &str) -> Result, String> { require_aad(aad)?; - let key = cipher_key(key_b64)?; - - // Zeroizing, so the plaintext copy is wiped if the seal fails. The - // capacity is exact, so the buffer never reallocates. - let mut sealed = Zeroizing::new(Vec::with_capacity(NONCE_LEN + plaintext.len() + TAG_LEN)); - sealed.extend_from_slice(&[0; NONCE_LEN]); - sealed.extend_from_slice(plaintext.as_bytes()); - let (nonce, tag) = key - .seal_in_place_separate_tag(Aad::from(aad.as_bytes()), &mut sealed[NONCE_LEN..]) - .map_err(|_| "encrypt: AES-256-GCM seal failed".to_owned())?; - sealed[..NONCE_LEN].copy_from_slice(nonce.as_ref()); - sealed.extend_from_slice(tag.as_ref()); - Ok(std::mem::take(&mut *sealed)) + seal(&*decode_key(key_b64)?, plaintext.as_bytes(), aad) } /// Decrypt `nonce(12) || ciphertext || tag(16)` under the base64 key @@ -62,28 +52,79 @@ pub fn encrypt_secret(plaintext: &str, key_b64: &str, aad: &str) -> Result Result { require_aad(aad)?; - let (nonce, sealed) = match encrypted.split_first_chunk::() { - Some((nonce, sealed)) if sealed.len() >= TAG_LEN => (nonce, sealed), - _ => { - return Err(format!( - "ciphertext too short: {} bytes (need at least 12-byte nonce + 16-byte auth tag)", - encrypted.len() - )); - } - }; - let key = cipher_key(key_b64)?; + split_sealed(encrypted)?; + let mut plaintext = open_text(&*decode_key(key_b64)?, encrypted, aad)?; + Ok(std::mem::take(&mut *plaintext)) +} + +/// Encrypt `plaintext` under the 32 key bytes `key`, binding `aad`. Returns +/// `nonce(12) || ciphertext || tag(16)`. +pub(crate) fn seal(key: &[u8; KEY_LEN], plaintext: &[u8], aad: &str) -> Result, String> { + require_aad(aad)?; + let key = aead_key(key)?; + + // Zeroizing, so the plaintext copy is wiped if the seal fails. The + // capacity is exact, so the buffer never reallocates. + let mut sealed = Zeroizing::new(Vec::with_capacity(NONCE_LEN + plaintext.len() + TAG_LEN)); + sealed.extend_from_slice(&[0; NONCE_LEN]); + sealed.extend_from_slice(plaintext); + let (nonce, tag) = key + .seal_in_place_separate_tag(Aad::from(aad.as_bytes()), &mut sealed[NONCE_LEN..]) + .map_err(|_| "encrypt: AES-256-GCM seal failed".to_owned())?; + sealed[..NONCE_LEN].copy_from_slice(nonce.as_ref()); + sealed.extend_from_slice(tag.as_ref()); + Ok(std::mem::take(&mut *sealed)) +} +/// Decrypt `nonce(12) || ciphertext || tag(16)` under the 32 key bytes `key`, +/// authenticating `aad`. The plaintext is wiped when the result drops. +pub(crate) fn open( + key: &[u8; KEY_LEN], + encrypted: &[u8], + aad: &str, +) -> Result>, String> { + require_aad(aad)?; + let (nonce, sealed) = split_sealed(encrypted)?; + let key = aead_key(key)?; let mut in_out = Zeroizing::new(sealed.to_vec()); - let plaintext = key + let len = key .open_in_place( Nonce::from(nonce), Aad::from(aad.as_bytes()), &mut in_out[..], ) - .map_err(|_| "decrypt: authentication failed".to_owned())?; - std::str::from_utf8(plaintext) - .map(str::to_owned) - .map_err(|e| format!("decrypted secret is not valid UTF-8: {e}")) + .map_err(|_| "decrypt: authentication failed".to_owned())? + .len(); + in_out.truncate(len); + Ok(in_out) +} + +/// [`open`], for a plaintext that must be UTF-8 text. +pub(crate) fn open_text( + key: &[u8; KEY_LEN], + encrypted: &[u8], + aad: &str, +) -> Result, String> { + let mut plaintext = open(key, encrypted, aad)?; + match String::from_utf8(std::mem::take(&mut *plaintext)) { + Ok(text) => Ok(Zeroizing::new(text)), + Err(e) => { + let reason = format!("decrypted secret is not valid UTF-8: {}", e.utf8_error()); + drop(Zeroizing::new(e.into_bytes())); + Err(reason) + } + } +} + +/// Split `nonce(12) || sealed` and refuse input too short to hold a tag. +fn split_sealed(encrypted: &[u8]) -> Result<(&[u8; NONCE_LEN], &[u8]), String> { + match encrypted.split_first_chunk::() { + Some((nonce, sealed)) if sealed.len() >= TAG_LEN => Ok((nonce, sealed)), + _ => Err(format!( + "ciphertext too short: {} bytes (need at least 12-byte nonce + 16-byte auth tag)", + encrypted.len() + )), + } } /// Refuse an empty AAD. A ciphertext sealed with an empty AAD is the same as @@ -96,19 +137,46 @@ fn require_aad(aad: &str) -> Result<(), String> { Ok(()) } -/// Decode the base64 encryption key and load it into an AES-256-GCM key. -fn cipher_key(key_b64: &str) -> Result { +/// Decode a base64 key into its 32 bytes: the catalog key of the `encryption_key` +/// row, or the text of a KEK file ([`crate::key_ring::parse_kek_file`]). +/// +/// The reason for a key that does not decode names the kind of error and its +/// offset, and never the offending character, which can be part of the key. +pub(crate) fn decode_key(key_b64: &str) -> Result, String> { + let mut key = Zeroizing::new([0; KEY_LEN]); + decode_key_into(key_b64, &mut key)?; + Ok(key) +} + +/// [`decode_key`] into `key`, which then holds the only copy of the 32 bytes. +pub(crate) fn decode_key_into(key_b64: &str, key: &mut [u8; KEY_LEN]) -> Result<(), String> { // The capacity is the decoder's own size estimate, so `decode_vec` never // reallocates, and the decoded bytes, partial ones included, are wiped on // every return path. let mut key_bytes = Zeroizing::new(Vec::with_capacity(key_b64.len().div_ceil(4) * 3)); - BASE64 - .decode_vec(key_b64, &mut key_bytes) - .map_err(|e| format!("decode encryption key: {e}"))?; + BASE64.decode_vec(key_b64, &mut key_bytes).map_err(|e| { + let reason = match e { + base64::DecodeError::InvalidByte(offset, _) => { + format!("invalid symbol at offset {offset}") + } + base64::DecodeError::InvalidLastSymbol(offset, _) => { + format!("invalid last symbol at offset {offset}") + } + base64::DecodeError::InvalidLength(len) => format!("invalid input length {len}"), + base64::DecodeError::InvalidPadding => "invalid padding".to_owned(), + }; + format!("decode encryption key: {reason}") + })?; if key_bytes.len() != KEY_LEN { return Err("encryption key must be 32 bytes".to_owned()); } - RandomizedNonceKey::new(&AES_256_GCM, &key_bytes) + key.copy_from_slice(&key_bytes); + Ok(()) +} + +/// Load 32 key bytes into an AES-256-GCM key. +fn aead_key(key: &[u8; KEY_LEN]) -> Result { + RandomizedNonceKey::new(&AES_256_GCM, key) .map_err(|_| "load encryption key: AES-256-GCM key setup failed".to_owned()) } @@ -249,15 +317,23 @@ mod tests { "decrypt, {len}-byte key" ); } - let err = encrypt_secret(PLAINTEXT, "not base64!", AAD).unwrap_err(); - assert!(err.starts_with("decode encryption key: "), "{err}"); - let err = decrypt_secret(&sealed, "not base64!", AAD).unwrap_err(); - assert!(err.starts_with("decode encryption key: "), "{err}"); + // A trailing newline, from a key edited by hand, and a key without its + // padding are not base64. + for key in [ + "not base64!".to_owned(), + format!("{KEY_B64}\n"), + KEY_B64.trim_end_matches('=').to_owned(), + ] { + let err = encrypt_secret(PLAINTEXT, &key, AAD).unwrap_err(); + assert!(err.starts_with("decode encryption key: "), "{key:?}: {err}"); + let err = decrypt_secret(&sealed, &key, AAD).unwrap_err(); + assert!(err.starts_with("decode encryption key: "), "{key:?}: {err}"); + } } #[test] fn non_utf8_plaintext_is_rejected() { - let key = cipher_key(KEY_B64).expect("key"); + let key = aead_key(&decode_key(KEY_B64).expect("key")).expect("key"); let mut in_out = vec![0xff, 0xfe]; let (nonce, tag) = key .seal_in_place_separate_tag(Aad::from(AAD.as_bytes()), &mut in_out) @@ -323,7 +399,7 @@ mod tests { // which AES-GCM treats as no AAD, it yields the plaintext. The // rejections above come from the access key id binding, not from // damaged bytes. - let key = cipher_key(KEY_B64).expect("key"); + let key = aead_key(&decode_key(KEY_B64).expect("key")).expect("key"); let (nonce, sealed) = stored.split_first_chunk::().expect("nonce"); let mut in_out = sealed.to_vec(); let opened = key diff --git a/crates/storage/src/secret_keys.rs b/crates/storage/src/secret_keys.rs new file mode 100644 index 000000000..fd2ae38ac --- /dev/null +++ b/crates/storage/src/secret_keys.rs @@ -0,0 +1,383 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The key holder of the stored secrets, and the AAD encoding (RFC-0000 +//! sections 4, 5 and 6.2). +//! +//! A server holds one key: the catalog key, or the DEK of the key ring. Each +//! backend builds one [`SecretKeys`] at startup through +//! [`crate::server_components::load_secret_keys`], and its catalog store and +//! credential store share it. Each encrypt and decrypt site describes its row +//! with a [`SecretRow`], and the key holder builds the AAD from it: +//! +//! - under the catalog key, the access key id, as before the key ring; +//! - under a DEK, `extenddb-secret-v1` followed by the catalog id and the row +//! fields of section 5. +//! +//! The key bytes live in [`KeyBytes`], the one type of this crate that holds +//! them. + +use std::fmt::{self, Write as _}; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as BASE64; +use zeroize::Zeroizing; + +use crate::management_store::OpError; +use crate::secret_cipher::{self, KEY_LEN}; + +/// The settings row that holds the catalog key. +pub const CATALOG_KEY_SETTING: &str = "encryption_key"; + +/// The settings row that holds the catalog id, which migration 6 writes. +pub const CATALOG_ID_SETTING: &str = "catalog_id"; + +/// The PostgreSQL settings row that holds the data database connection +/// string. With a key ring its value is encrypted under the DEK (section 12). +pub const DATA_CONNECTION_SETTING: &str = "data_database_connection_string"; + +/// The kind of an AAD, which fixes its prefix. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AadKind { + /// A DEK wrapped under the KEK in the key ring. + Dek, + /// A stored secret under a DEK. + Secret, + /// The data database connection string row under a DEK. + Setting, +} + +impl AadKind { + /// The fixed text that starts every AAD of this kind. + #[must_use] + pub const fn prefix(self) -> &'static str { + match self { + Self::Dek => "extenddb-dek-v1", + Self::Secret => "extenddb-secret-v1", + Self::Setting => "extenddb-setting-v1", + } + } +} + +/// Encode an AAD: the prefix of `kind`, then for each field a `|`, the +/// field's length in bytes in decimal, a `:` and the field's bytes. No field +/// value can change where the next field starts, and an empty field (a null +/// value) is `0:`. +#[must_use] +pub fn encode_aad(kind: AadKind, fields: &[&str]) -> String { + let mut aad = String::from(kind.prefix()); + for field in fields { + // Writing to a String cannot fail. + let _ = write!(aad, "|{}:{field}", field.len()); + } + aad +} + +/// A catalog table that holds stored secrets. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum SecretTable { + /// `access_keys`: the secret of each access key of an IAM user. + AccessKeys, + /// `iam_sessions`: the secret of each AssumeRole session. + IamSessions, +} + +impl SecretTable { + /// Both tables, in the order the commands read them. + pub const ALL: [Self; 2] = [Self::AccessKeys, Self::IamSessions]; + + /// The table's name, which is also its field in the AAD. + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Self::AccessKeys => "access_keys", + Self::IamSessions => "iam_sessions", + } + } + + /// The table's primary key column. + #[must_use] + pub const fn key_column(self) -> &'static str { + match self { + Self::AccessKeys => "access_key_id", + Self::IamSessions => "session_token", + } + } +} + +/// The fields of a stored secret's row that its AAD binds (section 5). +/// +/// Every encrypt and decrypt site has these fields after its row read. The +/// AAD carries `expires_at` in whole Unix seconds, because the backends store +/// it at different precisions: a writer truncates the value before the +/// encrypt and before the write. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SecretRow<'a> { + /// The table that holds the row. + pub table: SecretTable, + /// The access key ID (`AKIA...` or `ASIA...`). + pub access_key_id: &'a str, + /// The account of the user or role. + pub account_id: &'a str, + /// The user name for an access key, the role name for a session. + pub principal_name: &'a str, + /// The session name, for a session only. + pub session_name: Option<&'a str>, + /// The session's `expires_at` in whole Unix seconds, for a session only. + pub expires_at: Option, +} + +impl<'a> SecretRow<'a> { + /// The row of an IAM user's access key. + #[must_use] + pub const fn access_key( + access_key_id: &'a str, + account_id: &'a str, + user_name: &'a str, + ) -> Self { + Self { + table: SecretTable::AccessKeys, + access_key_id, + account_id, + principal_name: user_name, + session_name: None, + expires_at: None, + } + } + + /// The row of an AssumeRole session. `expires_at` is in whole Unix seconds. + #[must_use] + pub const fn session( + access_key_id: &'a str, + account_id: &'a str, + role_name: &'a str, + session_name: &'a str, + expires_at: i64, + ) -> Self { + Self { + table: SecretTable::IamSessions, + access_key_id, + account_id, + principal_name: role_name, + session_name: Some(session_name), + expires_at: Some(expires_at), + } + } +} + +/// The 32 bytes of one key: the catalog key or a DEK. The one type of this +/// crate that holds key bytes. They sit in a slot of the locked key store +/// (`extenddb_auth::secmem`, RFC-0000 section 6.2), which wipes the slot when +/// it drops. +pub(crate) struct KeyBytes(extenddb_auth::secmem::KeySlot); + +impl KeyBytes { + /// Copy `bytes` into a slot of the locked key store. `bytes` is wiped + /// when it drops. + /// + /// # Errors + /// + /// When the store has no free slot. + pub(crate) fn new(bytes: Zeroizing<[u8; KEY_LEN]>) -> Result { + extenddb_auth::secmem::KeySlot::from_bytes(&bytes) + .map(Self) + .map_err(|e| e.to_string()) + } + + /// A new random key, from the generator that `init` uses for the catalog + /// key ([`crate::bootstrapper::helpers::generate_encryption_key`]). + pub(crate) fn generate() -> Result { + let text = Zeroizing::new(crate::bootstrapper::helpers::generate_encryption_key()?); + Self::new(secret_cipher::decode_key(&text)?) + } + + /// The key bytes. + pub(crate) fn expose(&self) -> &[u8; KEY_LEN] { + self.0.expose() + } +} + +/// The key a [`SecretKeys`] holds. +enum Mode { + /// The catalog key: the AAD is the access key ID. + CatalogKey, + /// A DEK of the key ring: the AAD is section 5's. + Dek { id: u64, catalog_id: String }, +} + +/// The key holder of a store: the one key that encrypts and decrypts the +/// stored secrets, the catalog key or a DEK. +/// +/// A backend builds one per process and shares it between its catalog store +/// and its credential store. A store built with no key holder refuses to +/// create, import or store a credential. +pub struct SecretKeys { + key: KeyBytes, + mode: Mode, +} + +impl SecretKeys { + /// A key holder for the catalog key, from the base64 text of the + /// `encryption_key` row. + /// + /// # Errors + /// + /// The secret cipher's reason when the text is not base64 or does not + /// decode to 32 bytes. + pub fn catalog_key(key_b64: &str) -> Result { + Ok(Self { + key: KeyBytes::new(secret_cipher::decode_key(key_b64)?)?, + mode: Mode::CatalogKey, + }) + } + + /// A key holder for the DEK `id` of the key ring of catalog `catalog_id`. + pub(crate) fn dek(key: KeyBytes, id: u64, catalog_id: &str) -> Self { + Self { + key, + mode: Mode::Dek { + id, + catalog_id: catalog_id.to_owned(), + }, + } + } + + /// A DEK key holder over `bytes`, for the tests of a backend's encrypt + /// and decrypt sites. + #[cfg(any(test, feature = "test-util"))] + #[must_use] + pub fn dek_for_tests(bytes: [u8; KEY_LEN], id: u64, catalog_id: &str) -> Self { + Self::dek( + KeyBytes::new(Zeroizing::new(bytes)).expect("a free slot of the locked key store"), + id, + catalog_id, + ) + } + + /// The key bytes, for the key ring's wrap and key ids. + pub(crate) fn key_bytes(&self) -> &KeyBytes { + &self.key + } + + /// The DEK id, or `None` for the catalog key. + #[must_use] + pub fn dek_id(&self) -> Option { + match &self.mode { + Mode::CatalogKey => None, + Mode::Dek { id, .. } => Some(*id), + } + } + + /// The catalog id in the AAD of a DEK, or `None` for the catalog key. + #[must_use] + pub fn catalog_id(&self) -> Option<&str> { + match &self.mode { + Mode::CatalogKey => None, + Mode::Dek { catalog_id, .. } => Some(catalog_id), + } + } + + /// The AAD of a stored secret in `row` under this key. + #[must_use] + pub fn aad(&self, row: &SecretRow<'_>) -> String { + match &self.mode { + Mode::CatalogKey => row.access_key_id.to_owned(), + Mode::Dek { catalog_id, .. } => { + let expires_at = row.expires_at.map(|t| t.to_string()); + encode_aad( + AadKind::Secret, + &[ + catalog_id, + row.table.name(), + row.access_key_id, + row.account_id, + row.principal_name, + row.session_name.unwrap_or(""), + expires_at.as_deref().unwrap_or(""), + ], + ) + } + } + } + + /// Encrypt the secret of `row`. Returns `nonce(12) || ciphertext || tag(16)`. + /// + /// # Errors + /// + /// The secret cipher's reason, for example an empty access key ID under + /// the catalog key. + pub fn encrypt(&self, row: &SecretRow<'_>, secret: &str) -> Result, String> { + secret_cipher::seal(self.key.expose(), secret.as_bytes(), &self.aad(row)) + } + + /// Decrypt the stored secret of `row`. The plaintext is wiped when the + /// result drops. + /// + /// # Errors + /// + /// `decrypt: authentication failed` when this key does not open the + /// secret: another key, another row, or altered bytes. + pub fn decrypt(&self, row: &SecretRow<'_>, stored: &[u8]) -> Result, String> { + secret_cipher::open_text(self.key.expose(), stored, &self.aad(row)) + } + + /// Encrypt the data database connection string under a DEK, with the AAD + /// of section 12. Returns the base64 text the settings row stores. + /// + /// # Errors + /// + /// Under the catalog key, which encrypts no setting, and on a cipher error. + pub fn encrypt_setting(&self, value: &str) -> Result { + let sealed = + secret_cipher::seal(self.key.expose(), value.as_bytes(), &self.setting_aad()?)?; + Ok(BASE64.encode(sealed)) + } + + /// Decrypt the base64 text of the data database connection string row. + /// + /// # Errors + /// + /// Under the catalog key, and when the text is not base64 or this DEK + /// does not open it (a plaintext row included). + pub fn decrypt_setting(&self, stored: &str) -> Result, String> { + let aad = self.setting_aad()?; + let sealed = BASE64 + .decode(stored) + .map_err(|_| "decrypt: the stored value is not base64".to_owned())?; + secret_cipher::open_text(self.key.expose(), &sealed, &aad) + } + + /// `extenddb-setting-v1||data_database_connection_string`. + fn setting_aad(&self) -> Result { + match &self.mode { + Mode::CatalogKey => Err("the catalog key encrypts no setting".to_owned()), + Mode::Dek { catalog_id, .. } => Ok(encode_aad( + AadKind::Setting, + &[catalog_id, DATA_CONNECTION_SETTING], + )), + } + } +} + +impl fmt::Debug for SecretKeys { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SecretKeys") + .field("dek_id", &self.dek_id()) + .finish_non_exhaustive() + } +} + +/// The key holder of a store that creates, imports or stores a credential, +/// or the refusal of a store built with no key (RFC-0000 section 7). +/// +/// # Errors +/// +/// [`OpError::Internal`] when `keys` is `None`. +pub fn require_keys(keys: Option<&SecretKeys>) -> Result<&SecretKeys, OpError> { + keys.ok_or_else(|| { + OpError::Internal( + "this store was opened without an encryption key, so it writes no credential" + .to_owned(), + ) + }) +} diff --git a/crates/storage/src/server_components.rs b/crates/storage/src/server_components.rs index c685e383a..761e9fbcb 100644 --- a/crates/storage/src/server_components.rs +++ b/crates/storage/src/server_components.rs @@ -17,6 +17,9 @@ use extenddb_auth::CredentialStore; use crate::config::StorageConfig; use crate::hooks::ServerRuntimeHooks; +use crate::key_ring::{Kek, KeyRefusal, KeyRing, KeyRows, open_ring}; +use crate::management_store::SettingsStore; +use crate::secret_keys::SecretKeys; use crate::{CatalogStore, StorageEngine}; /// Components needed to run the extenddb server. @@ -51,6 +54,11 @@ pub enum BackendError { /// Encryption key not found in settings table MissingEncryptionKey, + /// The encryption key in the settings table is one the secret cipher + /// refuses: it is not base64, or it does not decode to 32 bytes. Carries + /// the cipher's reason. + InvalidEncryptionKey(String), + /// Generic initialization failure InitializationFailed(String), @@ -75,6 +83,13 @@ impl std::fmt::Display for BackendError { f, "Encryption key not found in settings table. Run 'extenddb init'" ), + Self::InvalidEncryptionKey(reason) => write!( + f, + "Encryption key in settings table is not valid: {}. Restore the \ + original key: every stored access key and session secret is encrypted \ + under it", + reason.trim_end_matches('.') + ), Self::InitializationFailed(msg) => write!(f, "Backend initialization failed: {msg}"), Self::Catalog(e) => write!(f, "{e}"), } @@ -83,8 +98,129 @@ impl std::fmt::Display for BackendError { impl std::error::Error for BackendError {} +/// The key a factory loads (RFC-0000 section 7). `serve` and each command +/// pass it, so no code in this crate reads a file. +#[derive(Clone, Default)] +pub enum KeySource { + /// `key_file` is not set: the catalog key of the `encryption_key` row. + #[default] + CatalogKey, + /// `key_file` is set: the KEK that the caller read from it through the + /// file rule. The loader unwraps the ring's DEK with it and drops it, + /// which wipes it when it holds the last reference. A move or a + /// `mem::take` of the source copies a pointer and leaves the key where + /// it is. + Kek(Kek), + /// No key: the stores refuse to create, import or store a credential. + /// For callers that write no credential and read no stored secret. + None, +} + +impl std::fmt::Debug for KeySource { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::CatalogKey => "CatalogKey", + Self::Kek(_) => "Kek(..)", + Self::None => "None", + }) + } +} + +/// Two KEK sources are equal only when their bytes match, compared in +/// constant time (`CRYPTO_memcmp` through `aws-lc-rs`). +impl PartialEq for KeySource { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::CatalogKey, Self::CatalogKey) | (Self::None, Self::None) => true, + (Self::Kek(a), Self::Kek(b)) => { + aws_lc_rs::constant_time::verify_slices_are_equal(&a[..], &b[..]).is_ok() + } + _ => false, + } + } +} + +impl Eq for KeySource {} + +/// Load the key of a store from the catalog's key rows (RFC-0000 section 7). +/// +/// Each backend factory calls this once, in place of its own key query, with +/// a settings store over the catalog and the [`ServerComponentsOptions::key_source`] +/// it was given (take it with `std::mem::take`, so the KEK is wiped here). It +/// reads the `encryption_key`, `encryption_key_ring` and `catalog_id` rows +/// through [`SettingsStore::get_setting`], then applies the rows of the +/// section 7 table in order, and the first row that matches decides. With a +/// KEK it compares the KEK id first and unwraps every DEK second, and reads +/// no other ring field until all of them unwrap. +/// +/// Returns the one key holder that the backend's stores share, or `None` for +/// [`KeySource::None`], which reads nothing. +/// +/// # Errors +/// +/// [`BackendError::MissingEncryptionKey`] for a catalog with neither key row +/// and no `key_file`, [`BackendError::InvalidEncryptionKey`] for a catalog key +/// that the cipher refuses, and [`BackendError::InitializationFailed`] with the +/// table row's message for every other refusal and for a failed read. +pub async fn load_secret_keys( + settings: &dyn SettingsStore, + source: KeySource, +) -> Result>, BackendError> { + let kek = match source { + KeySource::None => return Ok(None), + KeySource::CatalogKey => None, + KeySource::Kek(kek) => Some(kek), + }; + let rows = KeyRows::read(settings).await.map_err(|e| { + BackendError::InitializationFailed(format!("read the encryption key rows: {}", e.message())) + })?; + let refused = |refusal: KeyRefusal| BackendError::InitializationFailed(refusal.to_string()); + let keys = match (kek, rows.ring.as_deref()) { + (None, Some(text)) => { + // No KEK to check the ring with: name only the next step, whose + // command checks the ring before it writes. + return Err(refused(match KeyRing::parse(text) { + Err(reason) => KeyRefusal::DamagedRing { + reason: format!("the ring does not parse: {reason}"), + }, + Ok(ring) if ring.switch_from_catalog_key => { + KeyRefusal::UnfinishedSwitchWithoutKeyFile + } + Ok(ring) => KeyRefusal::RingNeedsKeyFile { + kek_id: ring.kek.id, + }, + })); + } + (None, None) => { + let key = rows + .catalog_key + .as_deref() + .ok_or(BackendError::MissingEncryptionKey)?; + SecretKeys::catalog_key(key).map_err(BackendError::InvalidEncryptionKey)? + } + (Some(_), None) if rows.catalog_key.is_some() => { + return Err(refused(KeyRefusal::CatalogKeyWithoutRing)); + } + (Some(_), None) => return Err(refused(KeyRefusal::NoRing)), + (Some(kek), Some(text)) => { + let mut open = open_ring(text, rows.catalog_id.as_deref(), &kek).map_err(refused)?; + if open.ring.switch_from_catalog_key { + return Err(refused(KeyRefusal::UnfinishedSwitchWithKeyFile)); + } + if rows.catalog_key.is_some() { + return Err(refused(KeyRefusal::CatalogKeyAfterSwitch)); + } + if open.deks.len() > 1 { + return Err(refused(KeyRefusal::UnfinishedRotation)); + } + open.deks.pop().expect("an open ring holds a DEK") + } + }; + Ok(Some(Arc::new(keys))) +} + /// Options for server-component creation, beyond the storage config itself. -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] #[non_exhaustive] pub struct ServerComponentsOptions { /// Bootstrap the catalog at serve time when it is not initialized, @@ -132,6 +268,9 @@ pub struct ServerComponentsOptions { /// `extenddb_servers` entry), which a migration waiting for the /// registrations prints; `None` is `extenddb serve`. pub command: Option<&'static str>, + /// The key the factory loads with [`load_secret_keys`]. The default is + /// the catalog key, as before the key ring. + pub key_source: KeySource, } impl Default for ServerComponentsOptions { @@ -144,6 +283,7 @@ impl Default for ServerComponentsOptions { beside_server: false, startup_recovery: true, command: None, + key_source: KeySource::CatalogKey, } } } @@ -269,4 +409,43 @@ mod tests { ); assert!(warnings_for("us-east-1").await.is_empty()); } + + /// A key source is smaller than a key, so it cannot hold the KEK's bytes: + /// a move of it, or the `mem::take` of a factory, copies a pointer to the + /// one allocation of the KEK, and a clone shares that allocation. + #[test] + fn a_key_source_holds_a_pointer_to_the_kek() { + assert!(std::mem::size_of::() < crate::secret_cipher::KEY_LEN); + let kek = + crate::key_ring::parse_kek_file(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n") + .expect("a KEK file"); + let source = KeySource::Kek(Arc::clone(&kek)); + let KeySource::Kek(held) = source.clone() else { + panic!("a KEK source"); + }; + assert!(Arc::ptr_eq(&held, &kek)); + } + + #[test] + fn a_key_the_cipher_refuses_is_an_invalid_encryption_key() { + // The error that `load_secret_keys` gives a catalog key that does + // not load. + let invalid = |key: &str| { + SecretKeys::catalog_key(key) + .map(drop) + .map_err(BackendError::InvalidEncryptionKey) + .unwrap_err() + .to_string() + }; + // 16 zero bytes. + assert_eq!( + invalid("AAAAAAAAAAAAAAAAAAAAAA=="), + "Encryption key in settings table is not valid: encryption key must be 32 \ + bytes. Restore the original key: every stored access key and session \ + secret is encrypted under it" + ); + // The base64 decoder's reason ends with a period of its own. + let err = invalid("AAAA-AAA"); + assert!(err.contains("offset 4. Restore"), "{err}"); + } } diff --git a/devtools/run-tests b/devtools/run-tests index e7e2aa540..c778f3b40 100755 --- a/devtools/run-tests +++ b/devtools/run-tests @@ -578,7 +578,7 @@ if $RUN_PYTEST; then # -rP: the summary repeats the passed tests that printed something (the # backup cells print which branch ran and which store the server reports), # which pytest's capture would otherwise keep out of the log. - PYTEST_ARGS=(python3 -m pytest tests/ -v -rP --ignore=tests/python --ignore=tests/test_cli_lifecycle.py --ignore=tests/test_cli_container_readiness.py --ignore=tests/test_cli_migrate_concurrency.py --ignore=tests/test_cli_vector_catalog_migration.py --ignore=tests/test_gsi_async_queue.py --ignore=tests/test_backup_store_config.py --ignore=tests/test_backup_job.py) + PYTEST_ARGS=(python3 -m pytest tests/ -v -rP --ignore=tests/python --ignore=tests/test_cli_lifecycle.py --ignore=tests/test_cli_encryption_key.py --ignore=tests/test_cli_container_readiness.py --ignore=tests/test_cli_migrate_concurrency.py --ignore=tests/test_cli_vector_catalog_migration.py --ignore=tests/test_gsi_async_queue.py --ignore=tests/test_backup_store_config.py --ignore=tests/test_backup_job.py) # Parallel execution (--parallel): distribute by file so module/class-scoped # fixtures stay within a single worker. if [[ -n "$PARALLEL" ]] && python3 -c "import xdist" 2>/dev/null; then @@ -692,7 +692,7 @@ if $RUN_PYTEST \ && -n "${EXTENDDB_TEST_PG_CONNECTION_STRING:-}" ]]; then CLI_OUTFILE="discussions/test-cli-${HASH}.txt" echo "=== CLI lifecycle tests → ${CLI_OUTFILE} ===" - CLI_ARGS=(python3 -m pytest tests/test_cli_lifecycle.py tests/test_cli_container_readiness.py tests/test_cli_migrate_concurrency.py tests/test_cli_vector_catalog_migration.py tests/test_backup_store_config.py -v) + CLI_ARGS=(python3 -m pytest tests/test_cli_lifecycle.py tests/test_cli_encryption_key.py tests/test_cli_container_readiness.py tests/test_cli_migrate_concurrency.py tests/test_cli_vector_catalog_migration.py tests/test_backup_store_config.py -v) if [[ -n "$FILTER" ]]; then CLI_ARGS+=(-k "$FILTER") fi diff --git a/docker/README.md b/docker/README.md index 0b5aeecf6..66275e0f5 100644 --- a/docker/README.md +++ b/docker/README.md @@ -176,6 +176,46 @@ Mount configuration/TLS state at `/var/lib/extenddb`, set the root filesystem read-only, drop all capabilities, use the runtime default seccomp profile, and apply CPU/memory limits in the orchestrator. +### Encryption key file + +By default the catalog holds the key that encrypts stored secrets, so a copy of +the catalog opens every access key secret. To keep that key outside the catalog, +give the container a key-encryption key (KEK) file and set +`EXTENDDB__AUTH__ENCRYPTION__KEY_FILE` to its path (the admin guide's +[Encryption Key](../docs/manuals/05-admin-guide.md#encryption-key) section gives +the file format, the ownership rule and the `extenddb encryption-key` commands). +The server runs as uid 10001. It refuses a KEK file that neither root nor uid +10001 owns, and one that another user can read, except through the server's +group on a file that root owns; it cannot see who belongs to that group, so give +the group no other members. Each runtime must deliver the file with `uid`, `gid` +and `mode` set: + +* Docker swarm: `--secret source=extenddb-kek,target=kek,uid=10001,gid=10001,mode=0400`. + The default, root with mode 0444, is refused. Swarm keeps every secret in the + Raft log of its managers with the log's key unencrypted on each manager's disk; + `--autolock` keeps a copy of a manager's disk from giving the KEK, at the cost + of an operator typing the unlock key after each manager restart. +* Podman: `--secret extenddb-kek,type=mount,uid=10001,gid=10001,mode=0400`. +* Kubernetes: a Secret volume with `defaultMode: 0400` and + `securityContext: {runAsUser: 10001, runAsGroup: 10001, fsGroup: 10001}` on the + pod, which gives the file to root with group 10001 at mode 0440. +* Compose file secrets are bind mounts that ignore `uid`, `gid` and `mode`: uid + 10001 must own the host file at mode 0400. + +The server keeps the key and the cached signing keys in locked memory. The +default memlock limit is 64 KiB on kernels before 5.16, below the 640,000 bytes +the default cache size needs, so pass `--ulimit memlock=16777216:16777216` to +`docker run` (or the runtime's equivalent) on such hosts; with the key file set, +a server that cannot lock its memory refuses to start and names the limit it +needs. `--cap-add IPC_LOCK` alone does not raise the limit for uid 10001. + +The switch to the KEK file and a later key replacement run while no server +runs, as one-off containers with the same secret: a one-off swarm service, a +`podman run`, or a Kubernetes Job while the Deployment has 0 replicas. Each runs +`extenddb encryption-key --config /var/lib/extenddb/extenddb.toml`. +Keep a copy of the KEK away from the runtime's secret store: the store is not a +backup of it, and a catalog copy wrapped under a lost KEK keeps no stored secret. + ## Known image limitations * The repository has no backend-aware readiness endpoint; health is liveness. diff --git a/docs/adr/0026-credential-crypto-on-aws-lc.md b/docs/adr/0026-credential-crypto-on-aws-lc.md index 75d6e9ef9..1e21b5659 100644 --- a/docs/adr/0026-credential-crypto-on-aws-lc.md +++ b/docs/adr/0026-credential-crypto-on-aws-lc.md @@ -28,7 +28,10 @@ the `sha2` and `hmac` crates and compared signatures with a hand-written loop. AWS-LC is already in every ExtendDB binary. ExtendDB installs the `rustls::crypto::aws_lc_rs` provider for its TLS server and clients, and sqlx -connects to PostgreSQL with `tls-rustls-aws-lc-rs`. +connects to PostgreSQL with `tls-rustls-aws-lc-rs`. The MongoDB driver does not +use the installed provider. With its default `rustls-tls` feature it builds its +TLS client configuration on `rustls::crypto::ring`, so the MongoDB backend +connects to MongoDB through ring. ## Options Considered @@ -39,9 +42,10 @@ connects to PostgreSQL with `tls-rustls-aws-lc-rs`. encryption, and the SigV4 SHA-256, HMAC-SHA256 and signature compare, all from AWS-LC, the library the TLS provider already uses. 3. **Move the credential path onto ring.** ring has the same primitives and is - in `Cargo.lock`, but of the backend builds only the MongoDB one links it. - ExtendDB does not use ring as its TLS provider, and ring has no Federal - Information Processing Standards (FIPS) module. + in `Cargo.lock`, but of the backend builds only the MongoDB one links it, + for the MongoDB driver's TLS connections. The ExtendDB TLS server and its + other TLS clients do not use ring, and ring has no Federal Information + Processing Standards (FIPS) module. ## Decision @@ -72,7 +76,10 @@ HMAC-SHA256 and signature compare use aws-lc-rs (Option 2). - The stored format does not change: `nonce(12) || ciphertext || tag(16)`, with the access key id as AAD. Unit tests decrypt a secret from the 0.1.14 - release fixture and a secret written by the `aes-gcm` code. + release fixture and a secret written by the `aes-gcm` code. RFC-0000 (#707) + keeps the format and, for a secret under a data encryption key, makes the AAD + bind the row: catalog id, table, access key id, account, principal, session + name and expiry. - A secret written without AAD no longer decrypts, and an empty AAD is refused. No release wrote such a secret. - `sha2` stays for principal ids in `crates/auth/src/policy/principal_id.rs`, @@ -82,8 +89,12 @@ HMAC-SHA256 and signature compare use aws-lc-rs (Option 2). so the toolchain requirement is unchanged. A build of `extenddb-storage`, `extenddb-auth`, or the Cassandra or MongoDB backend crate on its own now compiles `aws-lc-sys` as well. -- The encryption key is still stored in the catalog. Moving it out of the - catalog and adding rotation needs an RFC. +- The encryption key is stored in the catalog by default. RFC-0000 (#707) adds + `[auth.encryption] key_file`: a key-encryption key in a file on the server + host wraps the data encryption key, the catalog holds only the wrapped key, + and `extenddb encryption-key` switches a deployment to the file, rewraps the + key under a new file and replaces the data encryption key. Its wrap, unwrap + and key id (HMAC-SHA256) use aws-lc-rs as well. --- diff --git a/docs/cassandra-setup.md b/docs/cassandra-setup.md index 951926c64..0af0a5ba5 100644 --- a/docs/cassandra-setup.md +++ b/docs/cassandra-setup.md @@ -350,6 +350,11 @@ keyspace is up. It reads the backup data that older versions wrote at `ALL`, so it fails when any replica is down, even with a replication factor of 3. See [Migrating legacy backups into the store](manuals/14-backup-and-restore.md#migrating-legacy-backups-into-the-store). +Run the `extenddb encryption-key` commands only when every replica of the +catalog keyspace is up. They read the key rows at `ALL`, and they write the key +ring and the stored secrets at `ALL`. So they fail when any replica is down, +even with a replication factor of 3. + ExtendDB creates its keyspaces with `NetworkTopologyStrategy`, with `replication_factor` replicas in `datacenter`. Use the name your cluster's nodes report (`nodetool status` prints it); in the `ALTER KEYSPACE` statements diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index 69659cfce..2e75cb64e 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -194,8 +194,18 @@ IAM-type entities. Runtime settings storage (key-value store): - `get_setting`, `set_setting`, `list_settings`, `cached_encryption_key` -Settings include `control_plane_delay_seconds`, `log_level`, and the -encryption key for access key secrets. +Settings include `control_plane_delay_seconds`, `log_level`, and the key +material for stored secrets: the catalog key (`encryption_key`) or, with +`[auth.encryption] key_file` set, the key ring (`encryption_key_ring`) that +holds the data encryption key wrapped under the key-encryption key in that +file. One function in `crates/storage` loads the key from the two rows and the +configured key source at startup and returns the one key the server uses, or a +refusal that names the command that fixes the state (the admin guide's +Encryption Key section). Each backend holds that key once, in the locked key +store, and a store built without the key refuses to create, import or store a +credential. The re-encryption pass of `extenddb encryption-key` is one driver in +this crate; each backend adds a paged read of the credential rows, a batch write +of ciphertexts by primary key, and the delete of one settings row. ### MetricsStore diff --git a/docs/design/05-component-auth-v3.md b/docs/design/05-component-auth-v3.md index b28af7e80..8c59e5871 100755 --- a/docs/design/05-component-auth-v3.md +++ b/docs/design/05-component-auth-v3.md @@ -12,7 +12,7 @@ The `auth` crate provides pluggable authentication and authorization for extendd The crate depends on `extenddb-core` (for types and errors) and `async_trait` (for object-safe async trait dispatch). It has no HTTP framework or storage dependencies. -> **Caching.** Credential lookups and policy fetches go through in-memory caches with write-through invalidation and a TTL: the credential cache in this crate (`credential_cache.rs`) and the authorization caches in the server crate (`authz_cache.rs`). `docs/design/12-auth-authz-cache.md` describes that design and replaces the "no caching" decision this document originally recorded. +> **Caching.** Credential lookups and policy fetches go through in-memory caches with write-through invalidation and a TTL: the credential cache in this crate (`credential_cache.rs`) and the authorization caches in the server crate (`authz_cache.rs`). `docs/design/12-auth-authz-cache.md` describes that design and replaces the "no caching" decision this document originally recorded. The credential cache holds no plaintext secret or session token: for each access key it keeps the principal fields, the SHA-256 of the session token and one SigV4 signing key per scope date in use, in the locked key store of this crate (`secmem.rs`), which keeps its pages out of swap and core dumps. ## 2. Key Design Decisions (from 2026-04-15 review session) @@ -321,11 +321,11 @@ The `OperationContext` carries `account_id` from auth resolution. Every engine d Unchanged from v2.0 §5.1. The server-side flow: 1. Parse `Authorization: AWS4-HMAC-SHA256 Credential=///dynamodb/aws4_request, SignedHeaders=, Signature=` -2. Look up `access_key_id` → `StoredCredential` (encrypted secret, account_id, user_name) -3. Decrypt secret key (AES-256-GCM) +2. Look up `access_key_id` in the credential cache; on a miss, read `StoredCredential` (encrypted secret, account_id, user_name) from the catalog +3. On a miss, decrypt the secret key (AES-256-GCM), derive the signing key of step 6 into a slot of the locked key store, and wipe the secret; a hit uses the cached signing key 4. Validate timestamp (X-Amz-Date within ±15 minutes) 5. Reconstruct canonical request from HTTP method, URI, signed headers, body hash -6. Derive signing key: 4-step HMAC-SHA256 chain (date → region → service → aws4_request) +6. Derive signing key: 4-step HMAC-SHA256 chain (date → region → service → aws4_request), once per access key and scope date 7. Compute expected signature 8. Constant-time compare 9. On match: resolve full identity (user or role session) @@ -403,12 +403,14 @@ Flow: ## 10. Encryption Key Management -Secret keys are encrypted at rest with AES-256-GCM. The encryption key is generated at `extenddb init` time and stored in the `settings` table. The threat model is: the Postgres database is the trust boundary. If an attacker can read the settings table, they already have access to all data. +Secret keys are encrypted at rest with AES-256-GCM. By default the encryption key is generated at `extenddb init` time and stored in the `settings` table, with the access key ID as the additional authenticated data (AAD), and the catalog database is the trust boundary: a reader of the settings table holds the key and every stored secret. ```sql INSERT INTO settings (key, value) VALUES ('encryption_key', ''); ``` +With `[auth.encryption] key_file` set, a key-encryption key (KEK) in a file on the server host wraps a data encryption key (DEK), and the catalog holds only the wrapped DEK, in the `settings` row `encryption_key_ring`, together with the KEK's id and the state of an unfinished switch or rotation. The KEK authenticates every field of the ring through the AAD of each wrapped DEK. Each stored secret written under the DEK carries an AAD that binds it to its row: `extenddb-secret-v1|||||||`, each field as its length in decimal, a colon and the bytes, so a writer to the catalog without the key cannot reassign a secret to another principal or extend a session. The server reads the KEK once at startup, unwraps the DEK into the locked key store and wipes the KEK. The `extenddb encryption-key` commands switch a deployment to a KEK file, rewrap the DEK under a new KEK, replace the DEK, and recover a restored catalog whose KEK is lost. The Security Model's threat model table gives what each attacker gets in each mode, and the admin guide's Encryption Key section the commands and the delivery routes of the file. + ## 11. Management API Endpoints All under `/management/*`. Authenticated via HTTP Basic auth (admin users use `admin_name:password`, IAM users use `account_id/user_name:password`). diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index 553cbb425..46cd8c524 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -471,7 +471,7 @@ All management routes use `POST /management/` with JSON request/response } ``` -> **Note:** The `SecretAccessKey` is returned only in this response and is not retrievable afterward. The storage layer stores the raw secret (not a hash) because SigV4 authentication requires the original secret key for HMAC computation. Secrets are encrypted at rest with AES-256-GCM using a per-catalog encryption key generated during `extenddb init`. +> **Note:** The `SecretAccessKey` is returned only in this response and is not retrievable afterward. The storage layer stores the raw secret (not a hash) because SigV4 authentication requires the original secret key for HMAC computation. Secrets are encrypted at rest with AES-256-GCM. By default the key is a per-catalog encryption key generated during `extenddb init`; with `[auth.encryption] key_file` set, it is a data encryption key that a key-encryption key file wraps (the Security Model's Credential Storage section). The response holds the secret for the life of the request, and afterwards the server's credential cache keeps only the SigV4 signing key derived from it. **Assume Role:** ```json diff --git a/docs/design/08-component-config.md b/docs/design/08-component-config.md index 5352a508e..8bc636e4b 100755 --- a/docs/design/08-component-config.md +++ b/docs/design/08-component-config.md @@ -55,6 +55,8 @@ Environment variables use double-underscore (`__`) as a nesting separator, prefi | `auth.aws_iam.region` | `EXTENDDB__AUTH__AWS_IAM__REGION` | | `auth.aws_iam.identity_cache_ttl_seconds` | `EXTENDDB__AUTH__AWS_IAM__IDENTITY_CACHE_TTL_SECONDS` | | `auth.aws_iam.policy_cache_ttl_seconds` | `EXTENDDB__AUTH__AWS_IAM__POLICY_CACHE_TTL_SECONDS` | +| `auth.encryption.key_file` | `EXTENDDB__AUTH__ENCRYPTION__KEY_FILE` | +| `auth.encryption.require_locked_memory` | `EXTENDDB__AUTH__ENCRYPTION__REQUIRE_LOCKED_MEMORY` | | `limits.max_item_size_bytes` | `EXTENDDB__LIMITS__MAX_ITEM_SIZE_BYTES` | ### 2.3 Loading @@ -122,10 +124,16 @@ provider = "builtin" # "none" | "builtin" | "aws_iam" | future: "azure_ad" region = "us-east-1" # Region for SigV4 validation # The credential encryption key is not read from this file: `extenddb init` generates it # and stores it in the catalog `settings` table (see docs/manuals/10-security-model.md). +# With [auth.encryption] key_file set, the catalog holds that key wrapped under the +# key-encryption key in the named file (see docs/manuals/05-admin-guide.md, Encryption Key). credential_cache_ttl_secs = 300 policy_cache_ttl_secs = 300 timestamp_skew_secs = 300 +[auth.encryption] +# key_file = "/etc/extenddb/kek" # set after `extenddb encryption-key switch --yes`; unset keeps the catalog key +# require_locked_memory = true # with key_file set, refuse to start when the key store cannot be locked + [limits] # Item & attribute limits max_item_size_bytes = 409600 # 400 KB diff --git a/docs/design/13-storage-mongodb.md b/docs/design/13-storage-mongodb.md index 0f1b6990b..f43516099 100644 --- a/docs/design/13-storage-mongodb.md +++ b/docs/design/13-storage-mongodb.md @@ -111,7 +111,11 @@ field is unset when the index flips to `ACTIVE`. ``` Keys include `catalog_version` (the catalog's migration id, which the migration runner writes with each catalog ledger row), `encryption_key` -(base64-encoded 256-bit AES-GCM key), `data_database_name`, and +(base64-encoded 256-bit AES-GCM key, the catalog key; absent after the switch +to a key-encryption key file), `encryption_key_ring` (with `[auth.encryption] +key_file` set: the data encryption key wrapped under the key-encryption key, the +KEK's id and the state of an unfinished switch or rotation, as one JSON +document), `data_database_name`, and `data_connection_string`. ### 3.6 `admin_users` @@ -143,8 +147,14 @@ Unique index on `user_arn`. } ``` Index on `(account_id, user_name)`. `secret_key_encrypted` is AES-256-GCM -ciphertext of the secret access key using the `settings.encryption_key`; -`access_key_id` is bound as additional authenticated data. +ciphertext of the secret access key using the `settings.encryption_key`, with +`access_key_id` bound as additional authenticated data; under the data +encryption key of a key ring, the additional authenticated data binds the +catalog id, the collection, the access key ID, the account, the user name and +the expiry instead (the Security Model's Credential Storage section). The +`extenddb encryption-key` pass rewrites each document with one `update_one` on +its `_id` and no upsert, so a document that the TTL index deletes during the +pass stays deleted. ### 3.9 `iam_groups` ```json @@ -1069,7 +1079,8 @@ The backend implements every trait in `extenddb-storage`: - `AuthorizationStore` — user/group/role/permissions-boundary/session policy lookup for IAM evaluation. - `MongoCredentialStore` — SigV4 credential resolution with - AES-GCM-decrypted secret keys. + AES-GCM-decrypted secret keys on a cache miss; the credential cache keeps the + derived signing key and wipes the secret. **Background workers** — spawned from `MongoRuntimeHooks::spawn_workers`: - `ttl_cleanup_worker` — sweep expired items every 60 s, emit diff --git a/docs/manuals/02-design-guide.md b/docs/manuals/02-design-guide.md index af9394fe3..5e489365d 100755 --- a/docs/manuals/02-design-guide.md +++ b/docs/manuals/02-design-guide.md @@ -23,7 +23,7 @@ On PostgreSQL, the data database connection string is stored in the catalog's `s | `tables` | DynamoDB table metadata. Composite PK: `(account_id, table_name)`. Stores key schema, attribute definitions, billing mode, stream spec, status, ARN, and TTL config. | | `indexes` | GSI/LSI metadata. FK on `table_id` (UUID) with CASCADE delete. | | `tags` | Resource tags. PK: `(resource_arn, tag_key)`. | -| `settings` | Key-value store for catalog version, data DB URL, the AES-256-GCM key that encrypts access key secrets (`encryption_key`), and runtime settings. | +| `settings` | Key-value store for catalog version, data DB URL, the AES-256-GCM key that encrypts access key secrets (`encryption_key`, or with `[auth.encryption] key_file` the `encryption_key_ring` row holding that key wrapped under a key-encryption key kept in a file), and runtime settings. | | `schema_history` | Migration tracking. Records which SQL files have been applied. | | `admin_users` | Admin credentials (bcrypt-hashed passwords). | | `iam_users` | IAM users scoped to accounts. Optional console password. | @@ -106,9 +106,9 @@ extenddb uses SigV4 signature verification with a local IAM credential store. Th Full SigV4 signature verification: 1. Extract `Authorization` header components (credential, signed headers, signature) -2. Look up access key in the credential store (cached in memory, database on a miss; encryption key cached at startup) +2. Look up access key in the credential store (the signing key cached in locked memory, database on a miss; the key that decrypts secrets is loaded at startup) 3. Reconstruct the canonical request and string-to-sign -4. Derive the signing key: `HMAC-SHA256(HMAC-SHA256(HMAC-SHA256(HMAC-SHA256("AWS4" + secret, date), region), service), "aws4_request")` +4. Derive the signing key on a cache miss: `HMAC-SHA256(HMAC-SHA256(HMAC-SHA256(HMAC-SHA256("AWS4" + secret, date), region), service), "aws4_request")`, then wipe the secret and keep the signing key in the locked key store for that scope date; a cache hit reuses it 5. Compare computed signature with the provided signature (constant-time comparison) 6. Return `AuthIdentity::User` or `AuthIdentity::RoleSession` with account context @@ -126,9 +126,9 @@ Policy conditions support all IAM condition operators: `StringEquals`, `StringNo ### Credential Storage -Access key secrets are encrypted at rest using AES-256-GCM. The encryption key is generated during `extenddb init` and stored in the `settings` table under the key `encryption_key`. Each access key record stores the encrypted secret and a unique nonce. +Access key secrets are encrypted at rest using AES-256-GCM. By default the encryption key is generated during `extenddb init` and stored in the `settings` table under the key `encryption_key`, with the access key ID as the additional authenticated data (AAD). With `[auth.encryption] key_file` set, a key-encryption key (KEK) in that file wraps a data encryption key (DEK), the `settings` row `encryption_key_ring` holds the wrapped DEK, and each secret's AAD binds it to its row (catalog id, table, access key ID, account, principal, session name and expiry). Each access key record stores the encrypted secret and a unique nonce. The Security Model's Credential Storage section has both modes. -Credential lookups (access key ID → decrypted secret) go through each server's in-memory credential cache; a miss reads the database. See Credential and Policy Caching in the Security Model. The server reads the encryption key that decrypts secrets once, at startup. extenddb never changes the key. A change made by hand in the `settings` table takes effect at the next restart. See Credential Storage in the Security Model, and Caching Design below. +Credential lookups (access key ID → SigV4 signing key) go through each server's in-memory credential cache; a miss reads the database, decrypts the secret, derives the signing key and wipes the secret. See Credential and Policy Caching in the Security Model. The server reads the key that decrypts secrets once, at startup, into the locked key store. `extenddb encryption-key` switches a deployment to a KEK file, changes the KEK and replaces the DEK (the admin guide's Encryption Key section); a change takes effect at the next restart. See Credential Storage in the Security Model, and Caching Design below. ## DynamoDB Streams Internals @@ -190,7 +190,7 @@ extenddb caches a small set of operational settings in memory to avoid per-reque | Setting | Mechanism | Refresh | Justification | |---------|-----------|---------|---------------| | `index_propagation_delay_ms` | `AtomicU64` | Background poller every 30s | Write-path hot path; briefly-stale value only affects GSI propagation timing | -| `encryption_key` | `Arc` loaded at startup | Never: read at startup, so a change made by hand takes a restart | Decryption key for access key secrets. extenddb generates it once and never changes it | +| `encryption_key` / `encryption_key_ring` | One slot of the locked key store, loaded at startup | Never: read at startup, so a change takes a restart | Key that decrypts access key secrets. `extenddb init` generates it; `extenddb encryption-key` replaces it, with every server stopped when stored secrets are rewritten | | `log_level` / `log_destination` | Tracing filter reload | Background poller every 30s | Observability tuning; stale value only delays log level changes | | `throttling_enabled` | `AtomicBool` | Background poller every 30s | Capacity management toggle; briefly-stale is safe | diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index f606c267e..267e1e9e2 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -255,6 +255,13 @@ The third line's tail names the record's state: `was FAILED ()` or `was |-----|---------|-------------| | `provider` | `builtin` | Auth provider: `builtin` (SigV4 + IAM). The server refuses to start with `"none"`. | +#### [auth.encryption] + +| Key | Default | Description | +|-----|---------|-------------| +| `key_file` | unset | Path of the key-encryption key (KEK) file. Unset, the server encrypts stored secrets with the catalog key in the `encryption_key` row, as `extenddb init` created it. Set, it unwraps the data encryption key (DEK) from the `encryption_key_ring` row with the KEK in this file. Set it only after `extenddb encryption-key switch --yes` has run; the [Encryption Key](#encryption-key) section gives the procedure, the file format and the ownership and mode the file must have. A leading `~` expands as in the TLS key path, and the path must then be absolute: `serve` changes its working directory to `/` when it detaches, so the configuration refuses a relative path. An in-memory SQLite catalog refuses it. | +| `require_locked_memory` | `true` | With `key_file` set, the server refuses to start when it cannot lock the memory that holds the DEK and the cached signing keys, and names the memlock limit it needs. `false` turns that refusal into a warning. Without `key_file` the server warns and starts in either case. | + #### [auth.cache] In-memory stale-while-revalidate caches eliminate the per-request catalog roundtrip for credentials, IAM policies, principal/resource tags, and table key info. Self-induced changes (admin API and console mutations) propagate instantly via write-through invalidation; off-instance changes take up to `ttl_seconds` to propagate. @@ -333,7 +340,7 @@ Managed via `extenddb settings set`. Changes take effect within 30 seconds witho ./target/release/extenddb settings --config extenddb.toml set log_level debug ``` -`list` and `get` mask secret values (`encryption_key`, and any key whose name +`list` and `get` mask secret values (`encryption_key`, `encryption_key_ring`, and any key whose name contains `connection_string`, `password`, `secret` or `token`) as `••••••••`, the same mask the management API and the console print. To print the stored value of a secret setting, pass `--show-secret` to `get`: @@ -343,7 +350,9 @@ value of a secret setting, pass `--show-secret` to `get`: ``` The value is written to standard output in full, so keep it out of shell -history, CI logs and pasted transcripts. +history, CI logs and pasted transcripts. `set` refuses `encryption_key` and +`encryption_key_ring`; the [Encryption Key](#encryption-key) commands are the +one way to change them. ## IAM Management @@ -939,6 +948,166 @@ deny `dynamodb:PutItem` on it instead. untag-user --account-id 123456789012 --user-name alice --tag-keys Department ``` +## Encryption Key + +extenddb encrypts only stored secrets: the secret of each access key and the secret of each AssumeRole session, and on PostgreSQL the `data_database_connection_string` row once a key ring exists. Table data is not encrypted. By default one AES-256-GCM key, the catalog key, encrypts them, and the catalog `settings` table holds that key in plaintext in the `encryption_key` row, so a copy of the catalog opens every stored secret. With `[auth.encryption] key_file` set, a key-encryption key (KEK) in a file on the server host wraps the data encryption key (DEK) that encrypts the stored secrets, and the catalog holds only the wrapped DEK, in the `encryption_key_ring` row. The [Security Model](10-security-model.md#attackers-and-what-each-gets) gives what each attacker gets in each mode. + +The `extenddb encryption-key` commands switch a deployment to a KEK file and manage its keys. Each takes `--config extenddb.toml`, previews by default and writes only with `--yes`. + +| Command | What it does | Servers | Rewrites stored secrets | +|---|---|---|---| +| `extenddb encryption-key status` | Prints the key source, the KEK id, the DEK ids and the count of stored secrets per key, and the access key ID, owner and creation time of each stored secret under a key other than the current one. It prints no secret | may run | no; it reads each secret and wipes the plaintext at once | +| `extenddb encryption-key switch --key-file ` | Switches from the catalog key to a KEK file | stopped | yes | +| `extenddb encryption-key rewrap --key-file ` | Wraps the same DEK under a new KEK, and rewrites the ring row only | may run | no | +| `extenddb encryption-key rotate` | Replaces the DEK | stopped | yes | +| `extenddb encryption-key reset --key-file --discard-secrets` | Recovers a restored catalog whose KEK is lost | stopped | deletes every stored secret | +| `extenddb encryption-key set-data-connection` | PostgreSQL only. Reads a connection string from standard input and writes the `data_database_connection_string` row encrypted under the DEK | may run | no | + +### The KEK file + +The file holds exactly 32 random bytes in standard base64 with padding, which is 44 characters, and at most one trailing newline. Nothing else is accepted: no comment, no blank line, no leading or trailing space. Create it under `umask 077`, and copy it to a place away from the host before any command writes the ring, because from that write on the ring opens only with it: + +```bash +umask 077 +head -c 32 /dev/urandom | base64 > /etc/extenddb/kek +``` + +The KEK must be new random bytes. A catalog copy taken before the switch holds the catalog key, and a KEK equal to it would open the ring of every later copy; `switch` refuses a KEK that equals the catalog key or a DEK of the ring. + +The file rule is the set of checks that the server and every command apply before they read the key. They refuse the file when one fails: + +1. The path is resolved to its canonical form, so a Kubernetes secret volume's symlink is checked at its target. +2. Every parent directory of the canonical path is owned by root or by the server's user, and none is writable by group or others unless its sticky bit is set. +3. The file is opened with `O_NOFOLLOW` and checked through the open descriptor, so no one can swap it between the check and the read. It is a regular file that root or the server's user owns, and others have no permission bits. +4. On Linux the file's POSIX access control list (ACL) is read before the group bits are judged. With an ACL mask entry, the group bits of the mode are the mask, and the owning group's permission is in its own ACL entry. Each named user entry must name the server's user, each named group entry its effective group, and the entry for others must grant nothing. Group access, through the mode's group bits without an ACL, the owning group's ACL entry, or a named group entry, is accepted only on a file that root owns, and only for the server's effective group. On macOS the rule checks owner and mode only, and the startup log says so. + +The two delivery routes that give the file a root owner pass: the systemd tmpfs case (root owner, an ACL entry for the service user, mode shown as 0440) and the Kubernetes `fsGroup` case (root owner, group 10001, mode 0440, for a server whose effective group is 10001). A file that the server's user owns needs no group access, and the rule refuses one that has it. The rule cannot see who belongs to a group, so the server's effective group must have no other members: every member can read a file that the rule accepts through that group. The rule refuses a file that any other user can read, where the TLS key check narrows the mode and warns: a user who could read the file may already hold the KEK. + +The server reads the file once at startup into memory it wipes afterwards, unwraps the DEK into the locked key store and drops the KEK. The file is unchanged. `rewrap` reads the file again when it runs. On SQLite the server warns at startup when the KEK file and the database file are on the same file system, because one snapshot then holds both. + +### Delivering the KEK file + +Any tool that gives a service a file at start can deliver the KEK, with no extenddb code. The server runs as the user `extenddb` in the [systemd unit](11-deployment-guide.md#systemd-service) and as uid 10001 in the container image, so each route gives that user the file with an owner and a mode that the file rule accepts. + +systemd is the recommended route for the systemd deployment of the deployment guide, on a host with systemd 250 or later and a TPM 2.0 chip. Write the KEK to a file, keep a copy away from the host, and seal the file to the TPM. `LoadCredentialEncrypted=` decrypts it at each start of the unit into `/run/credentials//`, which systemd unmounts when the unit stops, so a copy of the host disk holds no KEK that opens without that TPM. Root on the running host can still decrypt it. + +```bash +systemd-creds encrypt --with-key=tpm2 --name=extenddb-kek /etc/extenddb/kek /etc/credstore.encrypted/extenddb-kek +``` + +```ini +[Service] +LoadCredentialEncrypted=extenddb-kek:/etc/credstore.encrypted/extenddb-kek +Environment=EXTENDDB__AUTH__ENCRYPTION__KEY_FILE=%d/extenddb-kek +LimitMEMLOCK=16M +``` + +On a ramfs systemd gives the file to the unit's user at mode 0400. systemd 254 or later on Linux 6.4 or later uses a tmpfs, where root owns the file and a POSIX ACL entry lets the user read it, so the mode reads as 0440; the file rule accepts both. `LimitMEMLOCK=` is for the locked key store ([Memory locking](#memory-locking)). + +On Kubernetes, use a Secret volume with `defaultMode: 0400`, and `securityContext: {runAsUser: 10001, runAsGroup: 10001, fsGroup: 10001}` on the pod. kubelet then gives the file to root with group 10001 at mode 0440; without `fsGroup` the file belongs to group root and uid 10001 cannot open it. The file rule accepts the group bits only on a file that root owns and whose group is the server's effective group, so the server must run with group 10001: the image's `USER 10001:10001` gives it, and `runAsGroup: 10001` keeps it whatever the container runtime does. A process whose effective group is 0 and holds 10001 only as a supplementary group is refused. Every container in the pod gets the `fsGroup` as a supplementary group, so mount the Secret volume into the extenddb container alone. Secrets are unencrypted in etcd unless the cluster enables encryption at rest. Set the memlock limit through the container runtime. Point `EXTENDDB__AUTH__ENCRYPTION__KEY_FILE` at the mounted file. + +On Docker swarm, create the service with `--secret source=extenddb-kek,target=kek,uid=10001,gid=10001,mode=0400`. The default, root with mode 0444, fails the file rule. Swarm keeps every secret in the Raft log of its managers, and each manager keeps the key of that log unencrypted on its disk, so a copy of a manager's disk gives the KEK. If that copy must not give the KEK, enable `--autolock`; each manager restart then waits for an operator to type the unlock key, and after a manager's Docker restarts no service starts or restarts until an operator unlocks it. extenddb restarts do not wait while the managers are up. Compose file secrets are bind mounts that ignore `uid`, `gid` and `mode`, so uid 10001 must own the host file at mode 0400. + +On Podman, use `--secret extenddb-kek,type=mount,uid=10001,gid=10001,mode=0400`. The default, root with mode 0444, fails the file rule. + +With sops and age, sops keeps the encrypted KEK in configuration management, and `sops decrypt` in an `ExecStartPre=` writes the file under `umask 077`. Use this route only with an age identity on a hardware token, such as a YubiKey or a TPM through an age plugin: an age identity file on the same disk as the KEK protects no more than a plain KEK file. A PIN or touch policy on the token stops unattended restarts. + +The offline commands need the KEK too. They run only while every server is stopped, started by an operator, as the server's user, with the same delivery route as the server. On systemd that is a transient service with the same `LoadCredentialEncrypted=` line, started with `systemd-run --wait --pipe`; its credentials directory is `/run/credentials/.service/`. This example previews a switch, with every server stopped, as the `--yes` run after it: + +```bash +sudo systemd-run --wait --pipe --unit=extenddb-keys --uid=extenddb --gid=extenddb \ + -p LoadCredentialEncrypted=extenddb-kek:/etc/credstore.encrypted/extenddb-kek \ + /usr/local/bin/extenddb encryption-key switch --config /etc/extenddb/extenddb.toml \ + --key-file /run/credentials/extenddb-keys.service/extenddb-kek +``` + +`rotate`, `rewrap`, `set-data-connection` and `status` open the ring with the KEK that `key_file` names in the configuration. The transient unit does not inherit the `Environment=` line of the server's unit, so pass the path with `--setenv`: + +```bash +sudo systemd-run --wait --pipe --unit=extenddb-keys --uid=extenddb --gid=extenddb \ + -p LoadCredentialEncrypted=extenddb-kek:/etc/credstore.encrypted/extenddb-kek \ + --setenv=EXTENDDB__AUTH__ENCRYPTION__KEY_FILE=/run/credentials/extenddb-keys.service/extenddb-kek \ + /usr/local/bin/extenddb encryption-key rotate --config /etc/extenddb/extenddb.toml +``` + +`rewrap` needs the new KEK as well: a second `-p LoadCredentialEncrypted=extenddb-kek-2:/etc/credstore.encrypted/extenddb-kek-2` line delivers it, and `--key-file /run/credentials/extenddb-keys.service/extenddb-kek-2` names it. + +On Kubernetes it is a Job that mounts the same Secret while the Deployment has 0 replicas. On swarm it is a one-off service with the same secret, and on Podman a `podman run` with the same secret. `rewrap` and `set-data-connection` may run beside the running server, with the same route. + +None of these copies is a backup of the KEK. A TPM-sealed file opens only with that TPM, so it is lost with the host. Keep a copy of each KEK away from the host, made before the KEK is sealed or stored as a secret, for as long as a catalog copy wrapped under it is kept. Every route gives root on the running host the DEK, because the server holds it in memory. + +### Rules common to the commands + +- Each command reads the KEK file through the file rule, as the server's user, with the server's delivery route. +- Every command except `status` and `reset` checks the ring before it writes anything. A ring under another KEK is refused with both KEK ids printed. A ring in which any DEK fails to unwrap is refused; the message names `encryption-key status` and the [restore steps](14-backup-and-restore.md#restore-a-damaged-or-missing-key-ring) of the Backup and Restore manual. `status` reports such a ring: it prints its fields, marked as not authenticated, and which DEK ids fail to unwrap. +- Before its first write, `switch --yes` and `rotate --yes` open every `access_keys` and `iam_sessions` secret with the keys the run holds. If a secret opens under none of them, the run stops and writes nothing, and prints how many such secrets exist and their access key IDs. `--keep-unopenable` lets the run go on and leave those secrets as they are; they fail on every request today and fail the same way afterwards. On PostgreSQL the connection string row gets the same check, and `--keep-unopenable` does not apply to it. +- Without `--yes`, a command previews: it prints what `--yes` would do and writes nothing. The previews and `status` decrypt each stored secret only to find its key, wipe each plaintext at once, and print counts; for each secret under a key other than the target they print the access key ID, owner and creation time. They print no secret. +- The offline commands (`switch`, `rotate`, `reset`) open the catalog as `migrate --yes` does and take the migration lock, which waits for registered servers to stop. Their previews take the lock too, so stop every server before the preview. They take the `--lock-timeout` option of `migrate --yes`, wait up to that limit, and then exit 6. On Cassandra and MongoDB the lock is a lease that the command's stores check before each request. Behind PgBouncer, or for up to 30 s after a failover of the catalog's PostgreSQL server, a server can serve beside the holder of the lock, so stop every server first. +- No command takes a copy of the database, unlike `migrate --yes` on SQLite: a copy beside the database would hold the catalog key next to every secret. A run that stops at any step runs again with the same arguments, and the pass resumes. +- A command with nothing to do exits 0 and prints that the ring is already in the target state, with its KEK id and DEK id. A second `switch` with the current KEK file reports success, and so does a `rewrap` to the file the ring already names. +- Every command that writes prints a summary at the end: the KEK id, the DEK id, the counts per table, on PostgreSQL whether the `data_database_connection_string` row was rewritten, the access key IDs of the stored secrets that no key opens, and the `key_file` line for the configuration. No command prints a secret, the connection string or its password. The summary of `switch`, `rewrap` and `rotate` ends with this notice: "This does not revoke any credential. Each access key keeps its secret. A secret that leaked before this run works until its access key is re-created." The summary of `reset` ends with a line that says every access key and every session was deleted, and names the Backup and Restore manual's [lost KEK](14-backup-and-restore.md#the-kek-of-a-catalog-copy-is-lost) section. + +### `switch --key-file ` + +`switch` is the one-time change from the catalog key to a KEK file. The deployment runs with the catalog key before it and with `key_file` after it. + +1. Stop every server. The preview takes the migration lock, as the `--yes` run does, and waits for a running server until `--lock-timeout` passes. +2. Preview: `extenddb encryption-key switch --config extenddb.toml --key-file /etc/extenddb/kek`. +3. Run it with `--yes`, as the server's user. A run that has a switch to do refuses a configuration that sets `key_file`, so set `key_file` after the switch; a ring that is already finished under the given KEK is reported as nothing to do, and the run exits 0. It refuses a KEK equal to the catalog key or to a DEK of the ring, migrations that are not current, and a catalog without a `catalog_id` row. It checks every stored secret with the catalog key, writes the ring with a new DEK and the switch marked unfinished, rewrites every stored secret under the DEK (on PostgreSQL the connection string row too), deletes the `encryption_key` row, marks the switch finished and prints the summary. +4. Set `key_file` in `[auth.encryption]`, or `EXTENDDB__AUTH__ENCRYPTION__KEY_FILE`, and start the server. +5. Re-create the access keys that existed before the switch, to end the exposure of older catalog copies, which hold the catalog key. Sessions expire within 12 hours. + +A run that stopped resumes with the same arguments: the ring records the switch as unfinished and the id of the catalog key it started from, and the resumed run accepts only that catalog key. Until it finishes, the server refuses to start ([Troubleshooting](../troubleshooting.md#encryption-key-errors)). A new deployment that wants a KEK file runs `init`, then `switch --key-file --yes`, then `serve`; `init` creates no access key, so that deployment never has a stored secret under the catalog key. + +### `rewrap --key-file ` + +`rewrap` is the routine KEK change. It needs no outage and touches no stored secret: it opens the ring with the configured KEK, reads the new KEK from `--key-file`, writes the ring with the same DEK wrapped under the new KEK, and prints the summary with the `key_file` line for the new file. It refuses a ring whose switch is unfinished, a catalog that has a catalog key row, a ring with two DEKs (finish the switch or the rotation first), a new KEK that equals the DEK of the ring, and a ring that changed while it ran. It writes the ring only while the row still holds the ring that `rewrap` read: when a `rotate` wrote the ring in between, `rewrap` writes nothing and refuses with "the key ring changed while `extenddb encryption-key rewrap` ran, so nothing was written" ([Troubleshooting](../troubleshooting.md#the-key-ring-changed-while-rewrap-or-rotate-ran)). + +Running servers keep their DEK and read the ring only at startup. Until `key_file` names the new file, a restart refuses and prints both KEK ids, so change `key_file` right after the command. Whoever holds an old KEK and a catalog copy from before its rewrap still holds the DEK; only `rotate` ends that for a reader of catalog copies. + +### `rotate` + +`rotate` replaces the DEK. It rewrites every stored secret, so every server is stopped while it runs: stop every server, preview with `extenddb encryption-key rotate --config extenddb.toml`, run it with `--yes`, then start the server. The preview takes the migration lock as the `--yes` run does. It opens the ring with the configured KEK, refuses a ring whose switch is unfinished (finish the switch first) and a catalog key row (below), checks every stored secret with each DEK of the ring, adds a DEK with the next id, rewrites each stored secret under it, writes the ring with the new DEK alone, and prints the summary. It adds the DEK only while the row still holds the ring that `rotate` read: `rewrap` runs beside a server and outside the migration lock, and when a `rewrap` wrote the ring in between, `rotate` writes nothing and refuses with "the key ring changed while `extenddb encryption-key rotate` ran, so nothing was written". A run that stopped left two DEKs in the ring; the same command resumes it with the higher id as the target. A DEK replacement does not protect a secret whose ciphertext and key leaked together: re-create that access key. + +### A catalog key that appears after the switch + +After a finished switch the catalog has no `encryption_key` row. One can appear again from an older release run against the catalog, from an older SQLite dev image, which writes a new catalog key into a switched catalog at startup, or from a writer to the catalog database. The server refuses to start, says so and names `encryption-key status`, which lists each stored secret under that key with its access key ID, owner and creation time. `switch` and `rotate` refuse such a key unless the operator passes `--accept-catalog-key` after reading that list. With it, the run treats the catalog key as an old key, re-encrypts the listed secrets under the ring's DEK and deletes the row; `switch` then writes no new DEK. The older dev image is the documented reason to pass the option, and it runs with a configuration that does not set `key_file`. The option accepts the listed rows as written and checks nothing about them: a writer who inserted the key chose every field of those rows. + +### `reset --key-file --discard-secrets` + +`reset` recovers a restored catalog whose KEK is lost. Stop every server, preview, run it with `--yes`, then start the server; the preview takes the migration lock as the `--yes` run does. Every user, role, policy, group, account and table stays; every access key and every session goes. Without `--discard-secrets` the command refuses, so the preview and the flag both say what is lost. On PostgreSQL it reads the data database connection string on standard input, as `set-data-connection` does, because no key of the run opens the stored row. It deletes every `access_keys` and `iam_sessions` row and the `encryption_key` row if one exists, trying no key on them, writes the connection string row under a new DEK on PostgreSQL, writes a new ring with that DEK under the given KEK, and prints the summary with the deleted access key IDs. The old ring stays until that last write, so a run that stops earlier runs again with the same arguments and the same standard input. + +`reset` refuses a catalog with a catalog key row and no ring (without `key_file` that catalog uses the catalog key, and the message names `switch`), and a ring whose KEK id equals the given KEK's id while a DEK fails to unwrap: that ring has damage and its KEK is not lost, so restore a catalog copy instead. When every DEK unwraps under the given KEK, the KEK is not lost; `reset` writes nothing and exits 0. The Backup and Restore manual's [lost KEK](14-backup-and-restore.md#the-kek-of-a-catalog-copy-is-lost) section gives the steps around it. + +### `set-data-connection` + +`set-data-connection` runs on PostgreSQL only. The command takes a connection string on standard input, encrypts it under the DEK and writes the `data_database_connection_string` row. For a catalog with a ring it replaces the `psql UPDATE` of [Data Recovery](#data-recovery) after a restore to a server with another connection string; a catalog without a ring keeps its plaintext row and that `psql UPDATE`. It refuses a catalog without a ring, a ring whose switch is unfinished, a ring with two DEKs, and a string that does not parse as a PostgreSQL connection string. It may run beside a running server, which keeps its data pool until it restarts, so a wrong string shows at the next start; `extenddb verify` tests the stored string. The settings API keeps the row read-only. + +For standard input, here and for `reset`, the command reads it to the end, strips one trailing newline, refuses empty input and refuses a terminal, so it never waits with no prompt. A preview of `set-data-connection` reads no standard input; `reset` reads it in its preview too. To keep the password out of the shell history, write the string to a file under `umask 077`, run the command with the file as standard input, and delete the file after the run: + +```bash +umask 077 +printf '%s\n' 'postgresql://extenddb:@:/extenddb' > conn.txt +extenddb encryption-key set-data-connection --config extenddb.toml --yes < conn.txt +rm conn.txt +``` + +### What changes for an operator + +- Give the KEK file to `serve`, and on PostgreSQL to `migrate`, `catalog-check`, `verify` and the `backup` commands, which read the encrypted connection string row and need the KEK after the switch. +- Keep each old KEK while a catalog copy wrapped under it is kept. `rewrap` and `rotate` change no older copy, and a restore needs the KEK that the copy's ring names (the [Backup and Restore manual](14-backup-and-restore.md#recovering-from-catalog-loss)). +- After `init --overwrite`, put `[auth.encryption]` back; that command keeps only the storage settings. Delete `[auth.encryption]` and any `EXTENDDB__AUTH__ENCRYPTION__KEY_FILE` override before a rollback to a release without this setting (the [Upgrade Manual](07-upgrade-manual.md#the-switch-to-a-kek-file-rollback)). +- Keep catalog dumps under `umask 077`. A dump taken before the switch holds the catalog key. +- A switch or rotation that did not finish stops the server at its next start, with a message that names the command that resumes it. [Troubleshooting](../troubleshooting.md#encryption-key-errors) lists each message. The change adds no metric. + +### Memory locking + +The server keeps the key that opens stored secrets and the cached SigV4 signing keys in the locked key store: memory that stays out of swap and out of core dumps. On Linux it uses `memfd_secret` where the kernel offers it (enabled by default since Linux 6.5), and otherwise an anonymous mapping locked with `mlock` and marked `MADV_DONTDUMP` and `MADV_WIPEONFORK`. The startup log line names the protection in force: `memfd_secret`, locked pages, or none. The store's size follows `[auth.cache] max_entries`: two 32-byte slots per entry, so the default 10,000 entries need 640,000 bytes, plus one 32-byte buffer per runtime worker thread. + +The kernel's default memlock limit is 8 MiB on kernel 5.16 and later, and 64 KiB before. Hosts on an older kernel, for example RHEL 9 and Amazon Linux 2, need `LimitMEMLOCK=16M` in the unit, `--ulimit memlock=` in Docker, or a smaller `max_entries`. When locking fails under a configuration that sets `key_file`, startup refuses, names the limit it needs and both fixes; `[auth.encryption] require_locked_memory = false` turns the refusal into a warning. Without `key_file` the server warns and starts. + +Core dumps stay on: `MADV_DONTDUMP` keeps the core and excludes the key pages, so a crash can still be diagnosed. An operator who wants no core at all sets `LimitCORE=0` in the unit. On macOS the store uses `mlock` with no per-range core exclusion, and on Windows `VirtualLock`. + ## Web Console The management web console is served at `/console/` on the same port as the DynamoDB API. It requires `auth.provider = "builtin"`. @@ -1115,7 +1284,7 @@ Table backups (`CreateBackup`) hold one table's items and definition; they do no | MongoDB | `extenddb_catalog` and `extenddb_data`, fixed names | | Cassandra | The catalog keyspace `_catalog` and one keyspace per account, `_account_` (`keyspace_prefix` defaults to `extenddb`) | -On PostgreSQL the catalog and data databases are one copy: dump both with every server of the catalog stopped, or, to back up without stopping the server, take a base backup (`pg_basebackup`) of the PostgreSQL server that holds both. Each `pg_dump` takes its own snapshot of one database, so two dumps taken while a server runs disagree when a table is created or deleted between them. The catalog dump holds the encryption key and the application role's password (in the `data_database_connection_string` setting), so create both files readable by their owner alone, with `umask 077`. With the default names: +On PostgreSQL the catalog and data databases are one copy: dump both with every server of the catalog stopped, or, to back up without stopping the server, take a base backup (`pg_basebackup`) of the PostgreSQL server that holds both. Each `pg_dump` takes its own snapshot of one database, so two dumps taken while a server runs disagree when a table is created or deleted between them. Without `[auth.encryption] key_file`, the catalog dump holds the encryption key and the application role's password (in the `data_database_connection_string` setting); with a KEK file, it holds the wrapped data encryption key and that row encrypted, which open only with the KEK (the [Encryption Key](#encryption-key) section). In either case create both files readable by their owner alone, with `umask 077`. With the default names: ```bash # Backup, with the server stopped, with the pg_dump of the server's major version @@ -1140,7 +1309,7 @@ psql -v ON_ERROR_STOP=1 -f data_backup.sql extenddb psql -c 'DROP DATABASE extenddb_catalog_before_restore' -c 'DROP DATABASE extenddb_before_restore' postgres ``` -On a new PostgreSQL server (the old one lost with its databases) create the application role first: a dump holds no roles, and without it `createdb -O extenddb` fails, `role "extenddb" does not exist`. Give it the password that the catalog dump's `data_database_connection_string` row carries (`postgresql://extenddb:@:/extenddb`), the one the config file's `[storage.postgres] connection_string` names as well: `psql -c "CREATE USER extenddb WITH PASSWORD ''" postgres`. That row also records the data database's host and port, and the server connects to the data database there. On a server at another address, point the config file's `connection_string` at it and, after the restore and before the server starts, set the row: `psql -c "UPDATE settings SET value = 'postgresql://extenddb:@:/extenddb' WHERE key = 'data_database_connection_string'" extenddb_catalog`. Without that the server connects to the old address: it fails to start once nothing answers there, and while the old server still answers, the tables created then keep their items in the old server's data database while the new catalog lists them. +On a new PostgreSQL server (the old one lost with its databases) create the application role first: a dump holds no roles, and without it `createdb -O extenddb` fails, `role "extenddb" does not exist`. Give it the password that the catalog dump's `data_database_connection_string` row carries (`postgresql://extenddb:@:/extenddb`), the one the config file's `[storage.postgres] connection_string` names as well: `psql -c "CREATE USER extenddb WITH PASSWORD ''" postgres`. In a catalog with a key ring that row is encrypted and the dump no longer gives the password; take it from the config file's `connection_string`, which names the same role. That row also records the data database's host and port, and the server connects to the data database there. On a server at another address, point the config file's `connection_string` at it and, after the restore and before the server starts, set the row. For a catalog without a key ring (no `[auth.encryption] key_file`): `psql -c "UPDATE settings SET value = 'postgresql://extenddb:@:/extenddb' WHERE key = 'data_database_connection_string'" extenddb_catalog`. For a catalog with a key ring, the row is encrypted under the data encryption key, so write it with `extenddb encryption-key set-data-connection`, which reads the new string on standard input and needs the KEK file on the new host (the [Encryption Key](#encryption-key) section). Without that the server connects to the old address: it fails to start once nothing answers there, and while the old server still answers, the tables created then keep their items in the old server's data database while the new catalog lists them. --- diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 94a6930ce..231492da0 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -84,6 +84,12 @@ Migration 6 adds the catalog index of backups kept in a backup store, turns each A rollback to the previous binary needs two things: the catalog restored from the pre-upgrade backup (the previous binary refuses a catalog carrying migration 6, exit status 4), and the `[backup]` section removed from the configuration file, which the previous binary refuses as an unknown field before it reaches the catalog (`unknown field 'backup'`). The pre-upgrade backup predates every backup this release wrote to the store, so a restored catalog has no `backup_index` row for them while the store keeps their bytes under its root; the previous binary serves neither (it does not read the store). After the upgrade is run again, `extenddb backup sync --adopt-store` gives them rows: the store's identity file names the pre-rollback catalog, so the re-upgraded catalog finds the store owned by another catalog until the command makes it the owner (on SQLite's default root the server instead logs a warning and leaves the store unconfigured, so `/health` has no `backup_store` component until then), and the command then adopts every backup under the root. On SQLite `backup sync`, with or without its options, takes the serve lock as `backup purge` does, so the server is stopped while it runs; on PostgreSQL, MongoDB and Cassandra it runs beside the servers under the maintenance claim. In-catalog backups taken after it are lost with the rows, as before. A backup that `migrate-legacy` carried into the store after the upgrade has its bytes under the root like any other backup this release wrote, and `backup sync --adopt-store` adopts it. +### The switch to a KEK file: rollback + +A deployment that moved its stored secrets under a key-encryption key (KEK) file with `extenddb encryption-key switch` (the admin guide's [Encryption Key](05-admin-guide.md#encryption-key) section) has no `encryption_key` row in its catalog: the switch deleted it, and the catalog holds the data encryption key wrapped under the KEK in the `encryption_key_ring` row instead. The change adds no catalog migration, and a deployment that keeps the catalog key needs no `migrate --yes` run for it. A previous binary started on a switched catalog refuses with `MissingEncryptionKey`. To run the previous binary again, restore a catalog copy taken before the switch, which holds the catalog key; every catalog write since that copy is lost, and on Cassandra this manual has no tested rollback. Also delete `[auth.encryption]` and any `EXTENDDB__AUTH__ENCRYPTION__KEY_FILE` override from the configuration: the previous binary refuses an unknown field in `[auth]`, as it refuses `[backup]` above. The locked key store and the signing-key cache change no stored byte, so they need no rollback step. + +A SQLite dev image of a previous release started on a switched catalog writes a new `encryption_key` row into it and serves with that key, so every request signed with a credential under the DEK fails with HTTP 500. A server of this release then refuses to start on that catalog, and `extenddb encryption-key switch --key-file --accept-catalog-key --yes`, run with a configuration that does not set `key_file`, re-encrypts the secrets under the DEK and deletes the row. + ## Writing a New Migration Writing a catalog migration is contributor work. The procedure, with a worked example and the tests to run on each backend, is in the [catalog migration section](../../CONTRIBUTING.md#adding-a-catalog-migration) of `CONTRIBUTING.md` in the repository root. `extenddb migrate --list` prints the migrations the binary carries, with each one's kind on its backend. @@ -108,7 +114,7 @@ pg_dump -h -U > catalog_backup_$d.sql \ && test -s catalog_backup_$d.sql && test -s data_backup_$d.sql && echo "both dumps written" ``` -The catalog dump holds the encryption key and the application role's password, so `umask 077` creates both files readable by their owner alone. +The catalog dump holds the encryption key and the application role's password, or, for a deployment on a KEK file, the wrapped data encryption key and the encrypted connection string row, so `umask 077` creates both files readable by their owner alone. `pg_dump` refuses to dump a server of a newer major version than itself ("aborting because of server version mismatch"), exits 1 and leaves its file empty; use the client of the server's version. Go on only when the command prints "both dumps written": `psql` restores an empty file without an error. diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index 9f017a2b4..b3569ef53 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -19,14 +19,29 @@ This document describes the security architecture of extenddb, including the thr 1. **Client ↔ extenddb**: Untrusted. All input is validated. SigV4 signatures are verified. IAM policies are evaluated. 2. **extenddb ↔ PostgreSQL**: Trusted network. The PostgreSQL connection string contains credentials. Use TLS for the PostgreSQL connection in production (`sslmode=require` in the connection string). 3. **Admin ↔ Management API/Console**: Authenticated via admin credentials or IAM user credentials. CSRF tokens protect the web console. -4. **Catalog database contents**: Credential-equivalent. The AES-256-GCM key that encrypts access key secrets lives in the catalog `settings` table alongside the ciphertext it protects, so read access to the catalog database yields every stored access key secret. On PostgreSQL the same table holds `data_database_connection_string`, the login for the data database; the console, the management API and the `settings` CLI mask it, but a reader of the catalog database gets it in full. Treat catalog read access, and any catalog backup, as equivalent to holding those credentials. See [Credential Storage](#credential-storage). -5. **Server host**: Credential-equivalent as well. `extenddb.toml` holds the catalog connection string, and a running server keeps the encryption key and recently used decrypted secrets in process memory, so read access to the config file, a core dump of the server, or a read of its memory yields the same credentials. +4. **Catalog database contents**: Credential-equivalent in the default configuration. Without `[auth.encryption] key_file`, the AES-256-GCM key that encrypts access key secrets (the catalog key) lives in the catalog `settings` table alongside the ciphertext it protects, so read access to the catalog database yields every stored access key secret. With `key_file` set, the catalog holds only the data encryption key (DEK) wrapped under a key-encryption key (KEK) kept in a file on the server host, so a reader of the catalog or of a catalog copy gets no stored secret unless they also hold the KEK, or the copy predates the switch to the KEK file. On PostgreSQL the same table holds `data_database_connection_string`, the login for the data database; the console, the management API and the `settings` CLI mask it, and without `key_file` a reader of the catalog database gets it in full. After the switch that row is encrypted under the DEK as well. Treat catalog read access, and any catalog backup taken without a KEK file, as equivalent to holding those credentials. See [Credential Storage](#credential-storage) and [Attackers and what each gets](#attackers-and-what-each-gets). +5. **Server host**: Credential-equivalent as well. `extenddb.toml` holds the catalog connection string. A running server keeps the key that opens stored secrets (the catalog key or the DEK) and one SigV4 signing key per access key and scope date in the locked key store, memory that stays out of swap and out of core dumps; it holds no plaintext secret outside the moment of a cache miss. Read access to the config file yields the catalog login. Root on the host can read the server's memory and therefore the DEK, under every delivery route of the KEK file. ### Out of Scope - **PostgreSQL security**: extenddb relies on PostgreSQL access controls and network security. Securing the PostgreSQL instance (firewall rules, TLS, authentication) is the operator's responsibility. - **Operating system security**: File permissions on `extenddb.toml`, TLS keys, and the PID file are the operator's responsibility. The server sets the modes of the export files and of the import and export directories it creates ([Import and Export Files](#import-and-export-files)). -- **Key management**: extenddb generates the credential encryption key locally and stores it unwrapped in the catalog database. It does not wrap the key with an external KMS or HSM, derive it from an operator passphrase, or rotate it. Deployments that require any of those must add protection below extenddb, for example an encrypted volume, a managed database with a customer-managed KMS key, or a PostgreSQL distribution that adds transparent data encryption. That protects the key at rest but not from a principal that can query the catalog. +- **Key management**: extenddb generates the credential encryption key locally. By default it stores that key unwrapped in the catalog database. With `[auth.encryption] key_file` set, it keeps the key-encryption key in a file outside the catalog, which any tool that delivers a secret to a service as a file can hold: systemd credentials sealed to a Trusted Platform Module (TPM), a Kubernetes Secret volume, a Docker swarm or Podman secret (the admin guide's [Encryption Key](05-admin-guide.md#encryption-key) section). extenddb does not use a network key service, and it has no hardware key source of its own in this release: root on the running host can read the KEK file through every delivery route and the DEK from the server's memory. Deployments that must keep the key from root need protection below extenddb, for example an encrypted volume or a managed database with a customer-managed KMS key. + +### Attackers and what each gets + +The table gives, for each attacker, what a deployment on the catalog key (the default) exposes and what one on a KEK file exposes. + +| Attacker | Catalog key (the default) | KEK file (`key_file` set) | +|---|---|---| +| A reader of a catalog copy | Every stored secret, because the copy holds the catalog key | No secret, unless the copy predates the switch to the KEK file (it holds the catalog key) or the reader also holds the KEK. A physical copy of PostgreSQL, MongoDB or Cassandra taken after the switch can still hold the deleted `encryption_key` row: a write-ahead log archive, an SSTable before compaction, an oplog entry. [Backups](#backup-and-recovery) says what to do about that | +| A reader of the server's memory (heap leak, core dump, swap) | The key that opens stored secrets, and the signing keys valid for one scope date, in locked pages that core dumps exclude. No plaintext secret outside the moment of a cache miss | The same, with the DEK as the key | +| Root on the running host | The catalog key and every secret | The DEK, under every delivery route | +| A catalog writer | Admin control, with no key (below) | The same | + +A catalog writer, anyone who can write rows into the catalog database without an ExtendDB server, is out of scope. With no key at all, a writer can replace an admin's or an IAM user's password hash and take that user's control, write any policy document or role trust policy, and deny service by deleting or replacing the key rows. Encryption cannot protect against any of these. Each stored secret written under a DEK is bound to its row through the additional authenticated data (AAD) of AES-GCM (the catalog id, the table, the access key ID, the account, the user or role name, the session name and the expiry), so a writer who holds no key cannot reassign a secret to another principal, extend a session, or carry a secret into another deployment. A catalog key row that a writer inserts after the switch stops the server and is never taken as an old key by the commands the server's messages name. + +Some plaintext stays in memory as today: the TLS private key inside rustls, the database passwords in the configuration and in the connection pools, and the console session tokens. The response of one CreateAccessKey or AssumeRole request holds a secret for the life of that request. The catalog keeps each session token in plaintext as the primary key of `iam_sessions`. ## Authentication @@ -59,21 +74,24 @@ Request bodies are parsed before authentication (the service does the same), so #### Credential Storage -- Secret keys encrypted with AES-256-GCM using a per-catalog encryption key -- Encryption key generated during `extenddb init` and stored unwrapped in the catalog `settings` table, under the key `encryption_key` -- The encryption key and the ciphertext it protects therefore share one trust domain: anyone who can read the catalog database can decrypt every stored access key secret. Restrict catalog database access to the extenddb service account, and protect catalog backups to the same standard as the credentials themselves. -- The management API and web console redact `encryption_key` from settings responses. The key is readable only with catalog database access: a database client, or `extenddb settings get encryption_key --show-secret` on a host that holds the catalog connection string. -- extenddb has no command to rotate the encryption key, and `extenddb settings set` refuses `encryption_key`. Replacing the key by hand in the catalog `settings` table makes every stored access key secret and session credential unreadable. The server reads the key at startup and keeps it in memory, so a rotation takes these steps in order: - 1. Replace the value of `encryption_key` in the catalog `settings` table with 32 random bytes in standard base64, for example the output of `openssl rand -base64 32`. On MongoDB the key is the `value` field of the `settings` document whose `_id` is `encryption_key`. The server checks only that the key is present. A value of any other form makes every signed request, CreateAccessKey call and AssumeRole call fail. +- Secret keys encrypted with AES-256-GCM. The key that encrypts them depends on `[auth.encryption] key_file`: + - Not set (the default): the catalog key, generated during `extenddb init` and stored unwrapped in the catalog `settings` table, under the key `encryption_key`. The additional authenticated data (AAD) of each secret is its access key ID. + - Set: the data encryption key (DEK), a 32-byte key that the catalog holds wrapped under the key-encryption key (KEK) in that file, in the `settings` row `encryption_key_ring`. The ring also records the KEK's id (an HMAC of the KEK, which identifies it without revealing it) and the state of an unfinished switch or rotation. The AAD of each secret binds it to its row (catalog id, table, access key ID, account, principal name, session name and expiry). The server reads the KEK file once at startup, unwraps the DEK into the locked key store and wipes the KEK from memory. +- Without a KEK file, the encryption key and the ciphertext it protects share one trust domain: anyone who can read the catalog database can decrypt every stored access key secret. Restrict catalog database access to the extenddb service account, and protect catalog backups to the same standard as the credentials themselves. With a KEK file, a catalog copy opens only with the KEK that its ring names. +- The management API and web console redact `encryption_key` and `encryption_key_ring` from settings responses. The key is readable only with catalog database access: a database client, or `extenddb settings get encryption_key --show-secret` on a host that holds the catalog connection string. `extenddb settings set` refuses both rows. +- The KEK file holds 32 random bytes in standard base64 with padding (44 characters), with at most one trailing newline. The server and every `extenddb encryption-key` command refuse a file that others can read, that is not owned by the server's user or root, or whose parent directories a user other than the owner can write to (the admin guide's [Encryption Key](05-admin-guide.md#encryption-key) section gives the rule in full and the delivery routes). +- `extenddb encryption-key` switches a deployment from the catalog key to a KEK file (`switch`), changes the KEK with no outage (`rewrap`), replaces the DEK (`rotate`), recovers a restored catalog whose KEK is lost (`reset`) and, on PostgreSQL, writes the encrypted connection string row (`set-data-connection`). `switch` and `rotate` rewrite every stored secret and run while every server is stopped. None of them revokes a credential: a secret that leaked before the run works until its access key is re-created. +- For a deployment that keeps the catalog key, the only key replacement is by hand, and it costs an outage. Replacing the key in the catalog `settings` table makes every stored access key secret and session credential unreadable. The server reads the key at startup and keeps it in memory, so a replacement takes these steps in order: + 1. Replace the value of `encryption_key` in the catalog `settings` table with 32 random bytes in standard base64, for example the output of `openssl rand -base64 32`. On MongoDB the key is the `value` field of the `settings` document whose `_id` is `encryption_key`. The server refuses to start, and each `extenddb backup` command refuses to run, when the value is not 32 bytes in standard base64. 2. Restart every server that serves the catalog. From the restart on, each request signed with an old access key or an unexpired session credential fails with `InternalServerError` (HTTP 500). Once step 3 deletes an old key, a request signed with it fails with `UnrecognizedClientException`. 3. Delete every access key and create a new one. For each client that uses AssumeRole session credentials, call AssumeRole again with `extenddb manage assume-role`. The web console and `extenddb manage` sign in with a password, so they still work for this step. 4. Give each client its new credentials: an access key ID and secret, or the new session's access key ID, secret and session token. Until then, each of its requests fails. - Console passwords hashed with bcrypt (cost factor 12) -- Credentials and the inputs to authorization are cached in each server's memory; see Credential and Policy Caching below +- Signing keys derived from the credentials are cached in each server's memory; see Credential and Policy Caching below #### Credential and Policy Caching -Each server keeps in-memory caches between the request path and the catalog database, so that a request does not read the catalog for every credential and policy lookup. The caches hold decrypted credentials (long-term access keys and AssumeRole session credentials), parsed user, group and role inline policies, permissions boundaries, principal tags, resource tags, role-session data, user and role creation times, and each table's key and index definitions. Authorization decisions themselves are not cached: policies are evaluated on every request. Item data is not cached. This section covers the credentials that sign API requests; web console logins are described under Web Console Security. +Each server keeps in-memory caches between the request path and the catalog database, so that a request does not read the catalog for every credential and policy lookup. The credential cache holds, for each access key, its principal fields, its session flag and expiry, the SHA-256 of its session token, and one SigV4 signing key per scope date in use (at most two, around midnight UTC), each in a slot of the locked key store. It holds no plaintext secret and no plaintext session token: a cache miss decrypts the stored secret, derives the signing key into its slot and wipes the secret, and the server compares a presented session token by its hash in constant time. The other caches hold parsed user, group and role inline policies, permissions boundaries, principal tags, resource tags, role-session data, user and role creation times, and each table's key and index definitions. Authorization decisions themselves are not cached: policies are evaluated on every request. Item data is not cached. This section covers the credentials that sign API requests; web console logins are described under Web Console Security. The caches are on by default and are configured under `[auth.cache]` in `extenddb.toml` (see the Admin Guide): @@ -83,7 +101,7 @@ The caches are on by default and are configured under `[auth.cache]` in `extendd | `ttl_seconds` | `60` | The oldest a cached entry can be when it is used. Must be greater than 0 | | `soft_ttl_seconds` | `30` | After this age an entry is still used, and a background read replaces it. Must not exceed `ttl_seconds` | | `negative_ttl_seconds` | `5` | How long an empty answer is cached: an unknown access key ID, a missing table, or a principal with no policies, boundary or tags. Must not exceed `ttl_seconds` | -| `max_entries` | `10000` | Entries per cache; beyond this, entries are evicted. Must be greater than 0 | +| `max_entries` | `10000` | Entries per cache; beyond this, entries are evicted. Must be greater than 0. Also sets the size of the locked key store: two 32-byte signing-key slots per entry (640,000 bytes for the default), plus one buffer per runtime worker thread | These settings, whether set in the file or through `EXTENDDB__AUTH__CACHE__*` environment variables, are read at startup; changing them takes a restart. A server whose settings break one of the limits above refuses to start. @@ -387,7 +405,7 @@ pg_dump extenddb_catalog > catalog_backup.sql pg_dump extenddb > data_backup.sql ``` -The encryption key is stored in the catalog database, so a catalog dump contains both the key and the encrypted access key secrets. A catalog backup is credential-equivalent: store it encrypted, restrict who can read it, and do not copy it to less-protected environments (for example a developer machine or a shared bucket) to reproduce an issue. +Without `[auth.encryption] key_file`, the encryption key is stored in the catalog database, so a catalog dump contains both the key and the encrypted access key secrets. A catalog backup is then credential-equivalent: store it encrypted, restrict who can read it, and do not copy it to less-protected environments (for example a developer machine or a shared bucket) to reproduce an issue. With a KEK file, a dump taken after the switch holds the wrapped DEK and opens only with the KEK that its ring names; keep each KEK for as long as a copy wrapped under it is kept, and keep a copy of the KEK away from the host. A dump taken before the switch still holds the catalog key, and a physical copy of a PostgreSQL, MongoDB or Cassandra catalog taken after it can hold the deleted `encryption_key` row until its pages are overwritten: re-create the access keys that existed before the switch to end that exposure. Sessions expire within 12 hours. --- diff --git a/docs/manuals/11-deployment-guide.md b/docs/manuals/11-deployment-guide.md index 01d38e345..d11e9a79f 100755 --- a/docs/manuals/11-deployment-guide.md +++ b/docs/manuals/11-deployment-guide.md @@ -143,7 +143,7 @@ There is no readiness endpoint yet, so do not expect a Kubernetes becomes unreachable. Until a readiness endpoint that probes the storage layer exists, treat backend failures as something clients retry through. -For Kubernetes, run `extenddb init` as an init container or a one-time Job, then deploy extenddb as a Deployment with the generated `extenddb.toml` mounted as a ConfigMap or Secret. +For Kubernetes, run `extenddb init` as an init container or a one-time Job, then deploy extenddb as a Deployment with the generated `extenddb.toml` mounted as a ConfigMap or Secret. A deployment that keeps its stored secrets under a key-encryption key (KEK) file (the admin guide's [Encryption Key](05-admin-guide.md#encryption-key) section) mounts the KEK as a Secret volume with `defaultMode: 0400`, runs the pod with `securityContext: {runAsUser: 10001, runAsGroup: 10001, fsGroup: 10001}`, and points `EXTENDDB__AUTH__ENCRYPTION__KEY_FILE` at the mounted file. kubelet gives the file to root with group 10001 at mode 0440, which the server accepts only when its effective group is 10001. The server cannot see who belongs to that group, and every member can read the file, so give group 10001 no other members. Without `fsGroup` the file belongs to group root and uid 10001 cannot open it. Secrets are unencrypted in etcd unless the cluster enables encryption at rest. The `extenddb encryption-key` commands that need every server stopped run as a Job that mounts the same Secret while the Deployment has 0 replicas. ### Air-Gapped @@ -152,6 +152,7 @@ ExtendDB requires no internet connectivity. All functionality is self-contained Requirements in the air-gapped environment: - A supported storage backend, reachable from the ExtendDB host - The `extenddb` binary (statically linked or with matching libc) +- The KEK file, when the deployment encrypts its stored secrets under one (`[auth.encryption] key_file`), delivered by one of the routes in the admin guide's [Encryption Key](05-admin-guide.md#encryption-key) section, with a copy kept away from the host; no key source depends on a network key service ## Configuring PostgreSQL @@ -211,6 +212,7 @@ extenddb init \ - [ ] Change the admin password from the auto-generated one - [ ] Create named accounts and IAM users with least-privilege policies - [ ] Leave credential import off unless you need it. The server refuses imports unless `allow_credential_import` is `true`. If you enabled it to import keys, turn it off again: `extenddb settings set allow_credential_import false` +- [ ] Encrypt stored secrets under a KEK file: `extenddb encryption-key switch --key-file --yes` with every server stopped, then set `[auth.encryption] key_file`, and keep a copy of the KEK away from the host (the admin guide's [Encryption Key](05-admin-guide.md#encryption-key) section) ### Transport @@ -268,6 +270,11 @@ User=extenddb Group=extenddb Restart=on-failure RestartSec=5 +# The locked key store that holds the encryption key and the cached signing +# keys needs about 640 KiB for the default [auth.cache] max_entries. Kernels +# before 5.16 default the memlock limit to 64 KiB (the admin guide's Memory +# locking section). +LimitMEMLOCK=16M # On a host that backs up tables of large items, one malloc arena keeps a # backup job's high-water mark at the pipeline's terms whatever the number of # large items it reads (the admin guide's [backup] max_concurrent_jobs row @@ -288,6 +295,21 @@ sudo systemctl enable extenddb sudo systemctl start extenddb ``` +To keep the stored secrets under a key-encryption key (KEK) file instead of the catalog key (the admin guide's [Encryption Key](05-admin-guide.md#encryption-key) section), on a host with systemd 250 or later and a TPM 2.0 chip, seal the KEK to the TPM and let systemd decrypt it at each start of the unit. Keep a copy of the KEK away from the host first: the sealed file opens only with that TPM and is lost with the host. + +```bash +systemd-creds encrypt --with-key=tpm2 --name=extenddb-kek kek /etc/credstore.encrypted/extenddb-kek +``` + +Then add two lines to the `[Service]` section above: + +```ini +LoadCredentialEncrypted=extenddb-kek:/etc/credstore.encrypted/extenddb-kek +Environment=EXTENDDB__AUTH__ENCRYPTION__KEY_FILE=%d/extenddb-kek +``` + +Run `extenddb encryption-key switch --key-file --yes` with the unit stopped, through the admin guide's [`systemd-run` example](05-admin-guide.md#delivering-the-kek-file), which runs it as `extenddb` with the credential and gives the path under `/run/credentials/extenddb-keys.service/`, and then start the unit. The plaintext `kek` written under `umask 077` is root's at mode 0600, so the server's user cannot open it, and `/run/credentials/extenddb.service/` does not exist while the unit is stopped. systemd decrypts the credential into `/run/credentials/extenddb.service/` and unmounts that directory when the unit stops. On a ramfs the `extenddb` user owns the file at mode 0400; systemd 254 or later on Linux 6.4 or later uses a tmpfs, where root owns the file and an ACL entry lets the user read it. The server accepts both. With `LimitMEMLOCK=` in the unit the locked key store fits on every kernel; without `key_file` a server that cannot lock its memory warns and starts, with it the server refuses unless `require_locked_memory = false` is set. + With this unit only the `extenddb` user and root can read export files: the server creates them with mode 0600, and the import and export roots and account directories it creates with mode 0700, which the daemon's umask (027) can only narrow; before v0.1.15 that umask gave the `extenddb` group read access (see [the v0.1.15 entry](07-upgrade-manual.md#v0115-export-files-are-created-0600-and-the-import-and-export-directories-the-server-creates-0700) of the upgrade manual). To give a group access to a root, for example to put import files into it, create the root before the first start with that group and the mode you want, since an existing directory keeps its mode; export files in it are still created 0600. Import files go under `/`. When one directory is both an import and an export root (the deprecated `import_export_root`, or the same path under `[import]` and `[export]`), the first export of an account creates that directory 0700, so also create each `/` beforehand with the group and mode you want, or use separate import and export roots. Keep each parent directory of a root writable by its owner only (root or `extenddb`): the server logs a warning at startup for a parent directory that group or others can write to without the sticky bit, since a user who can write to it could replace the root. ## Multi-Instance Considerations diff --git a/docs/manuals/14-backup-and-restore.md b/docs/manuals/14-backup-and-restore.md index b5024fbc8..4dc36cd8b 100644 --- a/docs/manuals/14-backup-and-restore.md +++ b/docs/manuals/14-backup-and-restore.md @@ -32,13 +32,16 @@ snapshot tooling. What a table backup is not: - It does not hold the catalog: accounts, IAM users, groups, roles, policies, access keys, runtime settings - and the encryption key live in the catalog database, which no table backup contains. Back the catalog up + and the encryption key rows live in the catalog database, which no table backup contains. Back the catalog up with the database's own tools (the admin guide's [Data Recovery](05-admin-guide.md#data-recovery) entry names the databases and gives the PostgreSQL commands), and keep that copy off the host as well. On PostgreSQL the catalog and data databases are one copy: dump both with the server stopped, or take a base - backup of the PostgreSQL server that holds both. A catalog backup holds the encryption key that decrypts the - access key secrets, and on PostgreSQL the application role's password: protect it as a secret, and create - the dump files with `umask 077`. + backup of the PostgreSQL server that holds both. Without `[auth.encryption] key_file`, a catalog backup + holds the encryption key that decrypts the access key secrets, and on PostgreSQL the application role's + password: protect it as a secret, and create the dump files with `umask 077`. With a KEK file, the backup + holds the data encryption key wrapped under the KEK and opens only with that KEK; [Recovering from catalog + loss](#recovering-from-catalog-loss) says which key a restore needs. Create the dump files with `umask 077` + in either case. - It is not scheduled. ExtendDB has no backup scheduler: run `CreateBackup` from cron or your scheduler. As a crontab line, where every `%` must be escaped because cron turns an unescaped `%` into a newline: @@ -493,13 +496,27 @@ sync`. ### The catalog is restored from a database backup +A catalog copy needs the key it was taken with. A copy taken while the deployment used the catalog key holds +that key in its `encryption_key` row and needs a configuration without `[auth.encryption] key_file`. A copy +taken after `extenddb encryption-key switch` holds the data encryption key (DEK) wrapped under a +key-encryption key (KEK), in its `encryption_key_ring` row, and needs the KEK whose id that ring names, on +the restoring host, with the same `[auth.encryption]` section; the server refuses a ring that names another +KEK and prints both ids. `rewrap` and `rotate` change no older copy, so keep each KEK for as long as a copy +wrapped under it is kept (the admin guide's [Encryption Key](05-admin-guide.md#encryption-key) section). A +physical copy of a PostgreSQL, MongoDB or Cassandra catalog taken after the switch (a write-ahead log +archive, an SSTable before compaction, an oplog entry) can still hold the deleted `encryption_key` row and +with it each secret that existed before the switch; re-create those access keys to end that exposure. If the +KEK of a copy is lost, see [The KEK of a catalog copy is lost](#the-kek-of-a-catalog-copy-is-lost). + Restore the catalog from its database backup (the admin guide's [Data Recovery](05-admin-guide.md#data-recovery) entry). On PostgreSQL the catalog and data databases are one copy: restore both, either from dumps taken together with the server stopped, into new, empty databases owned by the application role as the entry gives it (restoring over the existing databases restores nothing), or from one base backup of the PostgreSQL server that held both, with PostgreSQL's own procedure. On a new PostgreSQL server create the application role before the dumps' restore and, when the server's address changed, set the -data database's address in the restored catalog, as the entry's last paragraph says. On SQLite the database +data database's address in the restored catalog, as the entry's last paragraph says: with a `psql UPDATE` of +the `data_database_connection_string` row for a catalog without a key ring, and with `extenddb encryption-key +set-data-connection` for a catalog with one, whose row is encrypted. On SQLite the database file holds the catalog and the tables; restore it as the entry's SQLite row says. Either way every table returns to the copy's moment, and a table created after it is gone. The restored catalog has the same catalog id, so it still owns the store root, and its accounts and IAM are back. Then run, with the servers stopped on SQLite and beside them on the other backends: @@ -546,6 +563,53 @@ table while its old items stay in a table of the data database that nothing refe the copy is listed and answers `ResourceNotFoundException` until it is deleted again. Restore the pair instead. +### The KEK of a catalog copy is lost + +A catalog copy taken after the switch to a KEK file opens only with the KEK that its `encryption_key_ring` +row names. When that KEK is gone, the stored secrets of the copy are gone with it: every access key secret +and every session secret. Everything else in the catalog is readable, and `extenddb encryption-key reset` +makes the copy serve again without them. With every server stopped: + +1. Restore the copy as the section above says, and check it with `extenddb encryption-key status`, with + `key_file` unset for that run: with `key_file` naming the lost file, `status` stops at the file rule and + prints nothing about the ring. Without it, `status` prints the ring with its KEK id and marks it as not + authenticated, since no KEK of yours opens it. The server itself refuses to start on it and prints the + ring's KEK id beside the id of the configured KEK. +2. Create a new KEK file and keep a copy away from the host, then run the preview and read what it lists: + + ```bash + extenddb encryption-key reset --config extenddb.toml --key-file /etc/extenddb/kek-2 --discard-secrets + ``` + + On PostgreSQL the command reads the data database connection string on standard input, in the preview + too, because no key of the run opens the stored row: write the string to a file under `umask 077` and + run the command with `< conn.txt`, as the admin guide's [`set-data-connection`](05-admin-guide.md#set-data-connection) + paragraph shows. +3. Run it again with `--yes`. It deletes every `access_keys` and `iam_sessions` row and the `encryption_key` + row if one exists, writes the connection string row under a new DEK on PostgreSQL, writes a new ring with + that DEK under the new KEK, and prints the deleted access key IDs. Every user, role, policy, group, account + and table stays. A run that stops before the ring write leaves the old ring, and the same command with the + same standard input runs again from the start. +4. Set `key_file` to the new file and start the server. +5. Give the users their credentials back: create new access keys, or import the pairs the clients hold under + their old IDs with `import-access-key`, as step 2 of [The catalog is lost and + re-created](#the-catalog-is-lost-and-re-created) does, turning `allow_credential_import` on for the + imports and off again after them. Clients that use AssumeRole call it again. + +`reset` is for a lost KEK only. It refuses a ring whose KEK id equals the given KEK's id while a DEK fails to +unwrap: that ring has damage or a changed field, and its KEK is not lost. It also refuses a catalog key row +without a ring. A catalog with neither row lost its DEK with the ring, and `reset` treats it as a lost KEK. + +### Restore a damaged or missing key ring + +For a damaged ring, and for a catalog key row without a ring, restore a catalog copy taken before the change +and check it with `status`. A ring that says a switch or a DEK replacement did not finish, when no run of yours +stopped, is a ring row that a writer to the catalog database put back from an older copy: do not resume it, +because the resumed run would re-encrypt the rows that writer chose. Restore a catalog copy taken after your +last `encryption-key` run finished, and check it with `status`. When a run of yours did stop, resume it with +the same command; for a switch, unset `key_file` for the run. A ring under an older KEK, or whose DEK id is +lower than the one the last command printed, can be such a write-back as well; `status` prints both ids. + ### The catalog is lost and re-created When no catalog backup exists, `extenddb init` creates a new catalog with a new catalog id. `init` refuses a @@ -558,7 +622,10 @@ values, so a `port`, `bind_addr`, TLS path, cache `ttl_seconds` or limit you set server listens on 18443; and `[backup]`, `[backup.store]`, `[import]`, `[export]` and every other section you added are dropped. Copy the file aside before running `init`, and before the new server starts put the copy back whole, taking only the regenerated -storage settings from the new file. Without `[backup.store]` a PostgreSQL, MongoDB or Cassandra server has +storage settings from the new file. A re-created catalog holds a new catalog key and no key ring, so leave +`[auth.encryption]` out of the copy you put back until `extenddb encryption-key switch --yes` has run on the +new catalog (the admin guide's [Encryption Key](05-admin-guide.md#encryption-key) section); with `key_file` +set, the server refuses a catalog that has the catalog key and no ring. Without `[backup.store]` a PostgreSQL, MongoDB or Cassandra server has no store (`/health` shows no `backup_store` component, `CreateBackup` writes in-catalog backups, and `backup sync --adopt-store` exits 1, "no backup store is configured"), and a SQLite server uses the default root beside the database; when the store was configured elsewhere, that root is a new, empty directory, and `--adopt-store` diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index ec69d055c..4549d6777 100755 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -40,11 +40,13 @@ connection_string = "postgresql://extenddb:***@/var/run/postgresql:5432/extenddb connection_string = "postgresql://extenddb:***@%2Fvar%2Frun%2Fpostgresql:5432/extenddb_catalog" ``` -Also update the catalog database: +Also update the catalog database. For a catalog without a key ring (no `[auth.encryption] key_file`): ```bash psql extenddb_catalog -c "UPDATE settings SET value='postgresql://extenddb:***@%2Fvar%2Frun%2Fpostgresql:5432/extenddb' WHERE key='data_database_connection_string';" ``` +For a catalog with a key ring the row is encrypted under the data encryption key, so write it with `extenddb encryption-key set-data-connection --config extenddb.toml --yes < conn.txt`, where `conn.txt` holds the corrected string and was written under `umask 077` (the admin guide's [Encryption Key](manuals/05-admin-guide.md#set-data-connection) section). The command needs the KEK file and may run beside the server, which reads the row at its next start. + **Prevention:** This issue is fixed in versions after 0.1, which automatically encode Unix socket paths correctly. ### `password authentication failed for user "extenddb"` @@ -234,6 +236,108 @@ journalctl -t extenddb -f **Fix:** No action needed. This confirms the runtime log level change took effect. +## Encryption Key Errors + +The server loads the key that opens stored secrets at startup from two catalog `settings` rows, `encryption_key` (the catalog key) and `encryption_key_ring` (the data encryption key, DEK, wrapped under the key-encryption key, KEK, in `[auth.encryption] key_file`), and refuses a catalog whose key state does not match its configuration. Each refusal below is one such state. The admin guide's [Encryption Key](manuals/05-admin-guide.md#encryption-key) section has the commands these fixes name; each previews by default and writes only with `--yes`. The message text of each refusal names the state and the command, and prints no key. + +### `Encryption key not found in settings table. Run 'extenddb init'` + +**Cause:** `key_file` is not set and the catalog has neither an `encryption_key` row nor an `encryption_key_ring` row. The catalog was created without `extenddb init`, or the row was deleted. + +**Fix:** For a new deployment, run `extenddb init`. For a catalog that had the row, restore a catalog copy that holds it: a new key opens none of the stored secrets. + +### `Encryption key in settings table is not valid: . Restore the original key: every stored access key and session secret is encrypted under it` + +**Cause:** The `encryption_key` row is not 32 bytes in standard base64. The server, and each `extenddb backup` command, refuse it, because a server started on it would fail every signed request with HTTP 500. + +**Fix:** Restore the original value of the row, from a catalog copy if needed. + +### `key_file` is not set and the catalog has a key ring marked as an unfinished switch + +**Cause:** `extenddb encryption-key switch --yes` started on this catalog and stopped before it finished. The ring records the switch as unfinished and the id of the catalog key it started from. + +**Fix:** If a switch of yours stopped, resume it with the same arguments, `extenddb encryption-key switch --config extenddb.toml --key-file --yes`, with every server stopped; the run checks the ring, accepts only the catalog key whose id the ring recorded, finishes the pass, then set `key_file` and start the server. If no switch of yours stopped, do not resume: a writer to the catalog database put that ring row back from an older copy. Restore a catalog copy taken after your last `encryption-key` run finished and check it with `encryption-key status` (the Backup and Restore manual's [Restore a damaged or missing key ring](manuals/14-backup-and-restore.md#restore-a-damaged-or-missing-key-ring) section). + +### `key_file` is not set and the catalog has a finished key ring + +**Cause:** The deployment switched to a KEK file, and this configuration does not name it. The message prints the KEK id the ring names. + +**Fix:** Set `[auth.encryption] key_file` (or `EXTENDDB__AUTH__ENCRYPTION__KEY_FILE`) to the file whose id the message prints, and start the server. + +### `key_file` is set and the file is missing, or fails the ownership, mode or ACL check + +**Cause:** The message names the path and the check that failed. The server and every `encryption-key` command refuse a KEK file that is not a regular file owned by root or the server's user, that others can read, that gives its group access while root does not own it or while its group is not the server's effective group (or whose ACL grants another user or group), or whose parent directories a user other than root or the owner can write to without the sticky bit. A file that passes those checks and does not hold a key is refused as `KEK file is not a KEK file: `; the reason names the length, or the offset of the character that does not decode, and leaves the character out. + +**Fix:** Check that the path is right for this host (a credential directory such as `/run/credentials//` exists only while the unit runs, so run the commands through the same delivery route as the server) and that the owner, mode, ACL and parent directories meet the rule in the admin guide's [The KEK file](manuals/05-admin-guide.md#the-kek-file) paragraph. On Kubernetes, `fsGroup: 10001` and `runAsGroup: 10001` give the file the server's group; on swarm and Podman, pass `uid=10001,gid=10001,mode=0400` with the secret. For the format refusal, restore the file from the copy kept away from the host; the file holds exactly 44 base64 characters and at most one trailing newline. + +### `key_file` is set and the catalog has the catalog key and no key ring + +**Cause:** In the documented order, `key_file` is set only after `switch --yes` has finished, so this state means a deleted ring or a configuration set too early. The message names `encryption-key status` and the restore steps, and no write command. + +**Fix:** If the switch has not run yet, unset `key_file`, run the switch with every server stopped, then set it. If the switch had run, the ring is gone: restore a catalog copy taken after the switch and check it with `encryption-key status`. + +### `key_file` is set and the catalog has neither key row + +**Cause:** The catalog has no `encryption_key` row and no `encryption_key_ring` row. The ring was deleted, or the catalog was never initialized. + +**Fix:** Restore a catalog copy that holds the ring and check it with `encryption-key status`. For a catalog that `extenddb init` never created, see the entry on an uninitialized catalog above. + +### The key ring names another KEK than the configured file + +**Cause:** The message prints both KEK ids. After `encryption-key rewrap --yes`, the ring names the new file while `key_file` still names the old one; otherwise the configured file is not the KEK that this ring was written under, for example after a restore of a catalog copy wrapped under an older KEK. When `key_file` names the KEK that your last `encryption-key` run wrote the ring under and you restored no catalog copy since that run, a writer to the catalog database put this ring row back from an older copy. + +**Fix:** After a rewrap, set `key_file` to the new file. For a ring row that a writer put back, restore a catalog copy taken after your last `encryption-key` run finished and check it with `encryption-key status` (the Backup and Restore manual's [Restore a damaged or missing key ring](manuals/14-backup-and-restore.md#restore-a-damaged-or-missing-key-ring) section). Otherwise find the KEK whose id the ring names and point `key_file` at it; if that KEK is lost, `encryption-key reset --key-file --discard-secrets` keeps every user, role, policy and table and deletes every access key and session (the Backup and Restore manual's [lost KEK](manuals/14-backup-and-restore.md#the-kek-of-a-catalog-copy-is-lost) section). + +### A DEK of the key ring fails to unwrap under the configured KEK + +**Cause:** The ring has damage or a changed field. The KEK authenticates every field of the ring, so a flipped flag, a changed id, an added or deleted DEK entry, or a wrapped DEK copied from another ring makes a DEK fail to unwrap. The message names `encryption-key status` and the restore steps, and no write command. `status` prints the ring's fields, marked as not authenticated, and which DEK ids fail. + +**Fix:** Restore a catalog copy taken before the change and check it with `encryption-key status`. `reset` refuses this ring, because its KEK is not lost. + +### `key_file` is set and the key ring is marked as an unfinished switch + +**Cause:** `key_file` was set while a stopped switch was unfinished, or a writer to the catalog database wrote the ring row of an unfinished switch back from a copy taken during the switch. The message names `encryption-key status` and the restore steps, and no write command. + +**Fix:** If a switch of yours stopped, unset `key_file` for the run, resume the switch with `encryption-key switch --key-file --yes` with every server stopped, then set `key_file` again. If no switch of yours stopped, restore a catalog copy taken after your last run finished and check it with `encryption-key status`; do not resume a switch you did not start, because the resumed run would re-encrypt rows the writer chose. + +### `key_file` is set and the catalog has both a key ring and a catalog key + +**Cause:** A catalog key row appeared after the switch finished. Its writer is an older release started on this catalog, an older SQLite dev image (which writes a new `encryption_key` row into a switched catalog at startup), or a writer to the catalog database. The message names `encryption-key status`, which lists each stored secret under that key with its access key ID, owner and creation time, and no write command. + +**Fix:** Run `extenddb encryption-key status --config extenddb.toml` and read the list. If the rows are yours (the older dev image case), run `encryption-key switch --key-file --accept-catalog-key --yes` with a configuration that does not set `key_file` and every server stopped; it re-encrypts the listed secrets under the DEK and deletes the row. If they are not yours, `--accept-catalog-key` would make a credential the writer chose valid: restore a catalog copy taken before the row appeared instead. + +### The key ring holds two DEKs + +**Cause:** `extenddb encryption-key rotate --yes` started on this catalog and stopped before it finished, so the ring holds the older DEK and the new one. + +**Fix:** Stop every server, then run `extenddb encryption-key rotate --config extenddb.toml` to preview, which takes the migration lock and lists the stored secrets still under the older DEK, then `rotate --yes`, which resumes the pass with the higher id as its target and writes the ring with that DEK alone. + +### The key ring changed while `rewrap` or `rotate` ran + +**Cause:** `rewrap` runs beside a server and outside the migration lock, so a `rotate` can write the ring between the read and the write of a `rewrap`, and a `rewrap` between the read and the first write of a `rotate`. Each of the two writes the ring only while the row still holds the ring it read. The message is "the key ring changed while `extenddb encryption-key ` ran, so nothing was written", and the run that printed it wrote nothing. + +**Fix:** Run the command again. A `rewrap` beside a `rotate` that is still running then refuses with the two-DEK refusal above until the `rotate` finishes. A `rotate` after a `rewrap` refuses with both KEK ids: set `key_file` to the file that the `rewrap` named, then run `rotate` again. + +The last ring write of `rotate` is conditional too, on the two-DEK ring of its first write. When another writer changed the ring after that write, `rotate` stops with "the key ring changed after `extenddb encryption-key rotate` wrote its two DEKs, so its last ring write did not happen" and names the DEK that the pass put the stored secrets under. Read the ring with `encryption-key status` before you run `rotate` again. + +### The rebuild of the database file failed after an encryption-key command + +**Cause:** On SQLite, `switch`, `rotate` and `reset` end with a rebuild of the catalog file (`VACUUM` under `secure_delete`), so no free page keeps a ciphertext the run replaced. The rebuild writes a new copy of the file, so it needs free disk space for that copy, and it ends with a checkpoint of the write-ahead log, which fails while another process has a transaction open on the database. The message is "`extenddb encryption-key ` wrote every row, and then the rebuild of the database file that erases the ciphertexts it replaced failed", followed by the database error. Every row of the run is written. + +**Fix:** Free disk space, or end every process that has the database file open (`fuser` or `lsof` on the file names them), then run the same command again with every server stopped. A `switch` or `reset` with nothing left to do rebuilds the file, and a `rotate` replaces the DEK again and then rebuilds the file. + +### The locked key store cannot be locked + +**Cause:** The server keeps the key that opens stored secrets and the cached signing keys in memory it locks out of swap and core dumps, sized by `[auth.cache] max_entries` (two 32-byte slots per entry, 640,000 bytes for the default, plus one buffer per runtime worker thread). The process's memlock limit is below that size: 64 KiB is the kernel default before Linux 5.16, and `mlock` of 1 MiB fails with `ENOMEM` under it. With `key_file` set the server refuses to start and names the memlock limit it needs; without `key_file` it logs a warning and starts with the keys in unlocked memory. + +**Fix:** Raise the limit: `LimitMEMLOCK=16M` in the systemd unit, `--ulimit memlock=` for a container, or a smaller `max_entries`. To start anyway with `key_file` set, `[auth.encryption] require_locked_memory = false` turns the refusal into a warning. The startup log line names the protection in force: `memfd_secret`, locked pages, or none. `serve` sets the key store up before it reads the catalog, so a refusal from the catalog (one of the entries above) can follow at the next start once the limit is raised. + +### A request fails with `InternalServerError` (HTTP 500) after a key change + +**Cause:** The stored secret of that access key opens under no key the server holds. `encryption-key status` lists such secrets by access key ID. A `switch --yes` or `rotate --yes` run with `--keep-unopenable` leaves them as they are; without the option the run stops before its first write and prints their access key IDs. + +**Fix:** Delete the access key and create a new one, or import the pair the client holds under its old ID with `import-access-key` (the Backup and Restore manual's [lost catalog](manuals/14-backup-and-restore.md#the-catalog-is-lost-and-re-created) section, step 2). + ## Stop Errors ### `No PID file found at ... Is extenddb running on port ...?` @@ -800,9 +904,9 @@ Keys imported earlier keep working while import is disabled. ### `Management API: encrypt session secret failed: ` -**Cause:** AES-256-GCM encryption of the temporary session secret key failed. This could indicate a corrupted or invalid encryption key in the settings table. +**Cause:** AES-256-GCM encryption of the temporary session secret key failed. The server checks the encryption key at startup and encrypts with the copy it loaded then, so the key in the `settings` table is not the cause. -**Fix:** Verify the `encryption_key` value in the `settings` table is a valid base64-encoded 32-byte key. If corrupted, re-run `extenddb init` to regenerate. +**Fix:** Open an issue with the error that follows the message in the server log. ### `Management API: store assume-role session failed: ` diff --git a/extenddb.sample.toml b/extenddb.sample.toml index 6296bc1c6..eafa3047d 100755 --- a/extenddb.sample.toml +++ b/extenddb.sample.toml @@ -14,6 +14,8 @@ # Environment variable overrides use the EXTENDDB__ prefix with __ as separator: # EXTENDDB__SERVER__PORT=9000 # EXTENDDB__STORAGE__POSTGRES__CONNECTION_STRING="postgresql://..." +# EXTENDDB__AUTH__ENCRYPTION__KEY_FILE=/etc/extenddb/kek +# EXTENDDB__AUTH__ENCRYPTION__REQUIRE_LOCKED_MEMORY=true # Path to the rendered documentation directory (HTML + PDF files). # Generated by `python3 docs/build-docs.py`. When set, the web console @@ -137,6 +139,12 @@ # become usable quickly. # max_entries = 10000 # Per-cache LRU cap. +# The release before this one refuses an [auth.encryption] table, even an +# empty one, so the header stays commented until key_file is set. +# [auth.encryption] +# key_file = "/etc/extenddb/kek" # set after `extenddb encryption-key switch --yes`; unset keeps the catalog key +# require_locked_memory = true # with key_file set, refuse to start when the key store cannot be locked + # Management web console is served at /console/ on the same port as the # DynamoDB API. No separate configuration needed — it uses the same bind # address and port as [server]. The console requires auth.provider = "builtin" diff --git a/fuzz/fuzz_targets/sigv4_verify.rs b/fuzz/fuzz_targets/sigv4_verify.rs index 613ef64ce..2e01006e8 100644 --- a/fuzz/fuzz_targets/sigv4_verify.rs +++ b/fuzz/fuzz_targets/sigv4_verify.rs @@ -3,11 +3,13 @@ // Mirrors BuiltinAuthProvider::authenticate in crates/auth/src/lib.rs. It reads // the Authorization header from the request headers as a string, parses it -// with sigv4::parse::parse_authorization, and calls -// sigv4::verify::verify_signature with "POST", "/", an empty query string, the -// request headers and the request body. Here a fixed secret key takes the -// place of the credential store lookup. The timestamp window check is left -// out because it depends on the clock; the sigv4_timestamp target covers it. +// with sigv4::parse::parse_authorization, derives the signing key for the +// scope the header names, and calls sigv4::verify::verify_signature with +// "POST", "/", an empty query string, the request headers and the request +// body. Here a fixed secret key and a derivation take the place of the +// credential cache, which holds the derived key and no plaintext secret. +// The timestamp window check is left out because it depends on the clock; +// the sigv4_timestamp target covers it. // // Input layout, with lines separated by '\n': // - The first line is the Authorization header value. The target also @@ -28,6 +30,7 @@ use libfuzzer_sys::fuzz_target; use extenddb_auth::sigv4::parse::parse_authorization; +use extenddb_auth::sigv4::signing_key::derive_signing_key; use extenddb_auth::sigv4::verify::verify_signature; // The AWS documentation example secret key. It is not a real credential; it @@ -44,5 +47,9 @@ fuzz_target!(|data: &[u8]| { let Ok(parsed) = parse_authorization(header) else { return; }; - let _ = verify_signature(&parsed, SECRET_KEY, "POST", "/", "", &headers, body); + // The cache derives one key per access key and scope date. The scope here + // is the header's own, so a header that names another date or region + // reaches the same comparison the server makes. + let signing_key = derive_signing_key(SECRET_KEY, &parsed.date, &parsed.region, &parsed.service); + let _ = verify_signature(&parsed, &signing_key, "POST", "/", "", &headers, body); }); diff --git a/tests/lifecycle_helpers.py b/tests/lifecycle_helpers.py index 74693f6ff..f2f55038a 100644 --- a/tests/lifecycle_helpers.py +++ b/tests/lifecycle_helpers.py @@ -134,10 +134,12 @@ def _init_args(cli_env): return args -def _run_extenddb(*args, config=None, timeout=30, check=True, env_override=None): +def _run_extenddb(*args, config=None, timeout=30, check=True, env_override=None, stdin=None): """Run a extenddb CLI command and return the CompletedProcess. - Never passes stdin — extenddb commands must be fully non-interactive. + Standard input is empty unless `stdin` is an open file, for a command that + reads one (`encryption-key set-data-connection`). extenddb commands must be + fully non-interactive. Use env_override to pass EXTENDDB_ADMIN_PASSWORD etc. """ cmd = [EXTENDDB_BINARY] @@ -154,7 +156,7 @@ def _run_extenddb(*args, config=None, timeout=30, check=True, env_override=None) text=True, timeout=timeout, check=check, - stdin=subprocess.DEVNULL, + stdin=subprocess.DEVNULL if stdin is None else stdin, env=env, ) diff --git a/tests/test_cli_encryption_key.py b/tests/test_cli_encryption_key.py new file mode 100644 index 000000000..29f8ef32b --- /dev/null +++ b/tests/test_cli_encryption_key.py @@ -0,0 +1,155 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""`extenddb encryption-key` through the CLI on a PostgreSQL catalog with a key ring. + +After `switch` the catalog's data_database_connection_string row is encrypted +under the ring's DEK. `status`, `rewrap` and `set-data-connection` open the +ring with the KEK that `[auth.encryption] key_file` names, and +`set-data-connection` replaces a row that does not open. `rewrap` and +`set-data-connection` refuse a catalog whose migrations are not current, as +`migrate` does. Like test_cli_lifecycle.py, this needs a PostgreSQL instance +(EXTENDDB_TEST_PG_CONNECTION_STRING) and a built binary, and is excluded from +the backend-agnostic pytest suite. +""" + +import base64 +import contextlib +import os +import types + +import psycopg2 +import pytest + +from lifecycle_helpers import PG_ADMIN_CONN, _init_args, _run_extenddb +from test_cli_vector_catalog_migration import _latest + +ROW = "data_database_connection_string" +AUTHENTICATED = "Authenticated under the configured KEK." +WRITTEN = f"The {ROW} row was written, encrypted under the DEK of the key ring." +HEALTHY = "=== HEALTHY: All checks passed ===" + + +@pytest.fixture() +def keyed(cli_env): + """A catalog after init and `switch --key-file`, with key_file naming the + KEK, and the helpers that run commands and read rows.""" + config = cli_env["config_path"] + + def run(*args, stdin=None): + return _run_extenddb(*args, config=config, check=False, stdin=stdin) + + def ok(result, line): + assert result.returncode == 0 and line in result.stdout, result.stdout + result.stderr + + def private(name, text): + # A new file that only its owner can read, as under `umask 077`. + path = os.path.join(os.path.dirname(config), name) + with open(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as f: + f.write(text) + return path + + def kek_file(name): + # 32 random bytes in standard base64 and one trailing newline, at an + # absolute path, which key_file requires. + return private(name, base64.b64encode(os.urandom(32)).decode() + "\n") + + def use_key_file(kek): + with open(config, "w") as f: + f.write(f'{generated}\n[auth.encryption]\nkey_file = "{kek}"\n') + + def setting(key): + with catalog.cursor() as cur: + cur.execute("SELECT value FROM settings WHERE key = %s", (key,)) + return cur.fetchone()[0] + + init = _run_extenddb( + "init", *_init_args(cli_env), config=config, check=False, + env_override={"EXTENDDB_ADMIN_PASSWORD": "TestPass1!"}, + ) + assert init.returncode == 0, init.stdout + init.stderr + with open(config) as f: + generated = f.read() + kek, kek2 = kek_file("kek"), kek_file("kek2") + with contextlib.closing(psycopg2.connect(PG_ADMIN_CONN + "/" + cli_env["db_name"])) as catalog: + catalog.autocommit = True + # The string init wrote, in plaintext until the switch. + data_connection = setting(ROW) + conn = private("conn.txt", data_connection + "\n") + + ok(run("encryption-key", "switch", "--key-file", kek, "--yes"), f"The {ROW} row was rewritten.") + use_key_file(kek) + yield types.SimpleNamespace( + run=run, ok=ok, use_key_file=use_key_file, setting=setting, catalog=catalog, + kek=kek, kek2=kek2, data_connection=data_connection, conn=conn, + ) + + +def test_status_rewrap_and_set_data_connection_run_with_the_configured_kek(keyed): + """init and switch, then status, rewrap and set-data-connection with the + KEK that key_file names, and set-data-connection on a row that does not + open.""" + run, ok, setting, kek2 = keyed.run, keyed.ok, keyed.setting, keyed.kek2 + + def set_data_connection(): + with open(keyed.conn) as stdin: + ok(run("encryption-key", "set-data-connection", "--yes", stdin=stdin), WRITTEN) + + ok(run("encryption-key", "status"), AUTHENTICATED) + + ring = setting("encryption_key_ring") + ok(run("encryption-key", "rewrap", "--key-file", kek2), "Nothing was written.") + assert setting("encryption_key_ring") == ring + ok( + run("encryption-key", "rewrap", "--key-file", kek2, "--yes"), + "=== extenddb encryption-key rewrap complete ===", + ) + keyed.use_key_file(kek2) + ok(run("encryption-key", "status"), AUTHENTICATED) + + set_data_connection() + ok(run("verify"), HEALTHY) + + # The plaintext row that a psql UPDATE writes does not open under the + # DEK. status still reports the ring, and set-data-connection replaces + # the row. + with keyed.catalog.cursor() as cur: + cur.execute("UPDATE settings SET value = %s WHERE key = %s", (keyed.data_connection, ROW)) + broken = run("verify") + assert broken.returncode == 1 and "does not open under the DEK" in broken.stdout, ( + broken.stdout + broken.stderr + ) + ok(run("encryption-key", "status"), AUTHENTICATED) + set_data_connection() + ok(run("verify"), HEALTHY) + + +# The commands that write beside a server, and the row each writes. +WRITES = [ + (("set-data-connection", "--yes"), ROW), + (("rewrap", "--key-file", "{kek2}", "--yes"), "encryption_key_ring"), +] + + +@pytest.mark.parametrize("args,row", WRITES) +def test_a_write_refuses_a_catalog_ahead_by_a_breaking_migration(keyed, args, row): + """With a breaking migration this binary does not know in the ledger, + the command exits 4 with the text that says to run `migrate` first, and + leaves its row as it was.""" + later = _latest() + 1 + with keyed.catalog.cursor() as cur: + cur.execute( + "INSERT INTO extenddb_migrations " + "(id, name, kind, checksum, outcome, applied_by) " + "VALUES (%s, 'later', 'breaking', 'x', 'applied', 'a later release')", + (later,), + ) + before = keyed.setting(row) + with open(keyed.conn) as stdin: + refused = keyed.run( + "encryption-key", *[a.format(kek2=keyed.kek2) for a in args], stdin=stdin + ) + assert refused.returncode == 4, refused.stdout + refused.stderr + assert f"{later} later" in refused.stderr, refused.stderr + assert "run `extenddb migrate` first" in refused.stderr, refused.stderr + assert keyed.setting(row) == before