diff --git a/crates/im-core/src/backup.rs b/crates/im-core/src/backup.rs index 8da0bb4..b0b0a7d 100644 --- a/crates/im-core/src/backup.rs +++ b/crates/im-core/src/backup.rs @@ -28,6 +28,7 @@ use turso::Builder; use crate::error::{Error, Result}; use crate::photo::is_photo_name; +use crate::secret; use crate::store::migrate::MIGRATIONS; use crate::store::{Store, col_int, col_text, db_err, fetch_all}; @@ -41,8 +42,8 @@ pub const DB_FILE: &str = "im.db"; pub const MANIFEST_FILE: &str = "manifest.json"; /// Name of the manifest's MAC inside a set: lower-case hex HMAC-SHA256 of the manifest bytes. pub const MAC_FILE: &str = "manifest.mac"; -/// What the manifest MAC key is derived for. The subkey is HMAC of this label under the instance key, the same -/// way recovery codes derive theirs, so the instance key itself keys only that derivation. +/// Label of the manifest MAC subkey. The subkey is `secret::derive` of this label under the instance key, the +/// same way recovery codes get theirs; the MAC itself is keyed with that subkey, never with the instance key. const MAC_SUBKEY_LABEL: &[u8] = b"im backup manifest v1"; /// Name of the photo directory inside a set, and beside the database in the data directory. pub const PHOTOS_DIR: &str = "photos"; @@ -85,11 +86,8 @@ pub struct RestoreOutcome { /// The HMAC over `bytes` under the manifest subkey of the instance key `key`. Its `verify_slice` is constant /// time, and its `finalize` gives the tag that is written to [`MAC_FILE`]. fn manifest_mac(key: &[u8; 32], bytes: &[u8]) -> HmacSha256 { + let subkey = secret::derive(key, MAC_SUBKEY_LABEL); // HMAC accepts a key of any length, so construction cannot fail. - let mut derive = - ::new_from_slice(key).expect("HMAC takes any key length"); - derive.update(MAC_SUBKEY_LABEL); - let subkey = derive.finalize().into_bytes(); let mut mac = ::new_from_slice(&subkey).expect("HMAC takes any key length"); mac.update(bytes); diff --git a/crates/im-core/src/secret.rs b/crates/im-core/src/secret.rs index ca94f7e..1506c2b 100644 --- a/crates/im-core/src/secret.rs +++ b/crates/im-core/src/secret.rs @@ -1,4 +1,8 @@ -//! The instance key and XChaCha20-Poly1305 sealing of secrets at rest. +//! The instance key, its derived subkeys, and XChaCha20-Poly1305 sealing of secrets at rest. +//! +//! The instance key never encrypts or MACs anything directly. Every use derives its own subkey from it +//! (see [`derive`]), and every sealed value is bound to a purpose (see [`purpose`]) that is checked as +//! associated data, so a value sealed for one purpose does not open as another. //! //! A sealed value is `v1:` followed by base64(nonce || ciphertext). The nonce is random for every //! seal, so sealing the same plaintext twice gives different text. The key never goes in the @@ -7,30 +11,77 @@ use std::path::Path; use base64::prelude::{BASE64_STANDARD, Engine as _}; -use chacha20poly1305::aead::Aead; +use chacha20poly1305::aead::{Aead, Payload}; use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; +use hmac::{Hmac, Mac}; +use sha2::Sha256; use crate::error::{Error, Result}; const PREFIX: &str = "v1:"; const NONCE_LEN: usize = 24; +/// Label of the subkey that seals values. The subkey is [`derive`] of this label. +const SEAL_LABEL: &[u8] = b"im seal v1"; + +/// What a sealed value is for. Passed as the associated data of [`seal`] and [`open`]: a value sealed +/// under one purpose fails authentication under any other. +pub mod purpose { + /// The sealed cookie that carries a password-verified sign-in until its second factor. + pub const PENDING_LOGIN: &str = "pending-login"; + /// The sealed cookie that carries a client secret to the page that shows it once. + pub const SECRET_FLASH: &str = "secret-flash"; + /// A TOTP shared secret, both the pending enrolment and the one kept after enabling. + pub const TOTP_SECRET: &str = "totp-secret"; + /// The 32-byte Ed25519 seed of a signing key. + pub const SIGNING_SEED: &str = "signing-seed"; + /// The body of an outgoing mail. + pub const MAIL_BODY: &str = "mail-body"; +} + +/// Derives a 32-byte subkey of the instance key `key` for `label`: HMAC-SHA256 of the label, keyed with +/// the instance key. Each use names its own label, so no two uses share key material. +pub(crate) fn derive(key: &[u8; 32], label: &[u8]) -> [u8; 32] { + // HMAC accepts a key of any length, so construction cannot fail. + let mut mac = + as hmac::KeyInit>::new_from_slice(key).expect("HMAC takes any key length"); + mac.update(label); + mac.finalize().into_bytes().into() +} + +/// The cipher keyed with the seal subkey of the instance key `key`. +fn cipher(key: &[u8; 32]) -> XChaCha20Poly1305 { + let subkey = derive(key, SEAL_LABEL); + XChaCha20Poly1305::new((&subkey).into()) +} /// Loads the 32-byte instance key at `path`, creating it if it is missing. /// -/// A new key is written with mode 0600 and `O_EXCL`, so two starts cannot both create it. An -/// existing key with any group or world permission is refused, because a leaked key defeats every -/// sealed secret. +/// A new key is written with mode 0600 and `O_EXCL`, so two starts cannot both create it, and the +/// directory is fsynced so the new entry survives a power cut. An existing key with any group or world +/// permission is refused, because a leaked key defeats every sealed secret. pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> { if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { std::fs::create_dir_all(parent)?; } match create_key(path) { - Ok(key) => Ok(key), + Ok(key) => { + sync_parent(path)?; + Ok(key) + } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => read_key(path), Err(e) => Err(e.into()), } } +/// Fsyncs the directory that holds `path`, so a file created in it is durable. +fn sync_parent(path: &Path) -> std::io::Result<()> { + let dir = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + std::fs::File::open(dir)?.sync_all() +} + fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { use std::io::Write; @@ -84,16 +135,21 @@ pub fn read_key(path: &Path) -> Result<[u8; 32]> { }) } -/// Seals `plaintext` under `key`. Output: `"v1:" + base64(nonce || ciphertext)`. +/// Seals `plaintext` under `key`, bound to `purpose`. Output: `"v1:" + base64(nonce || ciphertext)`. /// /// Errors if the cipher rejects the input. The caller must then refuse to store the value, never /// store it in clear. -pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result { +pub fn seal(key: &[u8; 32], purpose: &str, plaintext: &[u8]) -> Result { let mut nonce = [0u8; NONCE_LEN]; rand::fill(&mut nonce); - let cipher = XChaCha20Poly1305::new(key.into()); - let ciphertext = cipher - .encrypt(&XNonce::from(nonce), plaintext) + let ciphertext = cipher(key) + .encrypt( + &XNonce::from(nonce), + Payload { + msg: plaintext, + aad: purpose.as_bytes(), + }, + ) .map_err(|_| Error::Crypto("sealing failed".into()))?; let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len()); blob.extend_from_slice(&nonce); @@ -101,11 +157,11 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result { Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) } -/// Opens a value produced by [`seal`] under the same key. +/// Opens a value produced by [`seal`] under the same key and the same `purpose`. /// -/// Any failure (bad prefix, bad base64, short input, wrong key, tampering) is an error. The -/// messages are fixed strings, so nothing about the plaintext or the key can leak through them. -pub fn open(key: &[u8; 32], sealed: &str) -> Result> { +/// Any failure (bad prefix, bad base64, short input, wrong key, wrong purpose, tampering) is an error. +/// The messages are fixed strings, so nothing about the plaintext or the key can leak through them. +pub fn open(key: &[u8; 32], purpose: &str, sealed: &str) -> Result> { let encoded = sealed .strip_prefix(PREFIX) .ok_or_else(|| Error::Crypto("sealed value has no v1 prefix".into()))?; @@ -118,9 +174,14 @@ pub fn open(key: &[u8; 32], sealed: &str) -> Result> { let (nonce, ciphertext) = blob.split_at(NONCE_LEN); let nonce = <[u8; NONCE_LEN]>::try_from(nonce) .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?; - let cipher = XChaCha20Poly1305::new(key.into()); - cipher - .decrypt(&XNonce::from(nonce), ciphertext) + cipher(key) + .decrypt( + &XNonce::from(nonce), + Payload { + msg: ciphertext, + aad: purpose.as_bytes(), + }, + ) .map_err(|_| Error::Crypto("sealed value failed authentication".into())) } @@ -129,11 +190,15 @@ mod tests { use super::*; #[test] - fn seal_then_open_returns_the_plaintext_and_rejects_another_key() { + fn seal_then_open_returns_the_plaintext_and_rejects_another_key_or_purpose() { let key = [7u8; 32]; - let sealed = seal(&key, b"hello secret").unwrap(); + let sealed = seal(&key, purpose::SECRET_FLASH, b"hello secret").unwrap(); assert!(sealed.starts_with("v1:")); - assert_eq!(open(&key, &sealed).unwrap(), b"hello secret"); - assert!(open(&[8u8; 32], &sealed).is_err()); + assert_eq!( + open(&key, purpose::SECRET_FLASH, &sealed).unwrap(), + b"hello secret" + ); + assert!(open(&[8u8; 32], purpose::SECRET_FLASH, &sealed).is_err()); + assert!(open(&key, purpose::PENDING_LOGIN, &sealed).is_err()); } } diff --git a/crates/im-core/src/store/admin.rs b/crates/im-core/src/store/admin.rs index a248d99..d97cecf 100644 --- a/crates/im-core/src/store/admin.rs +++ b/crates/im-core/src/store/admin.rs @@ -443,14 +443,15 @@ impl Store { } /// Retires a published signing key that is not the current one. Its public key stays published for - /// the usual overlap, so tokens it signed still verify. The current key cannot be retired: the - /// statement excludes it, so a token can always be signed. + /// the usual overlap, so tokens it signed still verify. Its sealed seed is blanked in the same write, + /// because a retired key never signs again. The current key cannot be retired: the statement excludes + /// it, so a token can always be signed. pub async fn retire_signing_key(&self, kid: &str) -> Result { let now = now_stamp(); let conn = self.inner.conn.lock().await; let changed = conn .execute( - "UPDATE signing_keys SET retires_at = ?2 \ + "UPDATE signing_keys SET retires_at = ?2, private_sealed = '' \ WHERE kid = ?1 AND retires_at IS NULL AND activates_at <= ?2 \ AND kid <> (SELECT kid FROM signing_keys WHERE retires_at IS NULL AND activates_at <= ?2 \ ORDER BY activates_at DESC, kid DESC LIMIT 1)", diff --git a/crates/im-core/src/store/keys.rs b/crates/im-core/src/store/keys.rs index dc4a144..7e46af4 100644 --- a/crates/im-core/src/store/keys.rs +++ b/crates/im-core/src/store/keys.rs @@ -73,6 +73,19 @@ impl Store { finish(tx, outcome).await } + /// Blanks the sealed seed of every key that stopped signing at or before `now`. Verification needs only the + /// public key, so a retired key keeps nothing usable. Returns how many rows were blanked. + pub async fn scrub_retired_signing_seeds(&self, now: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE signing_keys SET private_sealed = '' \ + WHERE retires_at IS NOT NULL AND retires_at <= ?1 AND private_sealed <> ''", + (now.to_string(),), + ) + .await + .map_err(db_err) + } + /// Deletes keys retired at or before `cutoff`. Returns how many were removed. pub async fn prune_signing_keys(&self, cutoff: &str) -> Result { let conn = self.inner.conn.lock().await; diff --git a/crates/im-core/src/totp.rs b/crates/im-core/src/totp.rs index 31f7363..b4de798 100644 --- a/crates/im-core/src/totp.rs +++ b/crates/im-core/src/totp.rs @@ -11,6 +11,7 @@ use hmac::{Hmac, KeyInit, Mac}; use sha1::Sha1; use sha2::Sha256; +use crate::secret; use crate::token::{constant_time_eq, random_readable}; /// Shared secret length in bytes: 160 bits, the RFC 4226 recommendation. @@ -34,8 +35,7 @@ type HmacSha1 = Hmac; type HmacSha256 = Hmac; -/// What a recovery-code subkey is derived for. The subkey is HMAC of this label under the instance key, -/// so the instance key itself keys only that derivation. +/// Label of the recovery-code subkey. The subkey is `secret::derive` of this label under the instance key. const RECOVERY_SUBKEY_LABEL: &[u8] = b"im recovery code key v1"; /// A fresh random secret of [`SECRET_LEN`] bytes. @@ -161,11 +161,8 @@ pub fn recovery_code_hash(key: &[u8; 32], code: &str) -> String { .filter(|c| !c.is_whitespace() && *c != '-') .map(|c| c.to_ascii_lowercase()) .collect(); + let subkey = secret::derive(key, RECOVERY_SUBKEY_LABEL); // HMAC accepts a key of any length, so construction cannot fail. - let mut derive = - ::new_from_slice(key).expect("HMAC takes any key length"); - derive.update(RECOVERY_SUBKEY_LABEL); - let subkey = derive.finalize().into_bytes(); let mut mac = ::new_from_slice(&subkey).expect("HMAC takes any key length"); mac.update(normalized.as_bytes()); diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 6db3ecc..75d82ad 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -277,7 +277,7 @@ pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> let expires = unix_now() + PENDING_TTL.as_secs(); let nonce = generate_token(); let payload = format!("{user_id}|{expires}|{}|{nonce}|{next}", amr::PASSWORD); - let sealed = secret::seal(key, payload.as_bytes())?; + let sealed = secret::seal(key, secret::purpose::PENDING_LOGIN, payload.as_bytes())?; let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0)); jar(cx).add( Cookie::build((PENDING_COOKIE, sealed)) @@ -295,7 +295,7 @@ pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> /// `next` is the field as it was set; the caller applies [`safe_next`]. pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option { let cookie = jar(cx).get(PENDING_COOKIE)?; - let plain = secret::open(key, cookie.value()).ok()?; + let plain = secret::open(key, secret::purpose::PENDING_LOGIN, cookie.value()).ok()?; let text = String::from_utf8(plain).ok()?; // `next` comes last, so a `|` inside it cannot shift the other fields. let mut parts = text.splitn(5, '|'); @@ -333,7 +333,11 @@ pub const SECRET_FLASH_TTL: Duration = Duration::from_secs(2 * 60); /// sign-in: `__Host-`, Secure, HttpOnly, SameSite=Strict, Path=/. pub fn set_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str, secret: &str) -> Result<()> { let expires = unix_now() + SECRET_FLASH_TTL.as_secs(); - let sealed = secret::seal(key, format!("{client_id}|{expires}|{secret}").as_bytes())?; + let sealed = secret::seal( + key, + secret::purpose::SECRET_FLASH, + format!("{client_id}|{expires}|{secret}").as_bytes(), + )?; let max_age = time::Duration::seconds(i64::try_from(SECRET_FLASH_TTL.as_secs()).unwrap_or(0)); jar(cx).add( Cookie::build((SECRET_FLASH_COOKIE, sealed)) @@ -352,7 +356,7 @@ pub fn set_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str, secret: &str) pub fn take_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str) -> Option { let sealed = jar(cx).get(SECRET_FLASH_COOKIE)?.value().to_owned(); clear_secret_flash(cx); - let plain = secret::open(key, &sealed).ok()?; + let plain = secret::open(key, secret::purpose::SECRET_FLASH, &sealed).ok()?; let text = String::from_utf8(plain).ok()?; let mut parts = text.splitn(3, '|'); let id = parts.next()?; @@ -375,7 +379,7 @@ pub async fn verify_totp(store: &Store, key: &[u8; 32], user: &User, code: &str) if !user.totp_enabled() { return Ok(false); } - let shared = secret::open(key, sealed)?; + let shared = secret::open(key, secret::purpose::TOTP_SECRET, sealed)?; let last = user .totp_last_step .and_then(|step| u64::try_from(step).ok()); @@ -518,7 +522,12 @@ mod tests { .create_user("ada@example.com", "Ada", "hash", false) .await .expect("user"); - let sealed = secret::seal(&state.key, &totp::new_secret()).expect("seal"); + let sealed = secret::seal( + &state.key, + secret::purpose::TOTP_SECRET, + &totp::new_secret(), + ) + .expect("seal"); let code = totp::new_recovery_code(); state .store diff --git a/crates/im-web/src/cli.rs b/crates/im-web/src/cli.rs index 120afa1..bff485e 100644 --- a/crates/im-web/src/cli.rs +++ b/crates/im-web/src/cli.rs @@ -317,8 +317,16 @@ pub async fn fsck(config: &Path) -> ExitCode { .await .map_err(|e| e.to_string())? { - im_core::secret::open(&state.key, &key.private_sealed) - .map_err(|e| format!("signing key {} cannot be opened: {e}", key.kid))?; + // A retired key whose seed was blanked has nothing to open; its public key is all that is kept. + if key.retires_at.is_some() && key.private_sealed.is_empty() { + continue; + } + im_core::secret::open( + &state.key, + im_core::secret::purpose::SIGNING_SEED, + &key.private_sealed, + ) + .map_err(|e| format!("signing key {} cannot be opened: {e}", key.kid))?; } println!("im: database and signing keys ok"); Ok(()) diff --git a/crates/im-web/src/mail/mod.rs b/crates/im-web/src/mail/mod.rs index 710d8b8..5bbd272 100644 --- a/crates/im-web/src/mail/mod.rs +++ b/crates/im-web/src/mail/mod.rs @@ -139,7 +139,7 @@ pub async fn queue( "html": rendered.html, }) .to_string(); - let sealed = secret::seal(key, payload.as_bytes())?; + let sealed = secret::seal(key, secret::purpose::MAIL_BODY, payload.as_bytes())?; store .enqueue_mail(&NewMail { kind: mail.kind(), diff --git a/crates/im-web/src/mail/worker.rs b/crates/im-web/src/mail/worker.rs index 17441ba..ebdd8d8 100644 --- a/crates/im-web/src/mail/worker.rs +++ b/crates/im-web/src/mail/worker.rs @@ -180,7 +180,8 @@ fn open_message( if job.sealed_body.is_empty() { return Err("mail body is missing"); } - let plain = secret::open(key, &job.sealed_body).map_err(|_| "mail body cannot be opened")?; + let plain = secret::open(key, secret::purpose::MAIL_BODY, &job.sealed_body) + .map_err(|_| "mail body cannot be opened")?; let body: Body = serde_json::from_slice(&plain).map_err(|_| "mail body is not valid")?; let to = Recipient::new(body.to_name.as_deref(), &job.to_addr)?; build(sender, &to, &job.subject, body.text, body.html) diff --git a/crates/im-web/src/oidc/signing.rs b/crates/im-web/src/oidc/signing.rs index ec09a9a..1049eac 100644 --- a/crates/im-web/src/oidc/signing.rs +++ b/crates/im-web/src/oidc/signing.rs @@ -21,8 +21,8 @@ use tokio::sync::watch; const CHECK_EVERY: Duration = Duration::from_secs(24 * 60 * 60); /// Makes sure the chain is current: creates the first key when there is none, and creates the successor -/// when the newest key is due within the publish lead. Then removes keys retired more than [`OVERLAP`] -/// ago. Idempotent; safe to run at every boot. +/// when the newest key is due within the publish lead. Then blanks the seeds of keys that have stopped +/// signing, and removes keys retired more than [`OVERLAP`] ago. Idempotent; safe to run at every boot. pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<()> { let rows = store.signing_keys().await?; let now = now_stamp(); @@ -30,7 +30,7 @@ pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result let fresh = keys::generate(); let record = KeyRecord { kid: fresh.kid.clone(), - private_sealed: secret::seal(instance_key, &fresh.seed)?, + private_sealed: secret::seal(instance_key, secret::purpose::SIGNING_SEED, &fresh.seed)?, public_raw: fresh.public.to_vec(), created_at: now.clone(), activates_at: activates_at.clone(), @@ -39,6 +39,11 @@ pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result store.add_signing_key(&record).await?; tracing::info!(kid = %record.kid, activates_at = %activates_at, "signing key created"); } + // A key retired by a successor keeps its seed until its retirement time, because it signs until then. + let scrubbed = store.scrub_retired_signing_seeds(&now).await?; + if scrubbed > 0 { + tracing::info!(scrubbed, "seeds of retired signing keys blanked"); + } let cutoff = stamp_minus(&now, OVERLAP).unwrap_or_else(|| now.clone()); let pruned = store.prune_signing_keys(&cutoff).await?; if pruned > 0 { @@ -68,16 +73,28 @@ pub fn spawn( /// Makes a new key the signing key, one publish lead from now. It is published first and only then used: the /// JWKS carries it before the first token it signs, and the previous key keeps signing until then. Returns the -/// new key id. +/// new key id. Refused while another key is still waiting to activate: two pending keys would make the +/// retirement order ambiguous. pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result { let fresh = keys::generate(); let now = now_stamp(); + let pending = store + .signing_keys() + .await? + .iter() + .any(|key| key.retires_at.is_none() && key.activates_at > now); + if pending { + return Err(im_core::Error::Conflict( + "another signing key is still waiting to activate; rotate after it starts signing" + .into(), + )); + } let activates_at = stamp_plus(&now, keys::PUBLISH_LEAD).ok_or_else(|| { im_core::Error::Crypto("the new key's activation time is out of range".into()) })?; let record = KeyRecord { kid: fresh.kid.clone(), - private_sealed: secret::seal(instance_key, &fresh.seed)?, + private_sealed: secret::seal(instance_key, secret::purpose::SIGNING_SEED, &fresh.seed)?, public_raw: fresh.public.to_vec(), created_at: now, activates_at, @@ -136,7 +153,11 @@ pub async fn sign( /// Opens the sealed seed of a key row. fn seed_of(instance_key: &[u8; 32], record: &KeyRecord) -> im_core::Result<[u8; 32]> { - let bytes = secret::open(instance_key, &record.private_sealed)?; + let bytes = secret::open( + instance_key, + secret::purpose::SIGNING_SEED, + &record.private_sealed, + )?; <[u8; 32]>::try_from(bytes.as_slice()) .map_err(|_| im_core::Error::Crypto("signing key has the wrong length".into())) } diff --git a/crates/im-web/src/oidc/token.rs b/crates/im-web/src/oidc/token.rs index 0f7b47a..899167a 100644 --- a/crates/im-web/src/oidc/token.rs +++ b/crates/im-web/src/oidc/token.rs @@ -459,13 +459,17 @@ async fn id_token( nonce: Option<&str>, ) -> im_core::Result { let now = im_core::time::unix_now(); + // A stored stamp that does not parse is a server fault: it is never replaced by the current time. + let auth_time = unix_seconds(&session.auth_time).ok_or_else(|| { + im_core::Error::Database("the session's auth_time is not a stored stamp".into()) + })?; let mut claims = json!({ "iss": issuer(app), "sub": user.id, "aud": client.id, "iat": now, "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0), - "auth_time": unix_seconds(&session.auth_time).unwrap_or(now), + "auth_time": auth_time, "sid": session.id, "amr": amr::rfc8176(&session.amr), }); diff --git a/crates/im-web/src/pages/security.rs b/crates/im-web/src/pages/security.rs index f486850..7ba29bf 100644 --- a/crates/im-web/src/pages/security.rs +++ b/crates/im-web/src/pages/security.rs @@ -239,7 +239,7 @@ async fn start_enrolment(cx: &Cx, Form(form): Form) -> Result) -> Result Result { - let shared = secret::open(&state.key, sealed)?; + let shared = secret::open(&state.key, secret::purpose::TOTP_SECRET, sealed)?; let link = totp::otpauth_uri(&viewer.user.email, &shared); let code = qrcode::QrCode::new(link.as_bytes()) .map_err(|error| topcoat::Error::msg(error.to_string()))?; diff --git a/docs/architecture.md b/docs/architecture.md index 89ac865..fd039a1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -115,7 +115,8 @@ signed in to: drives back-channel logout and the "connected apps" list. **signing_keys**: `kid` PK (first 16 hex of SHA-256 of the public key), `private_sealed`, `public_raw` BLOB, `created_at`, `activates_at`, `retires_at` NULL. Exactly one key is "current": the newest with -`activates_at <= now` and no `retires_at`. +`activates_at <= now` and no `retires_at`. Once a key has stopped signing, `private_sealed` is blanked (empty), so +only the public key is kept; the row is deleted after the 7-day overlap. **invites**: `token_hash` PK, `email_folded`, `is_admin`, `invited_by` NULL FK SET NULL, `created_at`, `expires_at`, `accepted_at` NULL. Creating a new invite for an address deletes its older pending invites. diff --git a/docs/conventions.md b/docs/conventions.md index f5869f3..935efc1 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -95,8 +95,10 @@ tokens, passwords, cookies, or secrets. - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once. - Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second factors per user; checked before any lookup; `429` with `Retry-After`. -- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305 under the instance key, `v1:` + base64(nonce || - ciphertext). +- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305, `v1:` + base64(nonce || ciphertext). The instance + key is never used directly: every use gets its own key, HMAC-SHA256(instance key, " v1"), and + each seal binds its purpose (a fixed label) as associated data, so a value sealed for one purpose cannot + be opened as another. - Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left. ## 7. Authorization