Skip to content
3 changes: 2 additions & 1 deletion crates/storage-cassandra/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,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;

// ============================================================================
Expand Down Expand Up @@ -391,6 +391,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(
Expand Down
12 changes: 6 additions & 6 deletions crates/storage-mongodb/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,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 {
Expand Down Expand Up @@ -225,11 +225,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::<mongodb::bson::Document>("settings");
let enc_key = settings_coll
Expand All @@ -238,6 +237,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(
Expand Down
12 changes: 7 additions & 5 deletions crates/storage-postgres/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,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 {
Expand Down Expand Up @@ -961,10 +961,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<dyn extenddb_storage::CatalogStore>;
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<dyn extenddb_storage::CatalogStore>;

// Create auth provider
let enc_key = extenddb_storage::CatalogStore::cached_encryption_key(&*catalog_store)
Expand Down
8 changes: 6 additions & 2 deletions crates/storage-postgres/tests/backup_restore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
3 changes: 2 additions & 1 deletion crates/storage-sqlite/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,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;

Expand Down Expand Up @@ -432,6 +432,7 @@ async fn components_of(
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
Expand Down
37 changes: 36 additions & 1 deletion crates/storage-sqlite/src/migrations/serve_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -217,6 +218,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");
Expand Down
18 changes: 13 additions & 5 deletions crates/storage/src/secret_cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,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<RandomizedNonceKey, String> {
pub(crate) fn cipher_key(key_b64: &str) -> Result<RandomizedNonceKey, 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.
Expand Down Expand Up @@ -249,10 +249,18 @@ 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]
Expand Down
44 changes: 44 additions & 0 deletions crates/storage/src/server_components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),

Expand All @@ -75,6 +80,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}"),
}
Expand All @@ -83,6 +95,22 @@ 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::cipher_key(key_b64)
.map(|_| ())
.map_err(BackendError::InvalidEncryptionKey)
}

/// Options for server-component creation, beyond the storage config itself.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
Expand Down Expand Up @@ -269,4 +297,20 @@ mod tests {
);
assert!(warnings_for("us-east-1").await.is_empty());
}

#[test]
fn a_key_the_cipher_refuses_is_an_invalid_encryption_key() {
// 16 zero bytes.
assert_eq!(
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}");
}
}
12 changes: 8 additions & 4 deletions docs/adr/0026-credential-crypto-on-aws-lc.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/manuals/10-security-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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.
Expand Down
4 changes: 2 additions & 2 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -794,9 +794,9 @@ Keys imported earlier keep working while import is disabled.

### `Management API: encrypt session secret failed: <error>`

**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: <error>`

Expand Down
Loading