Per-purpose derived keys and purpose-bound seals, retired signing seeds erased, key file directory fsynced, rotation refused while a key is pending, unparseable auth_time fails
Browse files at this commitbf598fa67d38b6d15b917b4ca53e6b1f0bf37085Parent: 1f366fa- fix
- per-purpose derived keys and purpose-bound seals, retired signing seeds erased, key file directory fsynced, rotation refused while a key is pending, unparseable auth_time fails
14 changed files +180 -60
- crates/im-core/src/backup.rs +4 -6
- crates/im-core/src/secret.rs +87 -22
- crates/im-core/src/store/admin.rs +4 -3
- crates/im-core/src/store/keys.rs +13 -0
- crates/im-core/src/totp.rs +3 -6
- crates/im-web/src/auth.rs +15 -6
- crates/im-web/src/cli.rs +10 -2
- crates/im-web/src/mail/mod.rs +1 -1
- crates/im-web/src/mail/worker.rs +2 -1
- crates/im-web/src/oidc/signing.rs +27 -6
- crates/im-web/src/oidc/token.rs +5 -1
- crates/im-web/src/pages/security.rs +3 -3
- docs/architecture.md +2 -1
- docs/conventions.md +4 -2
crates/im-core/src/backup.rsmodified+4 -6
| @@ -28,6 +28,7 @@ use turso::Builder; | |||
| 28 | 28 | ||
| 29 | use crate::error::{Error, Result}; | 29 | use crate::error::{Error, Result}; |
| 30 | use crate::photo::is_photo_name; | 30 | use crate::photo::is_photo_name; |
| 31 | +use crate::secret; | ||
| 31 | use crate::store::migrate::MIGRATIONS; | 32 | use crate::store::migrate::MIGRATIONS; |
| 32 | use crate::store::{Store, col_int, col_text, db_err, fetch_all}; | 33 | use crate::store::{Store, col_int, col_text, db_err, fetch_all}; |
| 33 | 34 | ||
| @@ -41,8 +42,8 @@ pub const DB_FILE: &str = "im.db"; | |||
| 41 | pub const MANIFEST_FILE: &str = "manifest.json"; | 42 | pub const MANIFEST_FILE: &str = "manifest.json"; |
| 42 | /// Name of the manifest's MAC inside a set: lower-case hex HMAC-SHA256 of the manifest bytes. | 43 | /// Name of the manifest's MAC inside a set: lower-case hex HMAC-SHA256 of the manifest bytes. |
| 43 | pub const MAC_FILE: &str = "manifest.mac"; | 44 | pub const MAC_FILE: &str = "manifest.mac"; |
| 44 | -/// What the manifest MAC key is derived for. The subkey is HMAC of this label under the instance key, the same | 45 | +/// Label of the manifest MAC subkey. The subkey is `secret::derive` of this label under the instance key, the |
| 45 | -/// way recovery codes derive theirs, so the instance key itself keys only that derivation. | 46 | +/// same way recovery codes get theirs; the MAC itself is keyed with that subkey, never with the instance key. |
| 46 | const MAC_SUBKEY_LABEL: &[u8] = b"im backup manifest v1"; | 47 | const MAC_SUBKEY_LABEL: &[u8] = b"im backup manifest v1"; |
| 47 | /// Name of the photo directory inside a set, and beside the database in the data directory. | 48 | /// Name of the photo directory inside a set, and beside the database in the data directory. |
| 48 | pub const PHOTOS_DIR: &str = "photos"; | 49 | pub const PHOTOS_DIR: &str = "photos"; |
| @@ -85,11 +86,8 @@ pub struct RestoreOutcome { | |||
| 85 | /// The HMAC over `bytes` under the manifest subkey of the instance key `key`. Its `verify_slice` is constant | 86 | /// The HMAC over `bytes` under the manifest subkey of the instance key `key`. Its `verify_slice` is constant |
| 86 | /// time, and its `finalize` gives the tag that is written to [`MAC_FILE`]. | 87 | /// time, and its `finalize` gives the tag that is written to [`MAC_FILE`]. |
| 87 | fn manifest_mac(key: &[u8; 32], bytes: &[u8]) -> HmacSha256 { | 88 | fn manifest_mac(key: &[u8; 32], bytes: &[u8]) -> HmacSha256 { |
| 89 | + let subkey = secret::derive(key, MAC_SUBKEY_LABEL); | ||
| 88 | // HMAC accepts a key of any length, so construction cannot fail. | 90 | // HMAC accepts a key of any length, so construction cannot fail. |
| 89 | - let mut derive = | ||
| 90 | - <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC takes any key length"); | ||
| 91 | - derive.update(MAC_SUBKEY_LABEL); | ||
| 92 | - let subkey = derive.finalize().into_bytes(); | ||
| 93 | let mut mac = | 91 | let mut mac = |
| 94 | <HmacSha256 as KeyInit>::new_from_slice(&subkey).expect("HMAC takes any key length"); | 92 | <HmacSha256 as KeyInit>::new_from_slice(&subkey).expect("HMAC takes any key length"); |
| 95 | mac.update(bytes); | 93 | mac.update(bytes); |
crates/im-core/src/secret.rsmodified+87 -22
| @@ -1,4 +1,8 @@ | |||
| 1 | -//! The instance key and XChaCha20-Poly1305 sealing of secrets at rest. | 1 | +//! The instance key, its derived subkeys, and XChaCha20-Poly1305 sealing of secrets at rest. |
| 2 | +//! | ||
| 3 | +//! The instance key never encrypts or MACs anything directly. Every use derives its own subkey from it | ||
| 4 | +//! (see [`derive`]), and every sealed value is bound to a purpose (see [`purpose`]) that is checked as | ||
| 5 | +//! associated data, so a value sealed for one purpose does not open as another. | ||
| 2 | //! | 6 | //! |
| 3 | //! A sealed value is `v1:` followed by base64(nonce || ciphertext). The nonce is random for every | 7 | //! A sealed value is `v1:` followed by base64(nonce || ciphertext). The nonce is random for every |
| 4 | //! seal, so sealing the same plaintext twice gives different text. The key never goes in the | 8 | //! seal, so sealing the same plaintext twice gives different text. The key never goes in the |
| @@ -7,30 +11,77 @@ | |||
| 7 | use std::path::Path; | 11 | use std::path::Path; |
| 8 | 12 | ||
| 9 | use base64::prelude::{BASE64_STANDARD, Engine as _}; | 13 | use base64::prelude::{BASE64_STANDARD, Engine as _}; |
| 10 | -use chacha20poly1305::aead::Aead; | 14 | +use chacha20poly1305::aead::{Aead, Payload}; |
| 11 | use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; | 15 | use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; |
| 16 | +use hmac::{Hmac, Mac}; | ||
| 17 | +use sha2::Sha256; | ||
| 12 | 18 | ||
| 13 | use crate::error::{Error, Result}; | 19 | use crate::error::{Error, Result}; |
| 14 | 20 | ||
| 15 | const PREFIX: &str = "v1:"; | 21 | const PREFIX: &str = "v1:"; |
| 16 | const NONCE_LEN: usize = 24; | 22 | const NONCE_LEN: usize = 24; |
| 23 | +/// Label of the subkey that seals values. The subkey is [`derive`] of this label. | ||
| 24 | +const SEAL_LABEL: &[u8] = b"im seal v1"; | ||
| 25 | + | ||
| 26 | +/// What a sealed value is for. Passed as the associated data of [`seal`] and [`open`]: a value sealed | ||
| 27 | +/// under one purpose fails authentication under any other. | ||
| 28 | +pub mod purpose { | ||
| 29 | + /// The sealed cookie that carries a password-verified sign-in until its second factor. | ||
| 30 | + pub const PENDING_LOGIN: &str = "pending-login"; | ||
| 31 | + /// The sealed cookie that carries a client secret to the page that shows it once. | ||
| 32 | + pub const SECRET_FLASH: &str = "secret-flash"; | ||
| 33 | + /// A TOTP shared secret, both the pending enrolment and the one kept after enabling. | ||
| 34 | + pub const TOTP_SECRET: &str = "totp-secret"; | ||
| 35 | + /// The 32-byte Ed25519 seed of a signing key. | ||
| 36 | + pub const SIGNING_SEED: &str = "signing-seed"; | ||
| 37 | + /// The body of an outgoing mail. | ||
| 38 | + pub const MAIL_BODY: &str = "mail-body"; | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// Derives a 32-byte subkey of the instance key `key` for `label`: HMAC-SHA256 of the label, keyed with | ||
| 42 | +/// the instance key. Each use names its own label, so no two uses share key material. | ||
| 43 | +pub(crate) fn derive(key: &[u8; 32], label: &[u8]) -> [u8; 32] { | ||
| 44 | + // HMAC accepts a key of any length, so construction cannot fail. | ||
| 45 | + let mut mac = | ||
| 46 | + <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(key).expect("HMAC takes any key length"); | ||
| 47 | + mac.update(label); | ||
| 48 | + mac.finalize().into_bytes().into() | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// The cipher keyed with the seal subkey of the instance key `key`. | ||
| 52 | +fn cipher(key: &[u8; 32]) -> XChaCha20Poly1305 { | ||
| 53 | + let subkey = derive(key, SEAL_LABEL); | ||
| 54 | + XChaCha20Poly1305::new((&subkey).into()) | ||
| 55 | +} | ||
| 17 | 56 | ||
| 18 | /// Loads the 32-byte instance key at `path`, creating it if it is missing. | 57 | /// Loads the 32-byte instance key at `path`, creating it if it is missing. |
| 19 | /// | 58 | /// |
| 20 | -/// A new key is written with mode 0600 and `O_EXCL`, so two starts cannot both create it. An | 59 | +/// A new key is written with mode 0600 and `O_EXCL`, so two starts cannot both create it, and the |
| 21 | -/// existing key with any group or world permission is refused, because a leaked key defeats every | 60 | +/// directory is fsynced so the new entry survives a power cut. An existing key with any group or world |
| 22 | -/// sealed secret. | 61 | +/// permission is refused, because a leaked key defeats every sealed secret. |
| 23 | pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> { | 62 | pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> { |
| 24 | if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { | 63 | if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { |
| 25 | std::fs::create_dir_all(parent)?; | 64 | std::fs::create_dir_all(parent)?; |
| 26 | } | 65 | } |
| 27 | match create_key(path) { | 66 | match create_key(path) { |
| 28 | - Ok(key) => Ok(key), | 67 | + Ok(key) => { |
| 68 | + sync_parent(path)?; | ||
| 69 | + Ok(key) | ||
| 70 | + } | ||
| 29 | Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => read_key(path), | 71 | Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => read_key(path), |
| 30 | Err(e) => Err(e.into()), | 72 | Err(e) => Err(e.into()), |
| 31 | } | 73 | } |
| 32 | } | 74 | } |
| 33 | 75 | ||
| 76 | +/// Fsyncs the directory that holds `path`, so a file created in it is durable. | ||
| 77 | +fn sync_parent(path: &Path) -> std::io::Result<()> { | ||
| 78 | + let dir = path | ||
| 79 | + .parent() | ||
| 80 | + .filter(|p| !p.as_os_str().is_empty()) | ||
| 81 | + .unwrap_or(Path::new(".")); | ||
| 82 | + std::fs::File::open(dir)?.sync_all() | ||
| 83 | +} | ||
| 84 | + | ||
| 34 | fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { | 85 | fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { |
| 35 | use std::io::Write; | 86 | use std::io::Write; |
| 36 | 87 | ||
| @@ -84,16 +135,21 @@ pub fn read_key(path: &Path) -> Result<[u8; 32]> { | |||
| 84 | }) | 135 | }) |
| 85 | } | 136 | } |
| 86 | 137 | ||
| 87 | -/// Seals `plaintext` under `key`. Output: `"v1:" + base64(nonce || ciphertext)`. | 138 | +/// Seals `plaintext` under `key`, bound to `purpose`. Output: `"v1:" + base64(nonce || ciphertext)`. |
| 88 | /// | 139 | /// |
| 89 | /// Errors if the cipher rejects the input. The caller must then refuse to store the value, never | 140 | /// Errors if the cipher rejects the input. The caller must then refuse to store the value, never |
| 90 | /// store it in clear. | 141 | /// store it in clear. |
| 91 | -pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> { | 142 | +pub fn seal(key: &[u8; 32], purpose: &str, plaintext: &[u8]) -> Result<String> { |
| 92 | let mut nonce = [0u8; NONCE_LEN]; | 143 | let mut nonce = [0u8; NONCE_LEN]; |
| 93 | rand::fill(&mut nonce); | 144 | rand::fill(&mut nonce); |
| 94 | - let cipher = XChaCha20Poly1305::new(key.into()); | 145 | + let ciphertext = cipher(key) |
| 95 | - let ciphertext = cipher | 146 | + .encrypt( |
| 96 | - .encrypt(&XNonce::from(nonce), plaintext) | 147 | + &XNonce::from(nonce), |
| 148 | + Payload { | ||
| 149 | + msg: plaintext, | ||
| 150 | + aad: purpose.as_bytes(), | ||
| 151 | + }, | ||
| 152 | + ) | ||
| 97 | .map_err(|_| Error::Crypto("sealing failed".into()))?; | 153 | .map_err(|_| Error::Crypto("sealing failed".into()))?; |
| 98 | let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len()); | 154 | let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len()); |
| 99 | blob.extend_from_slice(&nonce); | 155 | blob.extend_from_slice(&nonce); |
| @@ -101,11 +157,11 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> { | |||
| 101 | Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) | 157 | Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) |
| 102 | } | 158 | } |
| 103 | 159 | ||
| 104 | -/// Opens a value produced by [`seal`] under the same key. | 160 | +/// Opens a value produced by [`seal`] under the same key and the same `purpose`. |
| 105 | /// | 161 | /// |
| 106 | -/// Any failure (bad prefix, bad base64, short input, wrong key, tampering) is an error. The | 162 | +/// Any failure (bad prefix, bad base64, short input, wrong key, wrong purpose, tampering) is an error. |
| 107 | -/// messages are fixed strings, so nothing about the plaintext or the key can leak through them. | 163 | +/// The messages are fixed strings, so nothing about the plaintext or the key can leak through them. |
| 108 | -pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> { | 164 | +pub fn open(key: &[u8; 32], purpose: &str, sealed: &str) -> Result<Vec<u8>> { |
| 109 | let encoded = sealed | 165 | let encoded = sealed |
| 110 | .strip_prefix(PREFIX) | 166 | .strip_prefix(PREFIX) |
| 111 | .ok_or_else(|| Error::Crypto("sealed value has no v1 prefix".into()))?; | 167 | .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<Vec<u8>> { | |||
| 118 | let (nonce, ciphertext) = blob.split_at(NONCE_LEN); | 174 | let (nonce, ciphertext) = blob.split_at(NONCE_LEN); |
| 119 | let nonce = <[u8; NONCE_LEN]>::try_from(nonce) | 175 | let nonce = <[u8; NONCE_LEN]>::try_from(nonce) |
| 120 | .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?; | 176 | .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?; |
| 121 | - let cipher = XChaCha20Poly1305::new(key.into()); | 177 | + cipher(key) |
| 122 | - cipher | 178 | + .decrypt( |
| 123 | - .decrypt(&XNonce::from(nonce), ciphertext) | 179 | + &XNonce::from(nonce), |
| 180 | + Payload { | ||
| 181 | + msg: ciphertext, | ||
| 182 | + aad: purpose.as_bytes(), | ||
| 183 | + }, | ||
| 184 | + ) | ||
| 124 | .map_err(|_| Error::Crypto("sealed value failed authentication".into())) | 185 | .map_err(|_| Error::Crypto("sealed value failed authentication".into())) |
| 125 | } | 186 | } |
| 126 | 187 | ||
| @@ -129,11 +190,15 @@ mod tests { | |||
| 129 | use super::*; | 190 | use super::*; |
| 130 | 191 | ||
| 131 | #[test] | 192 | #[test] |
| 132 | - fn seal_then_open_returns_the_plaintext_and_rejects_another_key() { | 193 | + fn seal_then_open_returns_the_plaintext_and_rejects_another_key_or_purpose() { |
| 133 | let key = [7u8; 32]; | 194 | let key = [7u8; 32]; |
| 134 | - let sealed = seal(&key, b"hello secret").unwrap(); | 195 | + let sealed = seal(&key, purpose::SECRET_FLASH, b"hello secret").unwrap(); |
| 135 | assert!(sealed.starts_with("v1:")); | 196 | assert!(sealed.starts_with("v1:")); |
| 136 | - assert_eq!(open(&key, &sealed).unwrap(), b"hello secret"); | 197 | + assert_eq!( |
| 137 | - assert!(open(&[8u8; 32], &sealed).is_err()); | 198 | + open(&key, purpose::SECRET_FLASH, &sealed).unwrap(), |
| 199 | + b"hello secret" | ||
| 200 | + ); | ||
| 201 | + assert!(open(&[8u8; 32], purpose::SECRET_FLASH, &sealed).is_err()); | ||
| 202 | + assert!(open(&key, purpose::PENDING_LOGIN, &sealed).is_err()); | ||
| 138 | } | 203 | } |
| 139 | } | 204 | } |
crates/im-core/src/store/admin.rsmodified+4 -3
| @@ -443,14 +443,15 @@ impl Store { | |||
| 443 | } | 443 | } |
| 444 | 444 | ||
| 445 | /// Retires a published signing key that is not the current one. Its public key stays published for | 445 | /// Retires a published signing key that is not the current one. Its public key stays published for |
| 446 | - /// the usual overlap, so tokens it signed still verify. The current key cannot be retired: the | 446 | + /// the usual overlap, so tokens it signed still verify. Its sealed seed is blanked in the same write, |
| 447 | - /// statement excludes it, so a token can always be signed. | 447 | + /// because a retired key never signs again. The current key cannot be retired: the statement excludes |
| 448 | + /// it, so a token can always be signed. | ||
| 448 | pub async fn retire_signing_key(&self, kid: &str) -> Result<bool> { | 449 | pub async fn retire_signing_key(&self, kid: &str) -> Result<bool> { |
| 449 | let now = now_stamp(); | 450 | let now = now_stamp(); |
| 450 | let conn = self.inner.conn.lock().await; | 451 | let conn = self.inner.conn.lock().await; |
| 451 | let changed = conn | 452 | let changed = conn |
| 452 | .execute( | 453 | .execute( |
| 453 | - "UPDATE signing_keys SET retires_at = ?2 \ | 454 | + "UPDATE signing_keys SET retires_at = ?2, private_sealed = '' \ |
| 454 | WHERE kid = ?1 AND retires_at IS NULL AND activates_at <= ?2 \ | 455 | WHERE kid = ?1 AND retires_at IS NULL AND activates_at <= ?2 \ |
| 455 | AND kid <> (SELECT kid FROM signing_keys WHERE retires_at IS NULL AND activates_at <= ?2 \ | 456 | AND kid <> (SELECT kid FROM signing_keys WHERE retires_at IS NULL AND activates_at <= ?2 \ |
| 456 | ORDER BY activates_at DESC, kid DESC LIMIT 1)", | 457 | ORDER BY activates_at DESC, kid DESC LIMIT 1)", |
crates/im-core/src/store/keys.rsmodified+13 -0
| @@ -73,6 +73,19 @@ impl Store { | |||
| 73 | finish(tx, outcome).await | 73 | finish(tx, outcome).await |
| 74 | } | 74 | } |
| 75 | 75 | ||
| 76 | + /// Blanks the sealed seed of every key that stopped signing at or before `now`. Verification needs only the | ||
| 77 | + /// public key, so a retired key keeps nothing usable. Returns how many rows were blanked. | ||
| 78 | + pub async fn scrub_retired_signing_seeds(&self, now: &str) -> Result<u64> { | ||
| 79 | + let conn = self.inner.conn.lock().await; | ||
| 80 | + conn.execute( | ||
| 81 | + "UPDATE signing_keys SET private_sealed = '' \ | ||
| 82 | + WHERE retires_at IS NOT NULL AND retires_at <= ?1 AND private_sealed <> ''", | ||
| 83 | + (now.to_string(),), | ||
| 84 | + ) | ||
| 85 | + .await | ||
| 86 | + .map_err(db_err) | ||
| 87 | + } | ||
| 88 | + | ||
| 76 | /// Deletes keys retired at or before `cutoff`. Returns how many were removed. | 89 | /// Deletes keys retired at or before `cutoff`. Returns how many were removed. |
| 77 | pub async fn prune_signing_keys(&self, cutoff: &str) -> Result<u64> { | 90 | pub async fn prune_signing_keys(&self, cutoff: &str) -> Result<u64> { |
| 78 | let conn = self.inner.conn.lock().await; | 91 | let conn = self.inner.conn.lock().await; |
crates/im-core/src/totp.rsmodified+3 -6
| @@ -11,6 +11,7 @@ use hmac::{Hmac, KeyInit, Mac}; | |||
| 11 | use sha1::Sha1; | 11 | use sha1::Sha1; |
| 12 | use sha2::Sha256; | 12 | use sha2::Sha256; |
| 13 | 13 | ||
| 14 | +use crate::secret; | ||
| 14 | use crate::token::{constant_time_eq, random_readable}; | 15 | use crate::token::{constant_time_eq, random_readable}; |
| 15 | 16 | ||
| 16 | /// Shared secret length in bytes: 160 bits, the RFC 4226 recommendation. | 17 | /// Shared secret length in bytes: 160 bits, the RFC 4226 recommendation. |
| @@ -34,8 +35,7 @@ type HmacSha1 = Hmac<Sha1>; | |||
| 34 | 35 | ||
| 35 | type HmacSha256 = Hmac<Sha256>; | 36 | type HmacSha256 = Hmac<Sha256>; |
| 36 | 37 | ||
| 37 | -/// What a recovery-code subkey is derived for. The subkey is HMAC of this label under the instance key, | 38 | +/// Label of the recovery-code subkey. The subkey is `secret::derive` of this label under the instance key. |
| 38 | -/// so the instance key itself keys only that derivation. | ||
| 39 | const RECOVERY_SUBKEY_LABEL: &[u8] = b"im recovery code key v1"; | 39 | const RECOVERY_SUBKEY_LABEL: &[u8] = b"im recovery code key v1"; |
| 40 | 40 | ||
| 41 | /// A fresh random secret of [`SECRET_LEN`] bytes. | 41 | /// A fresh random secret of [`SECRET_LEN`] bytes. |
| @@ -161,11 +161,8 @@ pub fn recovery_code_hash(key: &[u8; 32], code: &str) -> String { | |||
| 161 | .filter(|c| !c.is_whitespace() && *c != '-') | 161 | .filter(|c| !c.is_whitespace() && *c != '-') |
| 162 | .map(|c| c.to_ascii_lowercase()) | 162 | .map(|c| c.to_ascii_lowercase()) |
| 163 | .collect(); | 163 | .collect(); |
| 164 | + let subkey = secret::derive(key, RECOVERY_SUBKEY_LABEL); | ||
| 164 | // HMAC accepts a key of any length, so construction cannot fail. | 165 | // HMAC accepts a key of any length, so construction cannot fail. |
| 165 | - let mut derive = | ||
| 166 | - <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC takes any key length"); | ||
| 167 | - derive.update(RECOVERY_SUBKEY_LABEL); | ||
| 168 | - let subkey = derive.finalize().into_bytes(); | ||
| 169 | let mut mac = | 166 | let mut mac = |
| 170 | <HmacSha256 as KeyInit>::new_from_slice(&subkey).expect("HMAC takes any key length"); | 167 | <HmacSha256 as KeyInit>::new_from_slice(&subkey).expect("HMAC takes any key length"); |
| 171 | mac.update(normalized.as_bytes()); | 168 | mac.update(normalized.as_bytes()); |
crates/im-web/src/auth.rsmodified+15 -6
| @@ -277,7 +277,7 @@ pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> | |||
| 277 | let expires = unix_now() + PENDING_TTL.as_secs(); | 277 | let expires = unix_now() + PENDING_TTL.as_secs(); |
| 278 | let nonce = generate_token(); | 278 | let nonce = generate_token(); |
| 279 | let payload = format!("{user_id}|{expires}|{}|{nonce}|{next}", amr::PASSWORD); | 279 | let payload = format!("{user_id}|{expires}|{}|{nonce}|{next}", amr::PASSWORD); |
| 280 | - let sealed = secret::seal(key, payload.as_bytes())?; | 280 | + let sealed = secret::seal(key, secret::purpose::PENDING_LOGIN, payload.as_bytes())?; |
| 281 | let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0)); | 281 | let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0)); |
| 282 | jar(cx).add( | 282 | jar(cx).add( |
| 283 | Cookie::build((PENDING_COOKIE, sealed)) | 283 | Cookie::build((PENDING_COOKIE, sealed)) |
| @@ -295,7 +295,7 @@ pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> | |||
| 295 | /// `next` is the field as it was set; the caller applies [`safe_next`]. | 295 | /// `next` is the field as it was set; the caller applies [`safe_next`]. |
| 296 | pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<Pending> { | 296 | pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<Pending> { |
| 297 | let cookie = jar(cx).get(PENDING_COOKIE)?; | 297 | let cookie = jar(cx).get(PENDING_COOKIE)?; |
| 298 | - let plain = secret::open(key, cookie.value()).ok()?; | 298 | + let plain = secret::open(key, secret::purpose::PENDING_LOGIN, cookie.value()).ok()?; |
| 299 | let text = String::from_utf8(plain).ok()?; | 299 | let text = String::from_utf8(plain).ok()?; |
| 300 | // `next` comes last, so a `|` inside it cannot shift the other fields. | 300 | // `next` comes last, so a `|` inside it cannot shift the other fields. |
| 301 | let mut parts = text.splitn(5, '|'); | 301 | let mut parts = text.splitn(5, '|'); |
| @@ -333,7 +333,11 @@ pub const SECRET_FLASH_TTL: Duration = Duration::from_secs(2 * 60); | |||
| 333 | /// sign-in: `__Host-`, Secure, HttpOnly, SameSite=Strict, Path=/. | 333 | /// sign-in: `__Host-`, Secure, HttpOnly, SameSite=Strict, Path=/. |
| 334 | pub fn set_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str, secret: &str) -> Result<()> { | 334 | pub fn set_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str, secret: &str) -> Result<()> { |
| 335 | let expires = unix_now() + SECRET_FLASH_TTL.as_secs(); | 335 | let expires = unix_now() + SECRET_FLASH_TTL.as_secs(); |
| 336 | - let sealed = secret::seal(key, format!("{client_id}|{expires}|{secret}").as_bytes())?; | 336 | + let sealed = secret::seal( |
| 337 | + key, | ||
| 338 | + secret::purpose::SECRET_FLASH, | ||
| 339 | + format!("{client_id}|{expires}|{secret}").as_bytes(), | ||
| 340 | + )?; | ||
| 337 | let max_age = time::Duration::seconds(i64::try_from(SECRET_FLASH_TTL.as_secs()).unwrap_or(0)); | 341 | let max_age = time::Duration::seconds(i64::try_from(SECRET_FLASH_TTL.as_secs()).unwrap_or(0)); |
| 338 | jar(cx).add( | 342 | jar(cx).add( |
| 339 | Cookie::build((SECRET_FLASH_COOKIE, sealed)) | 343 | 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) | |||
| 352 | pub fn take_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str) -> Option<String> { | 356 | pub fn take_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str) -> Option<String> { |
| 353 | let sealed = jar(cx).get(SECRET_FLASH_COOKIE)?.value().to_owned(); | 357 | let sealed = jar(cx).get(SECRET_FLASH_COOKIE)?.value().to_owned(); |
| 354 | clear_secret_flash(cx); | 358 | clear_secret_flash(cx); |
| 355 | - let plain = secret::open(key, &sealed).ok()?; | 359 | + let plain = secret::open(key, secret::purpose::SECRET_FLASH, &sealed).ok()?; |
| 356 | let text = String::from_utf8(plain).ok()?; | 360 | let text = String::from_utf8(plain).ok()?; |
| 357 | let mut parts = text.splitn(3, '|'); | 361 | let mut parts = text.splitn(3, '|'); |
| 358 | let id = parts.next()?; | 362 | let id = parts.next()?; |
| @@ -375,7 +379,7 @@ pub async fn verify_totp(store: &Store, key: &[u8; 32], user: &User, code: &str) | |||
| 375 | if !user.totp_enabled() { | 379 | if !user.totp_enabled() { |
| 376 | return Ok(false); | 380 | return Ok(false); |
| 377 | } | 381 | } |
| 378 | - let shared = secret::open(key, sealed)?; | 382 | + let shared = secret::open(key, secret::purpose::TOTP_SECRET, sealed)?; |
| 379 | let last = user | 383 | let last = user |
| 380 | .totp_last_step | 384 | .totp_last_step |
| 381 | .and_then(|step| u64::try_from(step).ok()); | 385 | .and_then(|step| u64::try_from(step).ok()); |
| @@ -518,7 +522,12 @@ mod tests { | |||
| 518 | .create_user("ada@example.com", "Ada", "hash", false) | 522 | .create_user("ada@example.com", "Ada", "hash", false) |
| 519 | .await | 523 | .await |
| 520 | .expect("user"); | 524 | .expect("user"); |
| 521 | - let sealed = secret::seal(&state.key, &totp::new_secret()).expect("seal"); | 525 | + let sealed = secret::seal( |
| 526 | + &state.key, | ||
| 527 | + secret::purpose::TOTP_SECRET, | ||
| 528 | + &totp::new_secret(), | ||
| 529 | + ) | ||
| 530 | + .expect("seal"); | ||
| 522 | let code = totp::new_recovery_code(); | 531 | let code = totp::new_recovery_code(); |
| 523 | state | 532 | state |
| 524 | .store | 533 | .store |
crates/im-web/src/cli.rsmodified+10 -2
| @@ -317,8 +317,16 @@ pub async fn fsck(config: &Path) -> ExitCode { | |||
| 317 | .await | 317 | .await |
| 318 | .map_err(|e| e.to_string())? | 318 | .map_err(|e| e.to_string())? |
| 319 | { | 319 | { |
| 320 | - im_core::secret::open(&state.key, &key.private_sealed) | 320 | + // A retired key whose seed was blanked has nothing to open; its public key is all that is kept. |
| 321 | - .map_err(|e| format!("signing key {} cannot be opened: {e}", key.kid))?; | 321 | + if key.retires_at.is_some() && key.private_sealed.is_empty() { |
| 322 | + continue; | ||
| 323 | + } | ||
| 324 | + im_core::secret::open( | ||
| 325 | + &state.key, | ||
| 326 | + im_core::secret::purpose::SIGNING_SEED, | ||
| 327 | + &key.private_sealed, | ||
| 328 | + ) | ||
| 329 | + .map_err(|e| format!("signing key {} cannot be opened: {e}", key.kid))?; | ||
| 322 | } | 330 | } |
| 323 | println!("im: database and signing keys ok"); | 331 | println!("im: database and signing keys ok"); |
| 324 | Ok(()) | 332 | Ok(()) |
crates/im-web/src/mail/mod.rsmodified+1 -1
| @@ -139,7 +139,7 @@ pub async fn queue( | |||
| 139 | "html": rendered.html, | 139 | "html": rendered.html, |
| 140 | }) | 140 | }) |
| 141 | .to_string(); | 141 | .to_string(); |
| 142 | - let sealed = secret::seal(key, payload.as_bytes())?; | 142 | + let sealed = secret::seal(key, secret::purpose::MAIL_BODY, payload.as_bytes())?; |
| 143 | store | 143 | store |
| 144 | .enqueue_mail(&NewMail { | 144 | .enqueue_mail(&NewMail { |
| 145 | kind: mail.kind(), | 145 | kind: mail.kind(), |
crates/im-web/src/mail/worker.rsmodified+2 -1
| @@ -180,7 +180,8 @@ fn open_message( | |||
| 180 | if job.sealed_body.is_empty() { | 180 | if job.sealed_body.is_empty() { |
| 181 | return Err("mail body is missing"); | 181 | return Err("mail body is missing"); |
| 182 | } | 182 | } |
| 183 | - let plain = secret::open(key, &job.sealed_body).map_err(|_| "mail body cannot be opened")?; | 183 | + let plain = secret::open(key, secret::purpose::MAIL_BODY, &job.sealed_body) |
| 184 | + .map_err(|_| "mail body cannot be opened")?; | ||
| 184 | let body: Body = serde_json::from_slice(&plain).map_err(|_| "mail body is not valid")?; | 185 | let body: Body = serde_json::from_slice(&plain).map_err(|_| "mail body is not valid")?; |
| 185 | let to = Recipient::new(body.to_name.as_deref(), &job.to_addr)?; | 186 | let to = Recipient::new(body.to_name.as_deref(), &job.to_addr)?; |
| 186 | build(sender, &to, &job.subject, body.text, body.html) | 187 | build(sender, &to, &job.subject, body.text, body.html) |
crates/im-web/src/oidc/signing.rsmodified+27 -6
| @@ -21,8 +21,8 @@ use tokio::sync::watch; | |||
| 21 | const CHECK_EVERY: Duration = Duration::from_secs(24 * 60 * 60); | 21 | const CHECK_EVERY: Duration = Duration::from_secs(24 * 60 * 60); |
| 22 | 22 | ||
| 23 | /// Makes sure the chain is current: creates the first key when there is none, and creates the successor | 23 | /// Makes sure the chain is current: creates the first key when there is none, and creates the successor |
| 24 | -/// when the newest key is due within the publish lead. Then removes keys retired more than [`OVERLAP`] | 24 | +/// when the newest key is due within the publish lead. Then blanks the seeds of keys that have stopped |
| 25 | -/// ago. Idempotent; safe to run at every boot. | 25 | +/// signing, and removes keys retired more than [`OVERLAP`] ago. Idempotent; safe to run at every boot. |
| 26 | pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<()> { | 26 | pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<()> { |
| 27 | let rows = store.signing_keys().await?; | 27 | let rows = store.signing_keys().await?; |
| 28 | let now = now_stamp(); | 28 | let now = now_stamp(); |
| @@ -30,7 +30,7 @@ pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result | |||
| 30 | let fresh = keys::generate(); | 30 | let fresh = keys::generate(); |
| 31 | let record = KeyRecord { | 31 | let record = KeyRecord { |
| 32 | kid: fresh.kid.clone(), | 32 | kid: fresh.kid.clone(), |
| 33 | - private_sealed: secret::seal(instance_key, &fresh.seed)?, | 33 | + private_sealed: secret::seal(instance_key, secret::purpose::SIGNING_SEED, &fresh.seed)?, |
| 34 | public_raw: fresh.public.to_vec(), | 34 | public_raw: fresh.public.to_vec(), |
| 35 | created_at: now.clone(), | 35 | created_at: now.clone(), |
| 36 | activates_at: activates_at.clone(), | 36 | activates_at: activates_at.clone(), |
| @@ -39,6 +39,11 @@ pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result | |||
| 39 | store.add_signing_key(&record).await?; | 39 | store.add_signing_key(&record).await?; |
| 40 | tracing::info!(kid = %record.kid, activates_at = %activates_at, "signing key created"); | 40 | tracing::info!(kid = %record.kid, activates_at = %activates_at, "signing key created"); |
| 41 | } | 41 | } |
| 42 | + // A key retired by a successor keeps its seed until its retirement time, because it signs until then. | ||
| 43 | + let scrubbed = store.scrub_retired_signing_seeds(&now).await?; | ||
| 44 | + if scrubbed > 0 { | ||
| 45 | + tracing::info!(scrubbed, "seeds of retired signing keys blanked"); | ||
| 46 | + } | ||
| 42 | let cutoff = stamp_minus(&now, OVERLAP).unwrap_or_else(|| now.clone()); | 47 | let cutoff = stamp_minus(&now, OVERLAP).unwrap_or_else(|| now.clone()); |
| 43 | let pruned = store.prune_signing_keys(&cutoff).await?; | 48 | let pruned = store.prune_signing_keys(&cutoff).await?; |
| 44 | if pruned > 0 { | 49 | if pruned > 0 { |
| @@ -68,16 +73,28 @@ pub fn spawn( | |||
| 68 | 73 | ||
| 69 | /// Makes a new key the signing key, one publish lead from now. It is published first and only then used: the | 74 | /// Makes a new key the signing key, one publish lead from now. It is published first and only then used: the |
| 70 | /// JWKS carries it before the first token it signs, and the previous key keeps signing until then. Returns the | 75 | /// JWKS carries it before the first token it signs, and the previous key keeps signing until then. Returns the |
| 71 | -/// new key id. | 76 | +/// new key id. Refused while another key is still waiting to activate: two pending keys would make the |
| 77 | +/// retirement order ambiguous. | ||
| 72 | pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<String> { | 78 | pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<String> { |
| 73 | let fresh = keys::generate(); | 79 | let fresh = keys::generate(); |
| 74 | let now = now_stamp(); | 80 | let now = now_stamp(); |
| 81 | + let pending = store | ||
| 82 | + .signing_keys() | ||
| 83 | + .await? | ||
| 84 | + .iter() | ||
| 85 | + .any(|key| key.retires_at.is_none() && key.activates_at > now); | ||
| 86 | + if pending { | ||
| 87 | + return Err(im_core::Error::Conflict( | ||
| 88 | + "another signing key is still waiting to activate; rotate after it starts signing" | ||
| 89 | + .into(), | ||
| 90 | + )); | ||
| 91 | + } | ||
| 75 | let activates_at = stamp_plus(&now, keys::PUBLISH_LEAD).ok_or_else(|| { | 92 | let activates_at = stamp_plus(&now, keys::PUBLISH_LEAD).ok_or_else(|| { |
| 76 | im_core::Error::Crypto("the new key's activation time is out of range".into()) | 93 | im_core::Error::Crypto("the new key's activation time is out of range".into()) |
| 77 | })?; | 94 | })?; |
| 78 | let record = KeyRecord { | 95 | let record = KeyRecord { |
| 79 | kid: fresh.kid.clone(), | 96 | kid: fresh.kid.clone(), |
| 80 | - private_sealed: secret::seal(instance_key, &fresh.seed)?, | 97 | + private_sealed: secret::seal(instance_key, secret::purpose::SIGNING_SEED, &fresh.seed)?, |
| 81 | public_raw: fresh.public.to_vec(), | 98 | public_raw: fresh.public.to_vec(), |
| 82 | created_at: now, | 99 | created_at: now, |
| 83 | activates_at, | 100 | activates_at, |
| @@ -136,7 +153,11 @@ pub async fn sign( | |||
| 136 | 153 | ||
| 137 | /// Opens the sealed seed of a key row. | 154 | /// Opens the sealed seed of a key row. |
| 138 | fn seed_of(instance_key: &[u8; 32], record: &KeyRecord) -> im_core::Result<[u8; 32]> { | 155 | fn seed_of(instance_key: &[u8; 32], record: &KeyRecord) -> im_core::Result<[u8; 32]> { |
| 139 | - let bytes = secret::open(instance_key, &record.private_sealed)?; | 156 | + let bytes = secret::open( |
| 157 | + instance_key, | ||
| 158 | + secret::purpose::SIGNING_SEED, | ||
| 159 | + &record.private_sealed, | ||
| 160 | + )?; | ||
| 140 | <[u8; 32]>::try_from(bytes.as_slice()) | 161 | <[u8; 32]>::try_from(bytes.as_slice()) |
| 141 | .map_err(|_| im_core::Error::Crypto("signing key has the wrong length".into())) | 162 | .map_err(|_| im_core::Error::Crypto("signing key has the wrong length".into())) |
| 142 | } | 163 | } |
crates/im-web/src/oidc/token.rsmodified+5 -1
| @@ -459,13 +459,17 @@ async fn id_token( | |||
| 459 | nonce: Option<&str>, | 459 | nonce: Option<&str>, |
| 460 | ) -> im_core::Result<String> { | 460 | ) -> im_core::Result<String> { |
| 461 | let now = im_core::time::unix_now(); | 461 | let now = im_core::time::unix_now(); |
| 462 | + // A stored stamp that does not parse is a server fault: it is never replaced by the current time. | ||
| 463 | + let auth_time = unix_seconds(&session.auth_time).ok_or_else(|| { | ||
| 464 | + im_core::Error::Database("the session's auth_time is not a stored stamp".into()) | ||
| 465 | + })?; | ||
| 462 | let mut claims = json!({ | 466 | let mut claims = json!({ |
| 463 | "iss": issuer(app), | 467 | "iss": issuer(app), |
| 464 | "sub": user.id, | 468 | "sub": user.id, |
| 465 | "aud": client.id, | 469 | "aud": client.id, |
| 466 | "iat": now, | 470 | "iat": now, |
| 467 | "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0), | 471 | "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0), |
| 468 | - "auth_time": unix_seconds(&session.auth_time).unwrap_or(now), | 472 | + "auth_time": auth_time, |
| 469 | "sid": session.id, | 473 | "sid": session.id, |
| 470 | "amr": amr::rfc8176(&session.amr), | 474 | "amr": amr::rfc8176(&session.amr), |
| 471 | }); | 475 | }); |
crates/im-web/src/pages/security.rsmodified+3 -3
| @@ -239,7 +239,7 @@ async fn start_enrolment(cx: &Cx, Form(form): Form<StartForm>) -> Result<impl Vi | |||
| 239 | return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await; | 239 | return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await; |
| 240 | } | 240 | } |
| 241 | let secret = totp::new_secret(); | 241 | let secret = totp::new_secret(); |
| 242 | - let sealed = secret::seal(&state.key, &secret)?; | 242 | + let sealed = secret::seal(&state.key, secret::purpose::TOTP_SECRET, &secret)?; |
| 243 | state | 243 | state |
| 244 | .store | 244 | .store |
| 245 | .set_totp_pending(&viewer.user.id, &sealed) | 245 | .set_totp_pending(&viewer.user.id, &sealed) |
| @@ -262,7 +262,7 @@ async fn confirm_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl V | |||
| 262 | ) | 262 | ) |
| 263 | .await; | 263 | .await; |
| 264 | }; | 264 | }; |
| 265 | - let shared = secret::open(&state.key, &sealed)?; | 265 | + let shared = secret::open(&state.key, secret::purpose::TOTP_SECRET, &sealed)?; |
| 266 | let last = viewer | 266 | let last = viewer |
| 267 | .user | 267 | .user |
| 268 | .totp_last_step | 268 | .totp_last_step |
| @@ -472,7 +472,7 @@ fn changed(state: &AppState, viewer: &Viewer) { | |||
| 472 | 472 | ||
| 473 | /// Builds the QR code of a secret as a `data:` image, so no request leaves the page for it. | 473 | /// Builds the QR code of a secret as a `data:` image, so no request leaves the page for it. |
| 474 | fn enrolment_of(state: &AppState, viewer: &Viewer, sealed: &str) -> Result<Enrolment> { | 474 | fn enrolment_of(state: &AppState, viewer: &Viewer, sealed: &str) -> Result<Enrolment> { |
| 475 | - let shared = secret::open(&state.key, sealed)?; | 475 | + let shared = secret::open(&state.key, secret::purpose::TOTP_SECRET, sealed)?; |
| 476 | let link = totp::otpauth_uri(&viewer.user.email, &shared); | 476 | let link = totp::otpauth_uri(&viewer.user.email, &shared); |
| 477 | let code = qrcode::QrCode::new(link.as_bytes()) | 477 | let code = qrcode::QrCode::new(link.as_bytes()) |
| 478 | .map_err(|error| topcoat::Error::msg(error.to_string()))?; | 478 | .map_err(|error| topcoat::Error::msg(error.to_string()))?; |
docs/architecture.mdmodified+2 -1
| @@ -115,7 +115,8 @@ signed in to: drives back-channel logout and the "connected apps" list. | |||
| 115 | 115 | ||
| 116 | **signing_keys**: `kid` PK (first 16 hex of SHA-256 of the public key), `private_sealed`, `public_raw` BLOB, | 116 | **signing_keys**: `kid` PK (first 16 hex of SHA-256 of the public key), `private_sealed`, `public_raw` BLOB, |
| 117 | `created_at`, `activates_at`, `retires_at` NULL. Exactly one key is "current": the newest with | 117 | `created_at`, `activates_at`, `retires_at` NULL. Exactly one key is "current": the newest with |
| 118 | -`activates_at <= now` and no `retires_at`. | 118 | +`activates_at <= now` and no `retires_at`. Once a key has stopped signing, `private_sealed` is blanked (empty), so |
| 119 | +only the public key is kept; the row is deleted after the 7-day overlap. | ||
| 119 | 120 | ||
| 120 | **invites**: `token_hash` PK, `email_folded`, `is_admin`, `invited_by` NULL FK SET NULL, `created_at`, | 121 | **invites**: `token_hash` PK, `email_folded`, `is_admin`, `invited_by` NULL FK SET NULL, `created_at`, |
| 121 | `expires_at`, `accepted_at` NULL. Creating a new invite for an address deletes its older pending invites. | 122 | `expires_at`, `accepted_at` NULL. Creating a new invite for an address deletes its older pending invites. |
docs/conventions.mdmodified+4 -2
| @@ -95,8 +95,10 @@ tokens, passwords, cookies, or secrets. | |||
| 95 | - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once. | 95 | - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once. |
| 96 | - Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second | 96 | - Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second |
| 97 | factors per user; checked before any lookup; `429` with `Retry-After`. | 97 | factors per user; checked before any lookup; `429` with `Retry-After`. |
| 98 | -- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305 under the instance key, `v1:` + base64(nonce || | 98 | +- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305, `v1:` + base64(nonce || ciphertext). The instance |
| 99 | - ciphertext). | 99 | + key is never used directly: every use gets its own key, HMAC-SHA256(instance key, "<app> <use> v1"), and |
| 100 | + each seal binds its purpose (a fixed label) as associated data, so a value sealed for one purpose cannot | ||
| 101 | + be opened as another. | ||
| 100 | - Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left. | 102 | - Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left. |
| 101 | 103 | ||
| 102 | ## 7. Authorization | 104 | ## 7. Authorization |