diff --git a/crates/im-core/src/backup.rs b/crates/im-core/src/backup.rs index 6e29485..8da0bb4 100644 --- a/crates/im-core/src/backup.rs +++ b/crates/im-core/src/backup.rs @@ -1,37 +1,49 @@ //! Backup sets, verification, pruning and restore. //! //! A set is a directory `set-` under the backup root. It holds `im.db` (a consistent snapshot of the -//! database, see `store/snapshot.rs`), a `photos/` directory with a copy of every profile photo, and -//! `manifest.json`. The manifest names every file with its size and SHA-256. A set is written under a -//! temporary name and renamed into place only when its manifest is complete, so a half-written set is -//! never mistaken for a good one. +//! database, see `store/snapshot.rs`), a `photos/` directory with a copy of every profile photo, +//! `manifest.json`, and `manifest.mac`. The manifest names every file with its size and SHA-256. The MAC is +//! HMAC-SHA256 over the exact manifest bytes, keyed with a subkey of the instance key, so a manifest cannot be +//! rewritten to match changed files. A set is written under a temporary name and renamed into place only when +//! its manifest and MAC are complete, so a half-written set is never mistaken for a good one. //! -//! Verification checks every hash, refuses a file the manifest does not list (in the set or in `photos/`), -//! refuses a name that is not a plain file name, and runs `PRAGMA integrity_check` and the migration -//! check on a scratch copy, so the set itself is never written to. Restore verifies first and changes -//! nothing when verification fails. It only replaces a database and a photo directory that lie inside the -//! data directory, and it moves what it replaces into `data_dir/restore-/` rather than deleting it. -//! The caller must hold the data-directory lock: a running server is never restored under. +//! Verification checks the MAC first, in constant time, and reads nothing else from the manifest until it +//! passes. Then it checks every hash, refuses a file the manifest does not list, refuses any entry in `photos/` +//! that is not a photo name (see `photo::is_photo_name`) or not a regular file, and runs `PRAGMA +//! integrity_check` and the migration check on a scratch copy, so the set itself is never written to. Restore +//! verifies first and changes nothing when verification fails. It only replaces a database and a photo +//! directory that lie inside the data directory, and it moves what it replaces into `data_dir/restore-/` +//! rather than deleting it. The caller must hold the data-directory lock: a running server is never restored +//! under. use std::fs::OpenOptions; use std::io::{Read, Write}; -use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; +use hmac::{Hmac, KeyInit, Mac}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use turso::Builder; use crate::error::{Error, Result}; +use crate::photo::is_photo_name; use crate::store::migrate::MIGRATIONS; use crate::store::{Store, col_int, col_text, db_err, fetch_all}; +type HmacSha256 = Hmac; + /// The only manifest format this build reads and writes. pub const FORMAT: u32 = 1; /// Name of the snapshot inside a set. pub const DB_FILE: &str = "im.db"; /// Name of the manifest inside a set. 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. +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"; /// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix. @@ -70,6 +82,20 @@ pub struct RestoreOutcome { pub previous: PathBuf, } +/// 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 { + // 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); + mac +} + /// Creates a directory that only this user may enter. fn private_dir(path: &Path) -> Result<()> { std::fs::DirBuilder::new() @@ -89,12 +115,14 @@ fn private_file(path: &Path) -> Result { } /// Writes a complete set under `root` and returns its directory. `stamp` names it and must be safe in a -/// file name: callers replace `:` and `.` in the time stamp. +/// file name: callers replace `:` and `.` in the time stamp. `key` is the instance key that keys the manifest +/// MAC. pub async fn write_set( store: &Store, data_dir: &Path, root: &Path, stamp: &str, + key: &[u8; 32], ) -> Result { std::fs::create_dir_all(root)?; let tmp = root.join(format!(".tmp-{stamp}")); @@ -103,7 +131,7 @@ pub async fn write_set( return Err(Error::Conflict(format!("set {stamp} already exists"))); } private_dir(&tmp)?; - match write_into(store, data_dir, &tmp).await { + match write_into(store, data_dir, &tmp, key).await { Ok(()) => { std::fs::rename(&tmp, &final_dir)?; Ok(final_dir) @@ -116,10 +144,12 @@ pub async fn write_set( } } -/// Fills `dir` with the snapshot, the photos and the manifest, then fsyncs the directory. -async fn write_into(store: &Store, data_dir: &Path, dir: &Path) -> Result<()> { +/// Fills `dir` with the snapshot, the photos, the manifest and its MAC, then fsyncs the directory. +async fn write_into(store: &Store, data_dir: &Path, dir: &Path, key: &[u8; 32]) -> Result<()> { let db_path = dir.join(DB_FILE); store.snapshot_to(&db_path).await?; + // The snapshot holds every row, so it is private like the live database. + std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o600))?; let database = file_entry(DB_FILE, &db_path)?; let photos_out = dir.join(PHOTOS_DIR); @@ -127,7 +157,7 @@ async fn write_into(store: &Store, data_dir: &Path, dir: &Path) -> Result<()> { let mut photos = Vec::new(); let photos_in = data_dir.join(PHOTOS_DIR); if std::fs::symlink_metadata(&photos_in).is_ok() { - for name in plain_names(&photos_in)? { + for name in photo_names(&photos_in)? { let source = photos_in.join(&name); let target = photos_out.join(&name); let mut out = private_file(&target)?; @@ -149,20 +179,26 @@ async fn write_into(store: &Store, data_dir: &Path, dir: &Path) -> Result<()> { let mut file = private_file(&dir.join(MANIFEST_FILE))?; file.write_all(text.as_bytes())?; file.sync_all()?; + // The MAC is written after the manifest it covers, so a set with a MAC always has its manifest. + let tag = hex::encode(manifest_mac(key, text.as_bytes()).finalize().into_bytes()); + let mut mac_file = private_file(&dir.join(MAC_FILE))?; + mac_file.write_all(tag.as_bytes())?; + mac_file.sync_all()?; std::fs::File::open(&photos_out)?.sync_all()?; std::fs::File::open(dir)?.sync_all()?; Ok(()) } -/// The names of the regular files directly in `dir`. Links and sub-directories are skipped. -fn plain_names(dir: &Path) -> Result> { +/// The names of the photo files directly in `dir` when copying from the data directory. Links, +/// sub-directories and any name that is not a photo name are skipped, so only real photos are backed up. +fn photo_names(dir: &Path) -> Result> { let mut names = Vec::new(); for entry in std::fs::read_dir(dir)? { let entry = entry?; let meta = std::fs::symlink_metadata(entry.path())?; if meta.file_type().is_file() && let Some(name) = entry.file_name().to_str() - && is_plain_name(name) + && is_photo_name(name) { names.push(name.to_owned()); } @@ -171,14 +207,15 @@ fn plain_names(dir: &Path) -> Result> { Ok(names) } -/// True for a name that is one ordinary path component: letters, digits, `-` and `_`, no dots, no -/// separators. Photo files are named by ULID, so anything else is refused. -pub fn is_plain_name(name: &str) -> bool { - !name.is_empty() - && name.len() <= 128 - && name - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +/// Reads a file that must be a regular file, not a link. Returns its bytes. +fn read_regular(path: &Path) -> Result> { + if !std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_file()) { + return Err(Error::Invalid(format!( + "{} is not a regular file", + path.display() + ))); + } + Ok(std::fs::read(path)?) } /// Size and SHA-256 of a file, read in chunks. @@ -239,12 +276,20 @@ pub fn prune(root: &Path, keep: usize) -> Result { Ok(excess) } -/// Reads and checks the shape of a manifest: it must parse, be the known format, and name the snapshot -/// `im.db`. -pub fn read_manifest(set: &Path) -> Result { - let text = std::fs::read_to_string(set.join(MANIFEST_FILE)) +/// Reads a manifest, checking its MAC first. The MAC is compared in constant time over the exact bytes of +/// `manifest.json`, and nothing in the manifest is parsed or trusted until it passes. Then the manifest must +/// parse, be the known format, and name the snapshot `im.db`. +pub fn read_manifest(set: &Path, key: &[u8; 32]) -> Result { + let bytes = read_regular(&set.join(MANIFEST_FILE)) .map_err(|_| Error::Invalid("backup manifest is missing".into()))?; - let manifest: Manifest = serde_json::from_str(&text) + let tag = read_regular(&set.join(MAC_FILE)) + .map_err(|_| Error::Invalid("backup manifest has no MAC".into()))?; + let tag = hex::decode(String::from_utf8_lossy(&tag).trim()) + .map_err(|_| Error::Invalid("backup manifest MAC is not valid".into()))?; + manifest_mac(key, &bytes) + .verify_slice(&tag) + .map_err(|_| Error::Invalid("backup manifest does not match its MAC".into()))?; + let manifest: Manifest = serde_json::from_slice(&bytes) .map_err(|_| Error::Invalid("backup manifest is not valid".into()))?; if manifest.format != FORMAT || manifest.database.name != DB_FILE { return Err(Error::Invalid("backup manifest is not valid".into())); @@ -252,11 +297,12 @@ pub fn read_manifest(set: &Path) -> Result { Ok(manifest) } -/// Checks a set without changing it: every listed file matches its hash, no file is missing or unlisted, -/// and the snapshot passes `PRAGMA integrity_check` with contiguous migrations. The snapshot is checked -/// on a copy in `scratch`, so opening it cannot write WAL files into the set. -pub async fn verify_set(set: &Path, scratch: &Path) -> Result { - let manifest = read_manifest(set)?; +/// Checks a set without changing it: the manifest MAC, every listed file matches its hash, no file is missing +/// or unlisted, every entry in `photos/` is a regular file with a photo name, and the snapshot passes +/// `PRAGMA integrity_check` with contiguous migrations. The snapshot is checked on a copy in `scratch`, so +/// opening it cannot write WAL files into the set. +pub async fn verify_set(set: &Path, scratch: &Path, key: &[u8; 32]) -> Result { + let manifest = read_manifest(set, key)?; check_entry(set, &manifest.database)?; let mut listed = Vec::new(); for photo in &manifest.photos { @@ -265,16 +311,44 @@ pub async fn verify_set(set: &Path, scratch: &Path) -> Result { "backup manifest names a file outside photos".into(), )); }; - if !is_plain_name(id) { + if !is_photo_name(id) { return Err(Error::Invalid("backup manifest names an odd file".into())); } check_entry(set, photo)?; listed.push(id.to_owned()); } - // Nothing may be in the set that the manifest does not name. + // Nothing may be in the set that the manifest does not name. Every entry of photos/ is checked, not + // only the ones that look like photos: a stray name, a dot-file or a link is a refusal. let photos_dir = set.join(PHOTOS_DIR); + // The manifest, its MAC and the snapshot, plus the photo directory when there is one. + let mut expected = 3; if std::fs::symlink_metadata(&photos_dir).is_ok() { - let mut found = plain_names(&photos_dir)?; + if !std::fs::symlink_metadata(&photos_dir)?.file_type().is_dir() { + return Err(Error::Invalid("backup photos is not a directory".into())); + } + expected += 1; + let mut found = Vec::new(); + for entry in std::fs::read_dir(&photos_dir)? { + let entry = entry?; + let name = entry + .file_name() + .into_string() + .map_err(|_| Error::Invalid("backup photos hold an odd file name".into()))?; + if !is_photo_name(&name) { + return Err(Error::Invalid( + "backup photos hold a file that is not a photo".into(), + )); + } + if !std::fs::symlink_metadata(entry.path())? + .file_type() + .is_file() + { + return Err(Error::Invalid( + "backup photos hold a file that is not a regular file".into(), + )); + } + found.push(name); + } listed.sort(); found.sort(); if found != listed { @@ -284,7 +358,6 @@ pub async fn verify_set(set: &Path, scratch: &Path) -> Result { } } let on_disk = std::fs::read_dir(set)?.count(); - let expected = 2 + usize::from(std::fs::symlink_metadata(&photos_dir).is_ok()); if on_disk != expected { return Err(Error::Invalid( "backup set holds files its manifest does not list".into(), @@ -360,6 +433,7 @@ pub async fn restore( database: &Path, set: &Path, stamp: &str, + key: &[u8; 32], ) -> Result { let data_dir = std::fs::canonicalize(data_dir)?; let parent = database @@ -379,7 +453,7 @@ pub async fn restore( ))); } let scratch = data_dir.join(format!(".verify-{stamp}")); - let manifest = verify_set(set, &scratch).await; + let manifest = verify_set(set, &scratch, key).await; let _ = std::fs::remove_dir_all(&scratch); let manifest = manifest?; @@ -387,6 +461,7 @@ pub async fn restore( // The database moves aside with its sidecars; the set's copy is staged and then renamed in. let staged = previous.join("incoming.db"); std::fs::copy(set.join(DB_FILE), &staged)?; + std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o600))?; std::fs::File::open(&staged)?.sync_all()?; for suffix in ["", "-wal", "-shm"] { let mut from = database.as_os_str().to_owned(); @@ -422,6 +497,9 @@ pub async fn restore( mod tests { use super::*; + /// The instance key the test sets are written and checked with. + const KEY: [u8; 32] = [9u8; 32]; + /// A store with one user and one photo, written as a set under `dir`. async fn sample_set(dir: &Path) -> (Store, PathBuf) { let store = Store::open(&dir.join("im.db")).await.unwrap(); @@ -431,9 +509,15 @@ mod tests { .unwrap(); std::fs::create_dir_all(dir.join(PHOTOS_DIR)).unwrap(); std::fs::write(dir.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO"), b"png-bytes").unwrap(); - let set = write_set(&store, dir, &dir.join("backups"), "2026-10-28T10-00-00") - .await - .unwrap(); + let set = write_set( + &store, + dir, + &dir.join("backups"), + "2026-10-28T10-00-00", + &KEY, + ) + .await + .unwrap(); (store, set) } @@ -448,14 +532,14 @@ mod tests { // A changed photo in the set makes the whole set refuse, and nothing is replaced. let photo = set.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO"); std::fs::write(&photo, b"evil-bytes").unwrap(); - assert!(verify_set(&set, &scratch).await.is_err()); - let refused = restore(&data, &data.join("im.db"), &set, "t1").await; + assert!(verify_set(&set, &scratch, &KEY).await.is_err()); + let refused = restore(&data, &data.join("im.db"), &set, "t1", &KEY).await; assert!(refused.is_err()); assert!(!data.join("restore-t1").exists()); // Put the original bytes back: the set verifies and restores. std::fs::write(&photo, b"png-bytes").unwrap(); - let outcome = restore(&data, &data.join("im.db"), &set, "t2") + let outcome = restore(&data, &data.join("im.db"), &set, "t2", &KEY) .await .unwrap(); assert_eq!(outcome.photos, 1); @@ -465,6 +549,23 @@ mod tests { ); } + #[tokio::test] + async fn a_set_is_refused_under_another_key_or_with_a_stray_photo_entry() { + let dir = tempfile::tempdir().unwrap(); + let data = dir.path().join("data"); + std::fs::create_dir_all(&data).unwrap(); + let (_store, set) = sample_set(&data).await; + let scratch = data.join("scratch"); + + // The MAC is keyed: the same set does not verify under any other instance key. + assert!(verify_set(&set, &scratch, &KEY).await.is_ok()); + assert!(verify_set(&set, &scratch, &[1u8; 32]).await.is_err()); + + // A dot-file in photos/ is refused, even though every listed photo is still there. + std::fs::write(set.join(PHOTOS_DIR).join(".stray"), b"x").unwrap(); + assert!(verify_set(&set, &scratch, &KEY).await.is_err()); + } + #[tokio::test] async fn prune_touches_only_real_sets_with_a_manifest() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/im-core/src/oauth.rs b/crates/im-core/src/oauth.rs index 3511491..7bc08a1 100644 --- a/crates/im-core/src/oauth.rs +++ b/crates/im-core/src/oauth.rs @@ -69,8 +69,14 @@ pub fn is_valid_registered_uri(uri: &str) -> bool { let Some((scheme, rest)) = uri.split_once("://") else { return false; }; + // Any `@` before the first `/` after `//` is userinfo, even one that sits where a query would start. + // Such a URI names one host to a reader and another to a browser, so it is refused outright. + let before_path = &rest[..rest.find('/').unwrap_or(rest.len())]; + if before_path.contains('@') { + return false; + } let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())]; - if authority.is_empty() || authority.contains('@') { + if authority.is_empty() { return false; } let host = host_of(authority); @@ -93,6 +99,10 @@ fn is_loopback(host: &str) -> bool { matches!(host, "localhost" | "127.0.0.1" | "::1") } +/// The family key of im's own switcher row. No client may carry it, so a family app can never take the +/// row that names this service. +pub const HOME_KEY: &str = "im"; + /// True for a family key: `^[a-z][a-z0-9-]{0,31}$`, the same rule as `services.key`. pub fn is_valid_family_key(key: &str) -> bool { let bytes = key.as_bytes(); @@ -103,6 +113,12 @@ pub fn is_valid_family_key(key: &str) -> bool { .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-') } +/// True for a family key a client may carry: a valid family key other than [`HOME_KEY`]. The admin page and +/// `im client add` both use this, so the reserved key is refused the same way everywhere. +pub fn is_client_family_key(key: &str) -> bool { + key != HOME_KEY && is_valid_family_key(key) +} + #[cfg(test)] mod tests { use super::*; @@ -127,6 +143,8 @@ mod tests { for bad in [ "http://in.example.com/auth/callback", "https://in.example.com@evil.example/auth/callback", + "https://in.example.com?@evil.example/auth/callback", + "https://in.example.com?x=@evil.example/auth/callback", "https://in.example.com/auth/callback#frag", "https:///auth/callback", "https://in.example.com/a b", diff --git a/crates/im-core/src/photo.rs b/crates/im-core/src/photo.rs index 448185b..9240612 100644 --- a/crates/im-core/src/photo.rs +++ b/crates/im-core/src/photo.rs @@ -97,15 +97,19 @@ fn decode_error(_: image::ImageError) -> Error { /// The file that holds the photo of `user_id`. The id must be a plain identifier, so no id can /// name a path outside the photo directory. pub fn photo_path(data_dir: &Path, user_id: &str) -> Result { - let plain = !user_id.is_empty() - && user_id.len() <= 64 - && user_id.bytes().all(|b| b.is_ascii_alphanumeric()); - if !plain { + if !is_photo_name(user_id) { return Err(Error::Invalid("photo id is not valid".into())); } Ok(data_dir.join(PHOTO_DIR).join(user_id)) } +/// True for a file name the photo directory holds: the user id, 1 to 64 ASCII letters and digits. A +/// name with a separator, a dot, a dash or any other character is never a photo, so backup and restore +/// refuse it. +pub fn is_photo_name(name: &str) -> bool { + !name.is_empty() && name.len() <= 64 && name.bytes().all(|b| b.is_ascii_alphanumeric()) +} + /// Replaces the stored photo of `user_id` with `bytes`, which must already be normalised. /// /// The bytes go to a temporary file in the same directory, which is fsynced and renamed over the diff --git a/crates/im-core/src/secret.rs b/crates/im-core/src/secret.rs index 362a310..ca94f7e 100644 --- a/crates/im-core/src/secret.rs +++ b/crates/im-core/src/secret.rs @@ -59,7 +59,9 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { Ok(key) } -fn read_key(path: &Path) -> Result<[u8; 32]> { +/// Reads an existing instance key, with the same permission check as the start-up load. A missing key is +/// an error here: an operator command that needs the key must not invent one. +pub fn read_key(path: &Path) -> Result<[u8; 32]> { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; diff --git a/crates/im-core/src/store/admin.rs b/crates/im-core/src/store/admin.rs index 5c2d8f2..a248d99 100644 --- a/crates/im-core/src/store/admin.rs +++ b/crates/im-core/src/store/admin.rs @@ -17,7 +17,7 @@ use turso::Row; use crate::error::{Error, Result}; use crate::model::User; use crate::store::backchannel::{self, EndReason}; -use crate::store::clients::{CLIENT_COLS, map_client}; +use crate::store::clients::{CLIENT_COLS, map_client, upsert_service_link}; use crate::store::directory::{ChangeKind, record_change}; use crate::store::invites::{Invite, map_invite}; use crate::store::users::{USER_COLS, map_user}; @@ -190,6 +190,14 @@ impl Store { "the last enabled administrator cannot be deleted".into(), )); } + // Revoked explicitly, not only by the cascade below, so no refresh can succeed for this account + // after the delete, whatever the foreign keys do. + tx.execute( + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL", + (user_id.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; tx.execute( "DELETE FROM settings WHERE key = ?1", (format!("totp_pending:{user_id}"),), @@ -353,21 +361,7 @@ impl Store { client_id: &str, ) -> Result<()> { let conn = self.inner.conn.lock().await; - conn.execute( - "INSERT INTO services (key, name, url, position, client_id) \ - VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), 0) + 1 FROM services), ?4) \ - ON CONFLICT(key) DO UPDATE SET name = excluded.name, url = excluded.url, \ - client_id = excluded.client_id", - ( - key.to_string(), - name.to_string(), - url.to_string(), - client_id.to_string(), - ), - ) - .await - .map_err(db_err)?; - Ok(()) + upsert_service_link(&conn, key, name, url, client_id).await } /// The client with this id, enabled or not. Used by the admin client pages. @@ -467,6 +461,40 @@ impl Store { Ok(changed == 1) } + /// Reads the saved `policy.` values, lets `change` decide which of them to write, and writes those in one + /// transaction. `change` gets the saved values as they are inside the transaction, so a read-modify-write + /// of the policy cannot lose an update made by another request in between. An error from `change` rolls + /// the transaction back and is returned unchanged. + pub async fn update_policy_settings( + &self, + change: impl FnOnce(&[(String, String)]) -> Result>, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let saved = fetch_all( + &tx, + "SELECT key, value FROM settings WHERE substr(key, 1, length('policy.')) = 'policy.' ORDER BY key", + (), + |row: &Row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await?; + let writes = change(&saved)?; + for (key, value) in writes { + tx.execute( + "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \ + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", + (key, value, now_stamp()), + ) + .await + .map_err(db_err)?; + } + Ok(()) + } + .await; + finish(tx, outcome).await + } + /// Removes a setting. Returns false when there was no such setting. pub async fn delete_setting(&self, key: &str) -> Result { let conn = self.inner.conn.lock().await; diff --git a/crates/im-core/src/store/clients.rs b/crates/im-core/src/store/clients.rs index d07231e..153ac6e 100644 --- a/crates/im-core/src/store/clients.rs +++ b/crates/im-core/src/store/clients.rs @@ -4,11 +4,11 @@ //! logout URIs are JSON arrays that are matched exactly, never by prefix. A disabled client keeps its //! row, so its history stays readable, and it authenticates nowhere. -use turso::Row; +use turso::{Connection, Row}; use crate::error::{Error, Result}; use crate::model::Client; -use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; use crate::time::now_stamp; /// The columns of a client row, in the order [`map_client`] reads them. @@ -57,41 +57,99 @@ pub struct NewClient<'a> { pub service_key: Option<&'a str>, } +/// Inserts one client row. A family key that is already used is a conflict. Takes a connection or a +/// transaction, so the same insert serves both the plain and the linked registration. +async fn insert_client(conn: &Connection, id: &str, new: &NewClient<'_>) -> Result<()> { + let now = now_stamp(); + let redirect_uris = + serde_json::to_string(new.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?; + let post_logout = serde_json::to_string(new.post_logout_redirect_uris) + .map_err(|e| Error::Invalid(e.to_string()))?; + conn.execute( + "INSERT INTO clients (id, name, secret_hash, secret_rotated_at, redirect_uris, \ + post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, \ + created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?4)", + ( + id.to_string(), + new.name.to_string(), + new.secret_hash.to_string(), + now, + redirect_uris, + post_logout, + new.backchannel_logout_uri.map(str::to_owned), + new.allowed_scopes.to_string(), + new.service_key.map(str::to_owned), + ), + ) + .await + .map_err(|e| { + if e.to_string().contains("UNIQUE") { + Error::Conflict("that family key is already used by another client".into()) + } else { + db_err(e) + } + })?; + Ok(()) +} + +/// Creates or updates the switcher row of a family key and points it at `client_id`. The caller decides +/// whether it runs alone or inside a transaction. +pub(crate) async fn upsert_service_link( + conn: &Connection, + key: &str, + name: &str, + url: &str, + client_id: &str, +) -> Result<()> { + conn.execute( + "INSERT INTO services (key, name, url, position, client_id) \ + VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), 0) + 1 FROM services), ?4) \ + ON CONFLICT(key) DO UPDATE SET name = excluded.name, url = excluded.url, \ + client_id = excluded.client_id", + ( + key.to_string(), + name.to_string(), + url.to_string(), + client_id.to_string(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) +} + impl Store { /// Registers a client and returns its row. A family key that is already used is a conflict. pub async fn create_client(&self, new: &NewClient<'_>) -> Result { let id = new_id(); - let now = now_stamp(); - let redirect_uris = - serde_json::to_string(new.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?; - let post_logout = serde_json::to_string(new.post_logout_redirect_uris) - .map_err(|e| Error::Invalid(e.to_string()))?; let conn = self.inner.conn.lock().await; - conn.execute( - "INSERT INTO clients (id, name, secret_hash, secret_rotated_at, redirect_uris, \ - post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, \ - created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?4)", - ( - id.clone(), - new.name.to_string(), - new.secret_hash.to_string(), - now, - redirect_uris, - post_logout, - new.backchannel_logout_uri.map(str::to_owned), - new.allowed_scopes.to_string(), - new.service_key.map(str::to_owned), - ), - ) - .await - .map_err(|e| { - if e.to_string().contains("UNIQUE") { - Error::Conflict("that family key is already used by another client".into()) - } else { - db_err(e) - } - })?; + insert_client(&conn, &id, new).await?; + drop(conn); + self.client_by_id(&id).await?.ok_or(Error::NotFound) + } + + /// Registers a family client and creates or updates its switcher row, linked to the client, in one + /// transaction. Either both are written or neither is, so a family key never exists without its + /// switcher link and a link never names a client that failed to register. + pub async fn create_family_client( + &self, + new: &NewClient<'_>, + service_name: &str, + service_url: &str, + ) -> Result { + let id = new_id(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + insert_client(&tx, &id, new).await?; + let key = new + .service_key + .ok_or_else(|| Error::Invalid("a family client needs a family key".into()))?; + upsert_service_link(&tx, key, service_name, service_url, &id).await + } + .await; + finish(tx, outcome).await?; drop(conn); self.client_by_id(&id).await?.ok_or(Error::NotFound) } @@ -120,13 +178,13 @@ impl Store { .await } - /// True when a registered client carries this family key, so the key names a known service. Machine - /// tokens are issued only for known audiences (contracts.md 2.6). + /// True when an enabled client carries this family key, so the key names a known service. Machine + /// tokens are issued only for known audiences (contracts.md 2.6). A disabled client no longer names one. pub async fn family_key_known(&self, key: &str) -> Result { let conn = self.read_conn().await; let found = fetch_opt( &conn, - "SELECT 1 FROM clients WHERE service_key = ?1", + "SELECT 1 FROM clients WHERE service_key = ?1 AND disabled_at IS NULL", (key.to_string(),), |_row| Ok(()), ) diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index 81e5599..ad1dcbc 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -82,6 +82,7 @@ impl Store { apply_query_only(&reader).await?; readers.push(Mutex::new(reader)); } + restrict_database_files(path)?; Ok(Store { inner: Arc::new(Inner { _db: db, @@ -154,6 +155,23 @@ impl Store { } } +/// Makes the database file and its `-wal` and `-shm` sidecars private (mode 0600). They hold every row, +/// including sealed secrets, so no other local user may read them whatever the process umask was. Runs +/// after the connections are open, when the sidecars exist. +fn restrict_database_files(path: &Path) -> Result<()> { + use std::os::unix::fs::PermissionsExt; + + for suffix in ["", "-wal", "-shm"] { + let mut name = path.as_os_str().to_owned(); + name.push(suffix); + let file = std::path::PathBuf::from(name); + if std::fs::symlink_metadata(&file).is_ok_and(|meta| meta.file_type().is_file()) { + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?; + } + } + Ok(()) +} + /// Ends a transaction: commits when `outcome` is `Ok`, rolls back otherwise, and returns the /// outcome. Every multi-statement write ends with this, so no path leaves a transaction open. pub async fn finish(tx: Transaction<'_>, outcome: Result) -> Result { diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 27bcf42..6db3ecc 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -320,6 +320,52 @@ pub fn clear_pending_login(cx: &Cx) { jar(cx).remove(Cookie::build((PENDING_COOKIE, "")).path("/")); } +/// Logical name of the one-time secret cookie. It carries a client secret from the POST that made the secret +/// to the GET that shows it, so the secret never sits in a response to the POST or in a URL. +pub const SECRET_FLASH_COOKIE: &str = "im_secret"; + +/// How long a one-time secret waits in its cookie. Long enough for the redirect to be followed; a secret that +/// is not shown in that time is not kept. +pub const SECRET_FLASH_TTL: Duration = Duration::from_secs(2 * 60); + +/// Parks a client secret for the page that shows it once. The payload is sealed with the instance key, names +/// the client it belongs to, and expires after [`SECRET_FLASH_TTL`]. Same cookie attributes as the pending +/// 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 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)) + .path("/") + .secure(true) + .http_only(true) + .same_site(SameSite::Strict) + .max_age(max_age) + .build(), + ); + Ok(()) +} + +/// Takes the secret parked for `client_id`. The cookie is removed whether or not it matches, so a secret is +/// shown at most once. Returns `None` when the cookie is missing, tampered with, expired or for another client. +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 text = String::from_utf8(plain).ok()?; + let mut parts = text.splitn(3, '|'); + let id = parts.next()?; + let expires: u64 = parts.next()?.parse().ok()?; + let secret = parts.next()?; + (id == client_id && unix_now() < expires).then(|| secret.to_owned()) +} + +/// Removes the one-time secret cookie. +pub fn clear_secret_flash(cx: &Cx) { + jar(cx).remove(Cookie::build((SECRET_FLASH_COOKIE, "")).path("/")); +} + /// Checks one six-digit TOTP code for `user`, with the replay guard. True only when the code is /// valid and its step was not used before. Returns false when two-factor sign-in is off. pub async fn verify_totp(store: &Store, key: &[u8; 32], user: &User, code: &str) -> Result { diff --git a/crates/im-web/src/backchannel.rs b/crates/im-web/src/backchannel.rs index db5a3ce..be2b76a 100644 --- a/crates/im-web/src/backchannel.rs +++ b/crates/im-web/src/backchannel.rs @@ -7,12 +7,16 @@ //! until 24 hours after the row was queued; then it is abandoned and logged. Redirects are never //! followed. A failure never affects the logout that queued the row: that already committed. //! +//! Due rows are delivered a few at a time (see [`DELIVERY_CONCURRENCY`]), so one slow client does not hold up +//! the others. Their outcomes are recorded in the order the rows were due. +//! //! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), a fresh `jti`, the logout //! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. use std::sync::Arc; use std::time::Duration; +use futures_util::{StreamExt, stream}; use im_core::model::Client; use im_core::store::Store; use im_core::store::backchannel::{Attempt, Delivery}; @@ -41,6 +45,10 @@ const TICK: Duration = Duration::from_secs(5); /// The most rows one pass delivers. const BATCH: i64 = 20; +/// How many deliveries run at once. Each waits up to [`DELIVERY_TIMEOUT`] on its client, so they run together +/// and the pass takes about as long as its slowest client, not the sum of all of them. +pub const DELIVERY_CONCURRENCY: usize = 8; + /// How long to wait before the next try after `failures` failed tries (contracts.md 2.5). pub fn backoff(failures: i64) -> Duration { match failures { @@ -95,9 +103,18 @@ pub async fn process_due( now: &str, ) -> im_core::Result { let due = store.due_deliveries(now, BATCH).await?; + // The deliveries are built in a loop and polled `DELIVERY_CONCURRENCY` at a time. `buffered` keeps the + // order of `due`, so the outcomes are recorded oldest first. + let mut pending = Vec::with_capacity(due.len()); for job in &due { - let attempt = deliver(store, key, issuer, http, job).await; - match &attempt { + pending.push(deliver(store, key, issuer, http, job)); + } + let attempts: Vec = stream::iter(pending) + .buffered(DELIVERY_CONCURRENCY) + .collect() + .await; + for (job, attempt) in due.iter().zip(&attempts) { + match attempt { Attempt::Delivered => tracing::info!(row = %job.id, "back-channel logout delivered"), Attempt::Retry { attempts, @@ -112,9 +129,7 @@ pub async fn process_due( "back-channel logout abandoned" ), } - store - .record_attempt(&job.id, &attempt, &now_stamp()) - .await?; + store.record_attempt(&job.id, attempt, &now_stamp()).await?; } Ok(due.len()) } diff --git a/crates/im-web/src/backups.rs b/crates/im-web/src/backups.rs index 457add0..ca0d887 100644 --- a/crates/im-web/src/backups.rs +++ b/crates/im-web/src/backups.rs @@ -44,7 +44,7 @@ pub fn spawn(state: AppState) -> Option> { () = stopped(&mut stop) => break, } if due(&state.store, &state.config).await - && let Err(error) = run_and_record(&state.config, &state.store).await + && let Err(error) = run_and_record(&state.config, &state.store, &state.key).await { tracing::error!(error = %error, "scheduled backup failed"); } @@ -69,7 +69,11 @@ async fn due(store: &Store, config: &Config) -> bool { /// /// The outcome is recorded in `settings`, so the health page can show it. A failure is returned to the /// caller as well, so `im backup now` can exit with status 1. -pub async fn run_and_record(config: &Config, store: &Store) -> im_core::Result { +pub async fn run_and_record( + config: &Config, + store: &Store, + key: &[u8; 32], +) -> im_core::Result { let http = http_client(); let base = config .backup @@ -84,7 +88,7 @@ pub async fn run_and_record(config: &Config, store: &Store) -> im_core::Result { tracing::info!(set = %set.display(), "backup written"); @@ -109,9 +113,10 @@ pub async fn run_and_record(config: &Config, store: &Store) -> im_core::Result im_core::Result { - let set = backup::write_set(store, &config.data_dir, &config.backup.dir, stamp).await?; + let set = backup::write_set(store, &config.data_dir, &config.backup.dir, stamp, key).await?; let removed = backup::prune(&config.backup.dir, config.backup.keep as usize)?; if removed > 0 { tracing::info!(removed, "old backup sets removed"); diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index c19aa52..dadc205 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -33,7 +33,7 @@ use crate::sweeper; use crate::throttle::Throttle; /// Name of the instance key file inside the data directory. -const KEY_FILE: &str = "im.key"; +pub(crate) const KEY_FILE: &str = "im.key"; /// Name of the lock file inside the data directory. The server holds it for its whole life, and so does /// every operator command, so the two never open the database at once. @@ -155,6 +155,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. stop: watch::channel(false).1, + settings_lock: Arc::new(tokio::sync::Mutex::new(())), }) } @@ -165,17 +166,25 @@ pub(crate) async fn effective_policy( config: &im_core::config::Config, store: &Store, ) -> im_core::Result { - let mut policy = config.policy.clone(); - for (key, value) in store.settings_with_prefix("policy.").await? { + let saved = store.settings_with_prefix("policy.").await?; + Ok(merge_saved_policy(&config.policy, &saved)) +} + +/// The policy that the file values and the saved `policy.` values give. A saved value that does not parse +/// or is out of range is logged and ignored, so one bad row cannot keep the server from starting. The +/// settings page calls this on the values it reads inside its transaction. +pub(crate) fn merge_saved_policy(file: &PolicyConfig, saved: &[(String, String)]) -> PolicyConfig { + let mut policy = file.clone(); + for (key, value) in saved { let name = key.trim_start_matches("policy."); - match policy.set(name, &value) { + match policy.set(name, value) { Ok(next) => policy = next, Err(error) => { tracing::warn!(setting = %key, error = %error, "stored policy setting ignored"); } } } - Ok(policy) + policy } /// The request body limit of the photo upload: the picture plus room for the multipart framing and @@ -259,6 +268,7 @@ mod tests { stream_slots: Arc::new(StreamSlots::default()), anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), stop: watch::channel(false).1, + settings_lock: Arc::new(tokio::sync::Mutex::new(())), }; (dir, state) } diff --git a/crates/im-web/src/cli.rs b/crates/im-web/src/cli.rs index 830f828..120afa1 100644 --- a/crates/im-web/src/cli.rs +++ b/crates/im-web/src/cli.rs @@ -12,12 +12,12 @@ use std::process::ExitCode; use im_core::config::Config; use im_core::names::parse_display_name; use im_core::oauth::{ - SUPPORTED_SCOPES, is_supported_scope, is_valid_family_key, is_valid_registered_uri, + SUPPORTED_SCOPES, is_client_family_key, is_supported_scope, is_valid_registered_uri, }; use im_core::store::clients::NewClient; use im_core::token::{generate_token, hash_token}; -use crate::boot::{lock_data_dir, open_state}; +use crate::boot::{KEY_FILE, lock_data_dir, open_state}; use crate::pages::admin::clients::is_origin; use crate::state::AppState; @@ -145,10 +145,10 @@ async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> } } if let Some(key) = &args.family_key - && !is_valid_family_key(key) + && !is_client_family_key(key) { return Err(format!( - "family key {key} must be lowercase letters, digits and hyphens" + "family key {key} must be lowercase letters, digits and hyphens, and not im (the home row)" )); } match (&args.family_key, &args.public_url) { @@ -164,26 +164,22 @@ async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> let scopes = scope_list(args.scopes.as_deref().unwrap_or(DEFAULT_SCOPES))?; let secret = generate_token(); - let client = state - .store - .create_client(&NewClient { - name: &name, - secret_hash: &hash_token(&secret), - redirect_uris: &args.redirect_uris, - post_logout_redirect_uris: &args.post_logout_uris, - backchannel_logout_uri: args.backchannel_uri.as_deref(), - allowed_scopes: &scopes, - service_key: args.family_key.as_deref(), - }) - .await - .map_err(|e| e.to_string())?; - if let (Some(key), Some(url)) = (&args.family_key, &args.public_url) { - state - .store - .link_service(key, &name, url, &client.id) - .await - .map_err(|e| e.to_string())?; + let secret_hash = hash_token(&secret); + let new = NewClient { + name: &name, + secret_hash: &secret_hash, + redirect_uris: &args.redirect_uris, + post_logout_redirect_uris: &args.post_logout_uris, + backchannel_logout_uri: args.backchannel_uri.as_deref(), + allowed_scopes: &scopes, + service_key: args.family_key.as_deref(), + }; + // A family client and its switcher row are written in one transaction, as the admin page does. + let client = match (&args.family_key, &args.public_url) { + (Some(_), Some(url)) => state.store.create_family_client(&new, &name, url).await, + _ => state.store.create_client(&new).await, } + .map_err(|e| e.to_string())?; println!("client_id: {}", client.id); println!("client_secret: {secret}"); eprintln!("im: the client secret is shown once; store it now"); @@ -255,7 +251,7 @@ pub async fn backup(config: &Path, words: &[String]) -> ExitCode { match words { [verb] if verb == "now" => { with_state(config, |state| async move { - let set = crate::backups::run_and_record(&state.config, &state.store) + let set = crate::backups::run_and_record(&state.config, &state.store, &state.key) .await .map_err(|e| e.to_string())?; println!("im: backup written to {}", set.display()); @@ -285,8 +281,12 @@ pub async fn restore(config: &Path, words: &[String]) -> ExitCode { let outcome = async { let config = Config::load(config).map_err(|e| e.to_string())?; let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?; + // The manifest MAC is keyed with the instance key, so a restore needs the key that made the set. A + // missing key is an error: a new key could never verify the set. + let key = im_core::secret::read_key(&config.data_dir.join(KEY_FILE)) + .map_err(|e| e.to_string())?; let stamp = im_core::time::now_stamp().replace([':', '.'], "-"); - im_core::backup::restore(&config.data_dir, &config.database, &set, &stamp) + im_core::backup::restore(&config.data_dir, &config.database, &set, &stamp, &key) .await .map_err(|e| e.to_string()) } @@ -335,7 +335,7 @@ pub async fn keys(config: &Path, words: &[String]) -> ExitCode { .await .map_err(|e| e.to_string())?; println!( - "im: new signing key {kid}; the previous key stays published for the overlap" + "im: new signing key {kid} is published now and starts signing after the publish lead" ); Ok(()) }) diff --git a/crates/im-web/src/i18n/admin.rs b/crates/im-web/src/i18n/admin.rs index 4b71c56..d7f23b3 100644 --- a/crates/im-web/src/i18n/admin.rs +++ b/crates/im-web/src/i18n/admin.rs @@ -613,8 +613,8 @@ fn pair(key: A) -> (&'static str, &'static str) { A::RotateNow => ("Rotate now", "Şimdi döndür"), A::RetireKey => ("Retire", "Emekli yap"), A::NoticeKeyRotated => ( - "A new signing key is current. The old key is retired.", - "Yeni imzalama anahtarı güncel. Eski anahtar emekli yapıldı.", + "A new signing key is published. It starts signing in one day, and the old key signs until then.", + "Yeni imzalama anahtarı yayımlandı. Bir gün sonra imzalamaya başlar; o zamana kadar eski anahtar imzalar.", ), A::NoticeKeyRetired => ( "The key is retired. It stays published for the usual overlap.", diff --git a/crates/im-web/src/mail/message.rs b/crates/im-web/src/mail/message.rs index d57957a..13b649c 100644 --- a/crates/im-web/src/mail/message.rs +++ b/crates/im-web/src/mail/message.rs @@ -69,8 +69,20 @@ impl Sender { } } -/// Builds a `multipart/alternative` message with a plain-text and an HTML part. The subject is the -/// only other text, and it comes from fixed strings. +/// The subject as it goes on the wire: every control character, line breaks included, is removed, and the +/// ends are trimmed, so no subject can end a header early. Enqueueing checks the same thing, but a row +/// written by any other path still cannot break the header, so this runs again right before sending. +pub fn clean_subject(subject: &str) -> String { + subject + .chars() + .filter(|c| !c.is_control()) + .collect::() + .trim() + .to_owned() +} + +/// Builds a `multipart/alternative` message with a plain-text and an HTML part. The subject is cleaned by +/// [`clean_subject`] first. pub fn build( sender: &Sender, to: &Recipient, @@ -81,7 +93,7 @@ pub fn build( Message::builder() .from(sender.mailbox.clone()) .to(to.mailbox()?) - .subject(subject) + .subject(clean_subject(subject)) .multipart(MultiPart::alternative_plain_html(text, html)) .map_err(|_| "message could not be built") } diff --git a/crates/im-web/src/oidc/logout.rs b/crates/im-web/src/oidc/logout.rs index 7c48ad9..13a022c 100644 --- a/crates/im-web/src/oidc/logout.rs +++ b/crates/im-web/src/oidc/logout.rs @@ -94,8 +94,9 @@ async fn verify_hint( if jwt::check_issuer(&claims, issuer).is_err() { return Ok(None); } - // An access token has `azp` and `scope`; an ID token has neither. Only ID tokens are hints. - if claims.contains_key("azp") || claims.contains_key("scope") { + // An access token has `azp` and `scope`; an ID token has neither. Only ID tokens are hints. A logout + // token carries `events` and is never a hint either: it would otherwise pass for an ID token here. + if claims.contains_key("azp") || claims.contains_key("scope") || claims.contains_key("events") { return Ok(None); } let Some(client_id) = jwt::single_audience(&claims) else { diff --git a/crates/im-web/src/oidc/signing.rs b/crates/im-web/src/oidc/signing.rs index 52b2d0c..efb45b1 100644 --- a/crates/im-web/src/oidc/signing.rs +++ b/crates/im-web/src/oidc/signing.rs @@ -13,7 +13,7 @@ use im_core::keys::{self, OVERLAP}; use im_core::model::KeyRecord; use im_core::secret; use im_core::store::Store; -use im_core::time::{now_stamp, stamp_minus}; +use im_core::time::{now_stamp, stamp_minus, stamp_plus}; use serde_json::Value; use tokio::sync::watch; @@ -66,17 +66,21 @@ pub fn spawn( }) } -/// Makes a new key the signing key now. The previous key stops signing at once and stays published for the -/// usual overlap, so tokens it signed still verify. Returns the new key id. +/// 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. pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result { let fresh = keys::generate(); let now = now_stamp(); + 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)?, public_raw: fresh.public.to_vec(), - created_at: now.clone(), - activates_at: now, + created_at: now, + activates_at, retires_at: None, }; store.add_signing_key(&record).await?; diff --git a/crates/im-web/src/pages/admin/clients.rs b/crates/im-web/src/pages/admin/clients.rs index b2f4116..1063dd4 100644 --- a/crates/im-web/src/pages/admin/clients.rs +++ b/crates/im-web/src/pages/admin/clients.rs @@ -2,16 +2,18 @@ //! `/admin/services/{id}`: one client's settings, with rotate and disable. //! //! Registering a client here does what `im client add` does, with the same rules (`check`): the secret is -//! generated, shown once on the page that created it, and only its hash is stored. A family key also -//! needs a public address, because that is the link the switcher shows; the address is kept in the -//! switcher row of the same key. A rejected form is shown again with what was typed in it. +//! generated and only its hash is stored. A family key also needs a public address, because that is the link +//! the switcher shows; the client and that switcher row are written in one transaction. A rejected form is +//! shown again with what was typed in it. //! -//! The rotate action shows the new secret once on the same page, for the same reason. +//! A successful register or rotate is Post/Redirect/Get. The secret travels to the client's page in a short +//! sealed cookie (`auth::set_secret_flash`), and that page shows it once and clears the cookie, so the secret is +//! never in a response to the POST or in a URL. use im_core::Error as CoreError; use im_core::model::{AuditAction, Client, Service}; use im_core::names::parse_display_name; -use im_core::oauth::{is_supported_scope, is_valid_family_key, is_valid_registered_uri}; +use im_core::oauth::{is_client_family_key, is_supported_scope, is_valid_registered_uri}; use im_core::store::admin::ClientEdit; use im_core::store::clients::NewClient; use im_core::token::{generate_token, hash_token}; @@ -20,12 +22,12 @@ use serde_json::json; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; -use topcoat::router::error::{SeeOther, not_found}; +use topcoat::router::error::{SeeOther, not_found, see_other}; use topcoat::router::{page, route}; use topcoat::view::{View, component, view}; use crate::audit::{Actor, record}; -use crate::auth::{require_admin, require_admin_csrf}; +use crate::auth::{require_admin, require_admin_csrf, set_secret_flash, take_secret_flash}; use crate::i18n::Lang; use crate::i18n::admin::{A, text}; use crate::pages::admin::{ @@ -39,9 +41,6 @@ use crate::views::{ViewerInfo, field, shell}; /// The scopes a new client gets when the form leaves them as they are: what a family app signs in with. const DEFAULT_SCOPES: &str = "openid profile email"; -/// The key of im's own switcher row. A family app may not take it. -const HOME_KEY: &str = "im"; - /// The fields of the client form. Every field is text, as typed; [`check`] turns it into values. #[derive(Deserialize, Default, Clone)] struct ClientForm { @@ -114,7 +113,7 @@ fn check(form: &ClientForm) -> std::result::Result { let key = form.family_key.trim(); let family_key = if key.is_empty() { None - } else if key == HOME_KEY || !is_valid_family_key(key) { + } else if !is_client_family_key(key) { return Err("family-key"); } else { Some(key.to_owned()) @@ -199,89 +198,93 @@ async fn services_page(cx: &Cx, Form(query): Form) -> Result) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let (lang, info) = frame_info(cx, &viewer); let state = app_context::(cx); let csrf = viewer.session.csrf_token.clone(); - let mut success = None; - let mut problem = None; - let mut created = None; - let mut shown = ClientForm { - scopes: DEFAULT_SCOPES.to_owned(), - ..ClientForm::default() + let checked = match check(&form) { + Ok(checked) => checked, + Err(code) => return services_again(cx, lang, info, csrf, form, code).await, }; - match check(&form) { - Err(code) => { - problem = error_text(lang, code).map(str::to_owned); - shown = ClientForm { - csrf: String::new(), - ..form - }; - } - Ok(checked) => { - let secret = generate_token(); - match state + let secret = generate_token(); + let secret_hash = hash_token(&secret); + let new = NewClient { + name: &checked.name, + secret_hash: &secret_hash, + redirect_uris: &checked.redirect_uris, + post_logout_redirect_uris: &checked.post_logout_uris, + backchannel_logout_uri: checked.backchannel_uri.as_deref(), + allowed_scopes: &checked.scopes, + service_key: checked.family_key.as_deref(), + }; + // A family client and its switcher row are one transaction, so neither exists without the other. + let registered = match (&checked.family_key, &checked.public_url) { + (Some(_), Some(url)) => { + state .store - .create_client(&NewClient { - name: &checked.name, - secret_hash: &hash_token(&secret), - redirect_uris: &checked.redirect_uris, - post_logout_redirect_uris: &checked.post_logout_uris, - backchannel_logout_uri: checked.backchannel_uri.as_deref(), - allowed_scopes: &checked.scopes, - service_key: checked.family_key.as_deref(), - }) + .create_family_client(&new, &checked.name, url) .await - { - Ok(client) => { - if let (Some(key), Some(url)) = (&checked.family_key, &checked.public_url) { - state - .store - .link_service(key, &checked.name, url, &client.id) - .await?; - } - record( - cx, - Actor::User(&viewer.user.id), - AuditAction::ClientCreated, - Some(("client", &client.id)), - json!({ "family": checked.family_key.is_some() }), - ) - .await; - changed(&state.live); - success = Some(text(lang, A::ClientSaved).to_owned()); - created = Some(Created { - id: client.id, - name: client.name, - secret, - }); - } - Err(CoreError::Conflict(_)) => { - problem = error_text(lang, "family-taken").map(str::to_owned); - shown = ClientForm { - csrf: String::new(), - ..form - }; - } - Err(error) => return Err(error.into()), - } } - } + _ => state.store.create_client(&new).await, + }; + let client = match registered { + Ok(client) => client, + Err(CoreError::Conflict(_)) => { + return services_again(cx, lang, info, csrf, form, "family-taken").await; + } + Err(error) => return Err(error.into()), + }; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::ClientCreated, + Some(("client", &client.id)), + json!({ "family": checked.family_key.is_some() }), + ) + .await; + changed(&state.live); + set_secret_flash(cx, &state.key, &client.id, &secret)?; + Err(see_other(format!("/admin/services/{}?notice=client-saved", client.id)).into()) +} + +/// The services page again, with the form as it was typed and the reason it was refused. The arguments are +/// owned, because the view is returned from the handler and must not borrow from it. +async fn services_again( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + form: ClientForm, + code: &str, +) -> Result { + let state = app_context::(cx); let services = state.store.list_services().await?; let clients = state.store.list_clients().await?; + let shown = ClientForm { + csrf: String::new(), + ..form + }; Ok(services_view( - cx, lang, info, csrf, services, clients, shown, success, problem, created, + cx, + lang, + info, + csrf, + services, + clients, + shown, + None, + error_text(lang, code).map(str::to_owned), )) } -/// What the page shows once about a new client: its id and its secret. +/// What the page shows once about a client whose secret was just made: its id, its name and the secret. struct Created { id: String, name: String, @@ -296,6 +299,13 @@ async fn client_page(cx: &Cx, Form(query): Form) -> Result) -> Result) -> Result Ok(done(&base, "client-saved")) } -/// `POST /admin/services/{id}/rotate`. The old secret stops working at once; the new one is shown here, once. -#[page(POST "/admin/services/{id}/rotate")] -async fn rotate_secret(cx: &Cx, Form(form): Form) -> Result { +/// `POST /admin/services/{id}/rotate`. The old secret stops working at once. The new one is shown once on the +/// client's page, which this redirect leads to. +#[route(POST "/admin/services/{id}/rotate")] +async fn rotate_secret(cx: &Cx, Form(form): Form) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; - let (lang, info) = frame_info(cx, &viewer); let state = app_context::(cx); let client = client_from_path(cx, state).await?; let secret = generate_token(); @@ -399,23 +409,11 @@ async fn rotate_secret(cx: &Cx, Form(form): Form) -> Result ) .await; changed(&state.live); - let public_url = public_url_of(state, &client).await?; - let created = Created { - id: client.id.clone(), - name: client.name.clone(), - secret, - }; - Ok(detail_view( - cx, - lang, - info, - viewer.session.csrf_token.clone(), - client, - public_url, - Some(text(lang, A::NoticeSecretRotated).to_owned()), - None, - Some(created), - )) + set_secret_flash(cx, &state.key, &client.id, &secret)?; + Ok(see_other(format!( + "/admin/services/{}?notice=secret-rotated", + client.id + ))) } /// `POST /admin/services/{id}/disable`. A disabled client cannot sign in or exchange tokens. @@ -452,7 +450,6 @@ fn services_view( form: ClientForm, success: Option, problem: Option, - created: Option, ) -> impl View { view! { cx => shell(title: text(lang, A::ServicesTitle), lang: lang, viewer: Some(info), @@ -461,9 +458,6 @@ fn services_view(

