From c2290b356b5175f127567326e7b0d427b263e752 Mon Sep 17 00:00:00 2001 From: Lee <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:13:09 +0000 Subject: [PATCH 1/6] fix(storage): refuse a damaged encryption key at startup Each backend refused to start when the catalog had no encryption key, but it started with a key that the secret cipher refuses: a key that is not base64, or that does not decode to 32 bytes. The credential store then failed to decrypt every stored secret, so each signed request got a 500 and the log named the key error. secret_cipher::check_key runs the decode and length check that encrypt_secret and decrypt_secret run. check_encryption_key in server_components maps its error to the new BackendError::InvalidEncryptionKey. The SQLite, PostgreSQL, MongoDB and Cassandra factories call it on the key they load, after the check for a missing key, so serve stops with the reason the cipher gives. A key with a trailing newline from a hand edit is not base64, and the check refuses it in the same way. The comment on the MongoDB key load read as if a key of the wrong length was refused at startup, when only a missing key was. It now describes both checks. Tests: check_key accepts and refuses the same keys as encrypt_secret, with the same error. A SQLite catalog with a 16-byte key, or with a 32-byte key and a trailing newline, refuses to start and names the reason. The same catalog starts again with a 32-byte key. With the SQLite call removed, that test fails because the server starts. --- crates/storage-cassandra/src/lib.rs | 3 +- crates/storage-mongodb/src/lib.rs | 12 ++--- crates/storage-postgres/src/lib.rs | 12 +++-- crates/storage-sqlite/src/lib.rs | 3 +- .../src/migrations/serve_tests.rs | 45 ++++++++++++++++- crates/storage/src/secret_cipher.rs | 50 +++++++++++++++++++ crates/storage/src/server_components.rs | 43 ++++++++++++++++ 7 files changed, 154 insertions(+), 14 deletions(-) diff --git a/crates/storage-cassandra/src/lib.rs b/crates/storage-cassandra/src/lib.rs index 3f0489402..a745263d6 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -53,7 +53,7 @@ pub use metadata_engine::TtlBackfillCursor; 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, check_encryption_key}; use std::sync::Arc; // ============================================================================ @@ -372,6 +372,7 @@ fn server_components_factory( let enc_key: String = enc_key_row.get_r_by_name("value").map_err(|e| { BackendError::InitializationFailed(format!("Failed to parse encryption key: {e}")) })?; + check_encryption_key(&enc_key)?; let catalog_store = Arc::new( CassandraCatalogStore::with_encryption_key( diff --git a/crates/storage-mongodb/src/lib.rs b/crates/storage-mongodb/src/lib.rs index 3580b5fb5..f6961134d 100644 --- a/crates/storage-mongodb/src/lib.rs +++ b/crates/storage-mongodb/src/lib.rs @@ -43,7 +43,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, check_encryption_key}; /// Backend-specific runtime hooks for `MongoDB`. struct MongoRuntimeHooks { @@ -199,11 +199,10 @@ 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. + // Load encryption key from settings collection. A missing key, or a key + // that is not base64 for 32 bytes, must be a hard failure: the secret + // cipher refuses such a key, so every credential lookup would fail with + // a 500. Refuse to start instead, as the other backends do. let catalog_db = catalog_client.database("extenddb_catalog"); let settings_coll = catalog_db.collection::("settings"); let enc_key = settings_coll @@ -212,6 +211,7 @@ async fn build_components( .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)?; + check_encryption_key(&enc_key)?; let auth_client = catalog_client.clone(); let catalog_store = Arc::new(MongoCatalogStore::with_encryption_key( diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 7d0f9d28c..bfabce9d3 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -652,7 +652,7 @@ impl PostgresEngine { use extenddb_auth::CredentialStore; use extenddb_storage::hooks::{ServerRuntimeHooks, ServingRegistrar, WorkerContext}; -use extenddb_storage::server_components::{BackendError, ServerComponents}; +use extenddb_storage::server_components::{BackendError, ServerComponents, check_encryption_key}; /// Backend-specific runtime hooks for `PostgreSQL`. struct PostgresRuntimeHooks { @@ -912,10 +912,12 @@ fn server_components_factory( )) })?; - 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; + let enc_key = enc_key.ok_or(BackendError::MissingEncryptionKey)?; + check_encryption_key(&enc_key)?; + let catalog_store = Arc::new(PostgresCatalogStore::with_encryption_key( + catalog_pool.clone(), + enc_key, + )) as Arc; // Create auth provider let enc_key = extenddb_storage::CatalogStore::cached_encryption_key(&*catalog_store) diff --git a/crates/storage-sqlite/src/lib.rs b/crates/storage-sqlite/src/lib.rs index 2e1401039..2808b9160 100644 --- a/crates/storage-sqlite/src/lib.rs +++ b/crates/storage-sqlite/src/lib.rs @@ -196,7 +196,7 @@ 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, ServerComponents, check_encryption_key}; use crate::hooks::SqliteRuntimeHooks; @@ -350,6 +350,7 @@ fn sqlite_server_components_factory( BackendError::InitializationFailed(format!("fetch encryption key: {e}")) })?; let enc_key = enc_key.ok_or(BackendError::MissingEncryptionKey)?; + check_encryption_key(&enc_key)?; // The catalog store writes through the second pool over the same // file, so its writers must hold the SAME lock instance as the diff --git a/crates/storage-sqlite/src/migrations/serve_tests.rs b/crates/storage-sqlite/src/migrations/serve_tests.rs index 5b432edcb..ce29c685b 100644 --- a/crates/storage-sqlite/src/migrations/serve_tests.rs +++ b/crates/storage-sqlite/src/migrations/serve_tests.rs @@ -6,7 +6,8 @@ //! 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; @@ -217,6 +218,48 @@ 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'"); + for (key, reason) in [ + // 16 bytes. + ( + "AAAAAAAAAAAAAAAAAAAAAA==", + "encryption key must be 32 bytes", + ), + // 32 bytes and a trailing newline. + ( + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n", + "decode encryption key: ", + ), + ] { + exec(&db, &set_key(key)).await; + match start(&location, false).await { + Err(BackendError::InvalidEncryptionKey(r)) => { + assert!(r.starts_with(reason), "{key:?}: {r}"); + } + Err(other) => panic!("{key:?}: refused for another reason: {other}"), + Ok(_) => panic!("{key:?}: 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"); diff --git a/crates/storage/src/secret_cipher.rs b/crates/storage/src/secret_cipher.rs index 453636630..21df1dceb 100644 --- a/crates/storage/src/secret_cipher.rs +++ b/crates/storage/src/secret_cipher.rs @@ -86,6 +86,20 @@ pub fn decrypt_secret(encrypted: &[u8], key_b64: &str, aad: &str) -> Result Result<(), String> { + cipher_key(key_b64).map(|_| ()) +} + /// Refuse an empty AAD. A ciphertext sealed with an empty AAD is the same as /// one sealed with none, so accepting it would reopen the path without the /// access key id binding. @@ -255,6 +269,42 @@ mod tests { assert!(err.starts_with("decode encryption key: "), "{err}"); } + /// `check_key` refuses a key exactly when `encrypt_secret` does, with the + /// same error. A trailing newline, from a key edited by hand, and a key + /// without its padding are not base64. + #[test] + fn check_key_agrees_with_the_cipher() { + let keys = [ + KEY_B64.to_owned(), + BASE64.encode([0x11; 16]), + BASE64.encode([0x11; 31]), + BASE64.encode([0x11; 33]), + String::new(), + format!("{KEY_B64}\n"), + KEY_B64.trim_end_matches('=').to_owned(), + "not base64!".to_owned(), + ]; + for key in &keys { + assert_eq!( + check_key(key), + encrypt_secret(PLAINTEXT, key, AAD).map(|_| ()), + "key {key:?}" + ); + } + assert_eq!(check_key(KEY_B64), Ok(())); + assert_eq!( + check_key(&BASE64.encode([0x11; 16])).unwrap_err(), + "encryption key must be 32 bytes" + ); + for key in [ + format!("{KEY_B64}\n"), + KEY_B64.trim_end_matches('=').to_owned(), + ] { + let err = check_key(&key).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"); diff --git a/crates/storage/src/server_components.rs b/crates/storage/src/server_components.rs index 427fec383..6ad7db434 100644 --- a/crates/storage/src/server_components.rs +++ b/crates/storage/src/server_components.rs @@ -51,6 +51,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 +80,12 @@ 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: {reason}. Restore the \ + original key: every stored access key and session secret is encrypted \ + under it" + ), Self::InitializationFailed(msg) => write!(f, "Backend initialization failed: {msg}"), Self::Catalog(e) => write!(f, "{e}"), } @@ -83,6 +94,20 @@ impl std::fmt::Display for BackendError { impl std::error::Error for BackendError {} +/// Refuse a catalog encryption key that the secret cipher would refuse. +/// +/// Each backend calls this on the key it loads at startup, beside its +/// [`BackendError::MissingEncryptionKey`] check. Without it a damaged key +/// starts a server that fails every signed request with a 500. +/// +/// # Errors +/// +/// Returns [`BackendError::InvalidEncryptionKey`] when `key_b64` is not +/// base64 or does not decode to 32 bytes. +pub fn check_encryption_key(key_b64: &str) -> Result<(), BackendError> { + crate::secret_cipher::check_key(key_b64).map_err(BackendError::InvalidEncryptionKey) +} + /// Options for server-component creation, beyond the storage config itself. #[derive(Debug, Clone, Copy)] #[non_exhaustive] @@ -239,4 +264,22 @@ mod tests { ); assert!(warnings_for("us-east-1").await.is_empty()); } + + #[test] + fn a_key_the_cipher_refuses_is_an_invalid_encryption_key() { + // 32 zero bytes, and 16 zero bytes. + assert!(check_encryption_key("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=").is_ok()); + let err = check_encryption_key("AAAAAAAAAAAAAAAAAAAAAA==").unwrap_err(); + assert!( + matches!(&err, BackendError::InvalidEncryptionKey(reason) + if reason == "encryption key must be 32 bytes"), + "{err:?}" + ); + assert_eq!( + err.to_string(), + "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" + ); + } } From 67506a804ab879efad0af08128d0150138f65cd7 Mon Sep 17 00:00:00 2001 From: Lee <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:13:09 +0000 Subject: [PATCH 2/6] docs(adr): say in ADR-0026 that the MongoDB driver uses ring ADR-0026 said that ExtendDB installs the rustls aws-lc-rs provider for its TLS server and clients, and that ExtendDB does not use ring as its TLS provider. The MongoDB driver does not use the installed provider. With its default rustls-tls feature, mongodb 3.8.0 builds its client configuration with rustls::crypto::ring, so the MongoDB backend's connections to MongoDB run on ring. This is why the MongoDB build links ring. The Context section now names that exception, and option 3 says what ring is linked for. The decision does not change. --- docs/adr/0026-credential-crypto-on-aws-lc.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/adr/0026-credential-crypto-on-aws-lc.md b/docs/adr/0026-credential-crypto-on-aws-lc.md index cf0f95fa5..55b2fe672 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 From 7f41d61c2e058ebc63e023548fdbd2dfeaab6887 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:29:43 +0000 Subject: [PATCH 3/6] test(postgres): write a valid encryption key in the beside-server test components_opened_beside_a_server_apply_no_pending_index_write came from main with the merge. It wrote 'test-key' as the encryption key. The startup check refuses a value that does not decode to 32 bytes, with "InvalidEncryptionKey: decode encryption key: Invalid symbol 45, offset 4". The test now writes a key from generate_encryption_key, as the Cassandra access key tests do. --- crates/storage-postgres/tests/backup_restore.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/storage-postgres/tests/backup_restore.rs b/crates/storage-postgres/tests/backup_restore.rs index fc53a8517..ec3a61a0b 100644 --- a/crates/storage-postgres/tests/backup_restore.rs +++ b/crates/storage-postgres/tests/backup_restore.rs @@ -5647,11 +5647,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"); From 84e02364135bf2cc8d1ea90abed3f9f58fc00207 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:02:21 +0000 Subject: [PATCH 4/6] docs(security): say that the server refuses an invalid key at startup Step 1 of the manual key rotation said that the server checks only that the key is present. It said that a value of any other form makes every signed request fail. check_encryption_key refuses such a value at startup. The step now says that the server refuses to start. --- docs/manuals/10-security-model.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index 6ba451346..5bd60ee97 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -64,7 +64,7 @@ Request bodies are parsed before authentication (the service does the same), so - 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. + 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 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. From 3176a01dd6e667029b7445d78af9141b255f1caf Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:30:41 +0000 Subject: [PATCH 5/6] fix(storage): drop the doubled period in the invalid-key error The base64 decoder ends its invalid-symbol text with a period, so the error read "offset 44.. Restore the original key". The message now trims the trailing period from the reason. check_encryption_key calls cipher_key, which encrypt_secret and decrypt_secret already call, in place of a one-line public wrapper. Four tests pinned the same 16-byte refusal. The cipher keeps its data table of refused keys, server_components keeps one check of the message, and the SQLite serve test keeps one refused key. --- .../src/migrations/serve_tests.rs | 30 ++++------ crates/storage/src/secret_cipher.rs | 56 +++---------------- crates/storage/src/server_components.rs | 25 +++++---- 3 files changed, 31 insertions(+), 80 deletions(-) diff --git a/crates/storage-sqlite/src/migrations/serve_tests.rs b/crates/storage-sqlite/src/migrations/serve_tests.rs index ce29c685b..d59c2270c 100644 --- a/crates/storage-sqlite/src/migrations/serve_tests.rs +++ b/crates/storage-sqlite/src/migrations/serve_tests.rs @@ -227,26 +227,18 @@ async fn a_server_refuses_an_encryption_key_the_cipher_refuses() { let location = current_catalog(&db).await; let set_key = |key: &str| format!("UPDATE settings SET value = '{key}' WHERE key = 'encryption_key'"); - for (key, reason) in [ - // 16 bytes. - ( - "AAAAAAAAAAAAAAAAAAAAAA==", - "encryption key must be 32 bytes", - ), - // 32 bytes and a trailing newline. - ( - "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n", - "decode encryption key: ", - ), - ] { - exec(&db, &set_key(key)).await; - match start(&location, false).await { - Err(BackendError::InvalidEncryptionKey(r)) => { - assert!(r.starts_with(reason), "{key:?}: {r}"); - } - Err(other) => panic!("{key:?}: refused for another reason: {other}"), - Ok(_) => panic!("{key:?}: the server started"), + // 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, diff --git a/crates/storage/src/secret_cipher.rs b/crates/storage/src/secret_cipher.rs index 21df1dceb..8f1bb0387 100644 --- a/crates/storage/src/secret_cipher.rs +++ b/crates/storage/src/secret_cipher.rs @@ -86,20 +86,6 @@ pub fn decrypt_secret(encrypted: &[u8], key_b64: &str, aad: &str) -> Result Result<(), String> { - cipher_key(key_b64).map(|_| ()) -} - /// Refuse an empty AAD. A ciphertext sealed with an empty AAD is the same as /// one sealed with none, so accepting it would reopen the path without the /// access key id binding. @@ -111,7 +97,7 @@ fn require_aad(aad: &str) -> Result<(), String> { } /// Decode the base64 encryption key and load it into an AES-256-GCM key. -fn cipher_key(key_b64: &str) -> Result { +pub(crate) fn cipher_key(key_b64: &str) -> Result { // 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. @@ -263,44 +249,16 @@ 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}"); - } - - /// `check_key` refuses a key exactly when `encrypt_secret` does, with the - /// same error. A trailing newline, from a key edited by hand, and a key - /// without its padding are not base64. - #[test] - fn check_key_agrees_with_the_cipher() { - let keys = [ - KEY_B64.to_owned(), - BASE64.encode([0x11; 16]), - BASE64.encode([0x11; 31]), - BASE64.encode([0x11; 33]), - String::new(), - format!("{KEY_B64}\n"), - KEY_B64.trim_end_matches('=').to_owned(), - "not base64!".to_owned(), - ]; - for key in &keys { - assert_eq!( - check_key(key), - encrypt_secret(PLAINTEXT, key, AAD).map(|_| ()), - "key {key:?}" - ); - } - assert_eq!(check_key(KEY_B64), Ok(())); - assert_eq!( - check_key(&BASE64.encode([0x11; 16])).unwrap_err(), - "encryption key must be 32 bytes" - ); + // 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 = check_key(&key).unwrap_err(); + 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}"); } } diff --git a/crates/storage/src/server_components.rs b/crates/storage/src/server_components.rs index c6715b65a..95b62f698 100644 --- a/crates/storage/src/server_components.rs +++ b/crates/storage/src/server_components.rs @@ -82,9 +82,10 @@ impl std::fmt::Display for BackendError { ), Self::InvalidEncryptionKey(reason) => write!( f, - "Encryption key in settings table is not valid: {reason}. Restore the \ + "Encryption key in settings table is not valid: {}. Restore the \ original key: every stored access key and session secret is encrypted \ - under it" + under it", + reason.trim_end_matches('.') ), Self::InitializationFailed(msg) => write!(f, "Backend initialization failed: {msg}"), Self::Catalog(e) => write!(f, "{e}"), @@ -105,7 +106,9 @@ impl std::error::Error for BackendError {} /// Returns [`BackendError::InvalidEncryptionKey`] when `key_b64` is not /// base64 or does not decode to 32 bytes. pub fn check_encryption_key(key_b64: &str) -> Result<(), BackendError> { - crate::secret_cipher::check_key(key_b64).map_err(BackendError::InvalidEncryptionKey) + crate::secret_cipher::cipher_key(key_b64) + .map(|_| ()) + .map_err(BackendError::InvalidEncryptionKey) } /// Options for server-component creation, beyond the storage config itself. @@ -297,19 +300,17 @@ mod tests { #[test] fn a_key_the_cipher_refuses_is_an_invalid_encryption_key() { - // 32 zero bytes, and 16 zero bytes. - assert!(check_encryption_key("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=").is_ok()); - let err = check_encryption_key("AAAAAAAAAAAAAAAAAAAAAA==").unwrap_err(); - assert!( - matches!(&err, BackendError::InvalidEncryptionKey(reason) - if reason == "encryption key must be 32 bytes"), - "{err:?}" - ); + // 16 zero bytes. assert_eq!( - err.to_string(), + check_encryption_key("AAAAAAAAAAAAAAAAAAAAAA==") + .unwrap_err() + .to_string(), "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 = check_encryption_key("AAAA-AAA").unwrap_err().to_string(); + assert!(err.contains("offset 4. Restore"), "{err}"); } } From d324fa5bdaf9acaf1aa9476c05c70944bb3c927d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:30:41 +0000 Subject: [PATCH 6/6] docs: say that the backup commands refuse an invalid key too Each extenddb backup command opens the catalog through the factory that checks the key, so it refuses an invalid key as the server does. Step 1 of the manual rotation in the security model now names both. The troubleshooting entry for a failed encryption of a session secret gave a damaged key as a cause. The server checks the key at startup and encrypts with the copy it loaded then. The entry now says that the key is not the cause. --- docs/manuals/10-security-model.md | 2 +- docs/troubleshooting.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index 5bd60ee97..af0e0b627 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -64,7 +64,7 @@ Request bodies are parsed before authentication (the service does the same), so - 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 refuses to start when the value is not 32 bytes in standard base64. + 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. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index dd9736143..805bc358a 100755 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -794,9 +794,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: `