use crate::config::{StorageConfig, StorageEncryptionConfig};
use crate::errors::{AuthError, Result};
use crate::storage::encryption::{EncryptedStorage, StorageEncryption};
use crate::storage::{AuthStorage, MemoryStorage};
use std::sync::Arc;
pub(crate) async fn build_storage_backend_with_encryption(
config: &StorageConfig,
pool_size: Option<u32>,
encryption_config: &StorageEncryptionConfig,
) -> Result<Arc<dyn AuthStorage>> {
let backend = build_storage_backend_inner(config, pool_size).await?;
if matches!(config, StorageConfig::Memory) {
return Ok(backend);
}
if encryption_config.enabled
&& probe_is_cheap(config)
&& crate::storage::encryption::env_key_source_in_use()
{
match crate::storage::encryption::stored_envelopes_exist(backend.as_ref(), 100).await {
Ok(true) => tracing::warn!(
"Storage encryption uses the single AUTH_STORAGE_ENCRYPTION_KEY environment \
variable and encrypted values already exist: this key cannot rotate, and \
replacing it makes them undecryptable. Move to \
AUTH_STORAGE_ENCRYPTION_KEYS_FILE (current + old keys) before the first rotation."
),
Ok(false) => {}
Err(e) => tracing::debug!("could not probe storage for existing envelopes: {e}"),
}
}
wrap_with_encryption_if_enabled(backend, encryption_config)
}
fn probe_is_cheap(config: &StorageConfig) -> bool {
#[cfg(feature = "redis-storage")]
if matches!(config, StorageConfig::Redis { .. }) {
return false;
}
let _ = config;
true
}
pub(crate) fn check_overridden_storage(
storage: &Arc<dyn AuthStorage>,
encryption_config: &StorageEncryptionConfig,
) -> Result<()> {
if !encryption_config.enabled || storage.encrypts_kv_at_rest() {
return Ok(());
}
if encryption_config.require_wrapped_storage {
return Err(AuthError::configuration(
"storage_encryption.enabled is true and storage_encryption.require_wrapped_storage \
is set, but the storage supplied via new_with_storage / replace_storage / \
custom_storage is not an EncryptedStorage, so KV values would NOT be encrypted \
at rest. Wrap it with EncryptedStorage::new, or set \
storage_encryption.enabled = false to opt out explicitly.",
));
}
tracing::warn!(
"storage_encryption.enabled is true, but the storage supplied via new_with_storage / \
replace_storage / custom_storage is not an EncryptedStorage: KV values are NOT \
encrypted at rest. Wrap it with EncryptedStorage::new, set \
storage_encryption.enabled = false to opt out explicitly, or set \
storage_encryption.require_wrapped_storage = true to make this an error."
);
Ok(())
}
#[cfg(feature = "cli")]
pub(crate) async fn build_storage_backend_unencrypted(
config: &StorageConfig,
pool_size: Option<u32>,
) -> Result<Arc<dyn AuthStorage>> {
build_storage_backend_inner(config, pool_size).await
}
pub(crate) fn wrap_with_encryption_if_enabled(
backend: Arc<dyn AuthStorage>,
encryption_config: &StorageEncryptionConfig,
) -> Result<Arc<dyn AuthStorage>> {
if !encryption_config.enabled {
tracing::warn!(
"Storage encryption at rest is explicitly disabled (storage_encryption.enabled = false) -- \
KV-layer values (API keys, TOTP secrets, OAuth2 client registries, etc.) will be stored in plaintext."
);
return Ok(backend);
}
let encryption = StorageEncryption::from_env().map_err(|e| {
AuthError::configuration(format!(
"Storage encryption at rest is enabled (the default) but no encryption key could be \
loaded: {e}. Either configure AUTH_STORAGE_ENCRYPTION_KEY / \
AUTH_STORAGE_ENCRYPTION_KEYS_FILE, or set storage_encryption.enabled = false to \
explicitly opt out (not recommended for any backend that persists data)."
))
})?;
Ok(Arc::new(EncryptedStorage::new(
backend,
encryption,
encryption_config.allow_plaintext_reads,
encryption_config.allow_legacy_v0,
)))
}
async fn build_storage_backend_inner(
config: &StorageConfig,
_pool_size: Option<u32>,
) -> Result<Arc<dyn AuthStorage>> {
match config {
StorageConfig::Memory => Ok(Arc::new(MemoryStorage::new())),
#[cfg(feature = "redis-storage")]
StorageConfig::Redis { url, key_prefix } => {
crate::storage::RedisStorage::new(url, key_prefix)
.map(|storage| Arc::new(storage) as Arc<dyn AuthStorage>)
.map_err(|e| {
AuthError::configuration(format!("Failed to create Redis storage: {e}"))
})
}
#[cfg(feature = "postgres-storage")]
StorageConfig::Postgres {
connection_string,
table_prefix: _,
} => {
use sqlx::postgres::PgPoolOptions;
let pool = PgPoolOptions::new()
.max_connections(_pool_size.unwrap_or(10))
.connect(connection_string)
.await
.map_err(|e| {
AuthError::configuration(format!("Failed to connect PostgreSQL storage: {e}"))
})?;
let storage = crate::storage::postgres::PostgresStorage::new(pool);
storage.migrate().await.map_err(|e| {
AuthError::configuration(format!("Failed to initialize PostgreSQL storage: {e}"))
})?;
Ok(Arc::new(storage))
}
#[cfg(feature = "sqlite-storage")]
StorageConfig::Sqlite { connection_string } => {
use sqlx::sqlite::SqlitePoolOptions;
let pool = SqlitePoolOptions::new()
.max_connections(_pool_size.unwrap_or(10))
.connect(connection_string)
.await
.map_err(|e| {
AuthError::configuration(format!("Failed to connect SQLite storage: {e}"))
})?;
let storage = crate::storage::sqlite::SqliteStorage::new(pool);
storage.migrate().await.map_err(|e| {
AuthError::configuration(format!("Failed to initialize SQLite storage: {e}"))
})?;
Ok(Arc::new(storage))
}
StorageConfig::Custom(name) => Err(AuthError::configuration(format!(
"Custom storage backend '{name}' requires AuthFramework::new_with_storage() or replace_storage()",
))),
#[allow(unreachable_patterns)]
_ => Err(AuthError::configuration(
"Requested storage backend is unavailable in this build. Enable the matching storage feature.",
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::storage::MemoryStorage;
use crate::storage::encryption::{
EncryptionEnvGuard, StorageEncryption, TEST_ENCRYPTION_ENV_LOCK,
};
fn config(allow_plaintext_reads: bool, allow_legacy_v0: bool) -> StorageEncryptionConfig {
StorageEncryptionConfig {
enabled: true,
allow_plaintext_reads,
allow_legacy_v0,
..Default::default()
}
}
#[tokio::test]
async fn test_wrap_threads_allow_plaintext_reads_through() {
let _lock = TEST_ENCRYPTION_ENV_LOCK.lock().await;
let key = StorageEncryption::generate_key();
let _guard = EncryptionEnvGuard::set(&key);
let inner: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
inner
.store_kv("legacy:key", b"plaintext value", None)
.await
.unwrap();
let wrapped_strict =
wrap_with_encryption_if_enabled(inner.clone(), &config(false, false)).unwrap();
assert!(
wrapped_strict.get_kv("legacy:key").await.is_err(),
"allow_plaintext_reads: false must reject a non-envelope value"
);
let wrapped_permissive =
wrap_with_encryption_if_enabled(inner.clone(), &config(true, false)).unwrap();
assert_eq!(
wrapped_permissive.get_kv("legacy:key").await.unwrap(),
Some(b"plaintext value".to_vec()),
"allow_plaintext_reads: true must accept a non-envelope value"
);
}
#[tokio::test]
async fn test_wrap_threads_allow_legacy_v0_through() {
let _lock = TEST_ENCRYPTION_ENV_LOCK.lock().await;
let key_bytes_b64 = StorageEncryption::generate_key();
let _guard = EncryptionEnvGuard::set(&key_bytes_b64);
let encryption = StorageEncryption::from_env().unwrap();
let v1_envelope = encryption
.encrypt(b"legacy value", b"irrelevant-for-v0")
.unwrap();
let _ = v1_envelope; let v0_json = {
use aes_gcm::{Aes256Gcm, KeyInit, Nonce, aead::Aead};
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
let raw_key = BASE64.decode(&key_bytes_b64).unwrap();
let cipher = Aes256Gcm::new_from_slice(&raw_key).unwrap();
let nonce_bytes = [9u8; 12];
let nonce = Nonce::from_slice(&nonce_bytes);
let ciphertext = cipher.encrypt(nonce, b"legacy value".as_ref()).unwrap();
format!(
r#"{{"data":"{}","nonce":"{}","algorithm":"AES-256-GCM","key_derivation":"direct"}}"#,
BASE64.encode(&ciphertext),
BASE64.encode(nonce_bytes)
)
};
let inner: Arc<dyn AuthStorage> = Arc::new(MemoryStorage::new());
inner
.store_kv("legacy:v0:key", v0_json.as_bytes(), None)
.await
.unwrap();
let wrapped_strict =
wrap_with_encryption_if_enabled(inner.clone(), &config(false, false)).unwrap();
assert!(
wrapped_strict.get_kv("legacy:v0:key").await.is_err(),
"allow_legacy_v0: false must reject a format-version-0 envelope"
);
let wrapped_permissive =
wrap_with_encryption_if_enabled(inner.clone(), &config(false, true)).unwrap();
assert_eq!(
wrapped_permissive.get_kv("legacy:v0:key").await.unwrap(),
Some(b"legacy value".to_vec()),
"allow_legacy_v0: true must decrypt a format-version-0 envelope"
);
}
fn cfg_with(enabled: bool, require_wrapped_storage: bool) -> StorageEncryptionConfig {
StorageEncryptionConfig {
enabled,
require_wrapped_storage,
..Default::default()
}
}
fn wrapped() -> Arc<dyn AuthStorage> {
Arc::new(EncryptedStorage::new(
MemoryStorage::new(),
StorageEncryption::new_random(),
false,
false,
))
}
fn unwrapped() -> Arc<dyn AuthStorage> {
Arc::new(MemoryStorage::new())
}
#[test]
fn overridden_storage_check_matrix() {
assert!(check_overridden_storage(&wrapped(), &cfg_with(true, true)).is_ok());
assert!(check_overridden_storage(&unwrapped(), &cfg_with(true, false)).is_ok());
assert!(check_overridden_storage(&unwrapped(), &cfg_with(true, true)).is_err());
assert!(check_overridden_storage(&unwrapped(), &cfg_with(false, true)).is_ok());
}
}