(text(lang, A::ServicesTitle))

(text(lang, A::ServicesIntro))

flash_messages(success: success, problem: problem) - if let Some(created) = created { - secret_box(lang: lang, created: created) - }

(text(lang, A::ServicesList))

if services.is_empty() {

(text(lang, A::NoServices))

diff --git a/crates/im-web/src/pages/admin/settings.rs b/crates/im-web/src/pages/admin/settings.rs index 73b420b..eba7817 100644 --- a/crates/im-web/src/pages/admin/settings.rs +++ b/crates/im-web/src/pages/admin/settings.rs @@ -21,7 +21,7 @@ use topcoat::view::{View, component, view}; use crate::audit::{Actor, record}; use crate::auth::{require_admin, require_admin_csrf}; -use crate::boot::effective_policy; +use crate::boot::{effective_policy, merge_saved_policy}; use crate::i18n::Lang; use crate::i18n::admin::{A, text}; use crate::pages::admin::{ @@ -167,36 +167,48 @@ async fn settings_page(cx: &Cx, Form(query): Form) -> Result) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let state = app_context::(cx); - let current = state.policy(); - let mut next = current.clone(); - let mut changed_keys: Vec<(&'static str, String)> = Vec::new(); - for (key, typed) in form.values() { - let typed = typed.trim(); - if typed == value_of(¤t, key) { - continue; + let names = { + let _guard = state.settings_lock.lock().await; + let mut names: Vec<&'static str> = Vec::new(); + let outcome = state + .store + .update_policy_settings(|saved| { + let current = merge_saved_policy(&state.config.policy, saved); + let mut next = current.clone(); + let mut writes = Vec::new(); + for (key, typed) in form.values() { + let typed = typed.trim(); + if typed == value_of(¤t, key) { + continue; + } + next = next.set(key, typed)?; + names.push(key); + writes.push((format!("policy.{key}"), typed.to_owned())); + } + Ok(writes) + }) + .await; + match outcome { + Ok(()) => {} + Err(im_core::Error::Invalid(_)) => return Ok(refused("/admin/settings", "settings")), + Err(error) => return Err(error.into()), } - next = match next.set(key, typed) { - Ok(policy) => policy, - Err(_) => return Ok(refused("/admin/settings", "settings")), - }; - changed_keys.push((key, typed.to_owned())); - } - if changed_keys.is_empty() { + if !names.is_empty() { + // Refreshed from the committed rows, not from the values typed, so memory matches the database. + let policy = effective_policy(&state.config, &state.store).await?; + state.set_policy(policy); + } + names + }; + if names.is_empty() { return Ok(done("/admin/settings", "settings-saved")); } - for (key, value) in &changed_keys { - state - .store - .set_setting(&format!("policy.{key}"), value) - .await?; - } - state.set_policy(next); - let names: Vec<&str> = changed_keys.iter().map(|(key, _)| *key).collect(); record( cx, Actor::User(&viewer.user.id), @@ -218,9 +230,12 @@ async fn reset_setting(cx: &Cx, Form(form): Form) -> Result return Err(not_found().into()); }; let state = app_context::(cx); - state.store.delete_setting(&format!("policy.{key}")).await?; - let policy = effective_policy(&state.config, &state.store).await?; - state.set_policy(policy); + { + let _guard = state.settings_lock.lock().await; + state.store.delete_setting(&format!("policy.{key}")).await?; + let policy = effective_policy(&state.config, &state.store).await?; + state.set_policy(policy); + } record( cx, Actor::User(&viewer.user.id), diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs index 18383e8..a95857f 100644 --- a/crates/im-web/src/state.rs +++ b/crates/im-web/src/state.rs @@ -33,6 +33,9 @@ pub struct AppState { pub anonymous_streams: Arc, /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain. pub stop: watch::Receiver, + /// Held by every change to the saved policy, from the write to the refresh of `policy_live`. Two saves + /// then run one after the other, and the in-memory policy always matches what the database last committed. + pub settings_lock: Arc>, } impl AppState { diff --git a/docs/conventions.md b/docs/conventions.md index 12c49e4..eed1b03 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -61,8 +61,9 @@ tokens, passwords, cookies, or secrets. - Constraints live in the schema (`NOT NULL`, `CHECK`, `UNIQUE`, `REFERENCES ... ON DELETE ...`), not only in Rust. - Backups: `snapshot_to(path)` with `VACUUM INTO` on the writer, then checkpoint the copy so it is one self-contained file, then fsync. `admin backup --out DIR` writes the snapshot, the blob tree (where the app - has one) and a `manifest.json` with a sha256 per file. `admin backup-verify SET` checks hashes, - `integrity_check` and contiguous migrations. Never copy a live DB file. + has one), a `manifest.json` with a sha256 per file and a `manifest.mac`: HMAC-SHA256 of the manifest bytes + under a subkey of the instance key, which lives outside the backup. Verify and restore check the MAC first + (constant time), then hashes, `integrity_check` and contiguous migrations. Never copy a live DB file. ## 5. HTTP and pages