forge
Explore
Log in

Don't you dare go Hollow

Backup manifest MAC, settings save in one transaction, family key im refused in core, client secrets shown after redirect, client and link in one transaction, photo names checked on restore, im.db 0600, mail subject re-sanitized, OIDC lows

Browse files at this commit

924d542422981f3742cf9c04c950d327fc592604Ahmet Kaan GümüşParent: adfb39f
  • fix
    • backup manifest MAC, settings save in one transaction, family key im refused in core, client secrets shown after redirect, client and link in one transaction, photo names checked on restore, im.db 0600, mail subject re-sanitized, OIDC lows
Show full message
🔒 fix: backup manifest MAC, settings save in one transaction, family key im refused in core, client secrets shown after redirect, client and link in one transaction, photo names checked on restore, im.db 0600, mail subject re-sanitized, OIDC lows
crates/im-core/src/backup.rsmodified+149 -48
@@ -1,37 +1,49 @@
1 //! Backup sets, verification, pruning and restore.1 //! Backup sets, verification, pruning and restore.
2 //!2 //!
3 //! A set is a directory `set-<stamp>` under the backup root. It holds `im.db` (a consistent snapshot of the3 //! A set is a directory `set-<stamp>` under the backup root. It holds `im.db` (a consistent snapshot of the
4-//! database, see `store/snapshot.rs`), a `photos/` directory with a copy of every profile photo, and4+//! database, see `store/snapshot.rs`), a `photos/` directory with a copy of every profile photo,
5-//! `manifest.json`. The manifest names every file with its size and SHA-256. A set is written under a5+//! `manifest.json`, and `manifest.mac`. The manifest names every file with its size and SHA-256. The MAC is
6-//! temporary name and renamed into place only when its manifest is complete, so a half-written set is6+//! HMAC-SHA256 over the exact manifest bytes, keyed with a subkey of the instance key, so a manifest cannot be
7-//! never mistaken for a good one.7+//! rewritten to match changed files. A set is written under a temporary name and renamed into place only when
8+//! its manifest and MAC are complete, so a half-written set is never mistaken for a good one.
8 //!9 //!
9-//! Verification checks every hash, refuses a file the manifest does not list (in the set or in `photos/`),10+//! Verification checks the MAC first, in constant time, and reads nothing else from the manifest until it
10-//! refuses a name that is not a plain file name, and runs `PRAGMA integrity_check` and the migration11+//! passes. Then it checks every hash, refuses a file the manifest does not list, refuses any entry in `photos/`
11-//! check on a scratch copy, so the set itself is never written to. Restore verifies first and changes12+//! that is not a photo name (see `photo::is_photo_name`) or not a regular file, and runs `PRAGMA
12-//! nothing when verification fails. It only replaces a database and a photo directory that lie inside the13+//! integrity_check` and the migration check on a scratch copy, so the set itself is never written to. Restore
13-//! data directory, and it moves what it replaces into `data_dir/restore-<stamp>/` rather than deleting it.14+//! verifies first and changes nothing when verification fails. It only replaces a database and a photo
14-//! The caller must hold the data-directory lock: a running server is never restored under.15+//! directory that lie inside the data directory, and it moves what it replaces into `data_dir/restore-<stamp>/`
16+//! rather than deleting it. The caller must hold the data-directory lock: a running server is never restored
17+//! under.
15 18
16 use std::fs::OpenOptions;19 use std::fs::OpenOptions;
17 use std::io::{Read, Write};20 use std::io::{Read, Write};
18-use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};21+use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
19 use std::path::{Path, PathBuf};22 use std::path::{Path, PathBuf};
20 23
24+use hmac::{Hmac, KeyInit, Mac};
21 use serde::{Deserialize, Serialize};25 use serde::{Deserialize, Serialize};
22 use sha2::{Digest, Sha256};26 use sha2::{Digest, Sha256};
23 use turso::Builder;27 use turso::Builder;
24 28
25 use crate::error::{Error, Result};29 use crate::error::{Error, Result};
30+use crate::photo::is_photo_name;
26 use crate::store::migrate::MIGRATIONS;31 use crate::store::migrate::MIGRATIONS;
27 use crate::store::{Store, col_int, col_text, db_err, fetch_all};32 use crate::store::{Store, col_int, col_text, db_err, fetch_all};
28 33
34+type HmacSha256 = Hmac<Sha256>;
35+
29 /// The only manifest format this build reads and writes.36 /// The only manifest format this build reads and writes.
30 pub const FORMAT: u32 = 1;37 pub const FORMAT: u32 = 1;
31 /// Name of the snapshot inside a set.38 /// Name of the snapshot inside a set.
32 pub const DB_FILE: &str = "im.db";39 pub const DB_FILE: &str = "im.db";
33 /// Name of the manifest inside a set.40 /// Name of the manifest inside a set.
34 pub const MANIFEST_FILE: &str = "manifest.json";41 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+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+/// way recovery codes derive theirs, so the instance key itself keys only that derivation.
46+const MAC_SUBKEY_LABEL: &[u8] = b"im backup manifest v1";
35 /// Name of the photo directory inside a set, and beside the database in the data directory.47 /// Name of the photo directory inside a set, and beside the database in the data directory.
36 pub const PHOTOS_DIR: &str = "photos";48 pub const PHOTOS_DIR: &str = "photos";
37 /// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix.49 /// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix.
@@ -70,6 +82,20 @@ pub struct RestoreOutcome {
70 pub previous: PathBuf,82 pub previous: PathBuf,
71 }83 }
72 84
85+/// 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+fn manifest_mac(key: &[u8; 32], bytes: &[u8]) -> HmacSha256 {
88+ // 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 =
94+ <HmacSha256 as KeyInit>::new_from_slice(&subkey).expect("HMAC takes any key length");
95+ mac.update(bytes);
96+ mac
97+}
98+
73 /// Creates a directory that only this user may enter.99 /// Creates a directory that only this user may enter.
74 fn private_dir(path: &Path) -> Result<()> {100 fn private_dir(path: &Path) -> Result<()> {
75 std::fs::DirBuilder::new()101 std::fs::DirBuilder::new()
@@ -89,12 +115,14 @@ fn private_file(path: &Path) -> Result<std::fs::File> {
89 }115 }
90 116
91 /// Writes a complete set under `root` and returns its directory. `stamp` names it and must be safe in a117 /// Writes a complete set under `root` and returns its directory. `stamp` names it and must be safe in a
92-/// file name: callers replace `:` and `.` in the time stamp.118+/// file name: callers replace `:` and `.` in the time stamp. `key` is the instance key that keys the manifest
119+/// MAC.
93 pub async fn write_set(120 pub async fn write_set(
94 store: &Store,121 store: &Store,
95 data_dir: &Path,122 data_dir: &Path,
96 root: &Path,123 root: &Path,
97 stamp: &str,124 stamp: &str,
125+ key: &[u8; 32],
98 ) -> Result<PathBuf> {126 ) -> Result<PathBuf> {
99 std::fs::create_dir_all(root)?;127 std::fs::create_dir_all(root)?;
100 let tmp = root.join(format!(".tmp-{stamp}"));128 let tmp = root.join(format!(".tmp-{stamp}"));
@@ -103,7 +131,7 @@ pub async fn write_set(
103 return Err(Error::Conflict(format!("set {stamp} already exists")));131 return Err(Error::Conflict(format!("set {stamp} already exists")));
104 }132 }
105 private_dir(&tmp)?;133 private_dir(&tmp)?;
106- match write_into(store, data_dir, &tmp).await {134+ match write_into(store, data_dir, &tmp, key).await {
107 Ok(()) => {135 Ok(()) => {
108 std::fs::rename(&tmp, &final_dir)?;136 std::fs::rename(&tmp, &final_dir)?;
109 Ok(final_dir)137 Ok(final_dir)
@@ -116,10 +144,12 @@ pub async fn write_set(
116 }144 }
117 }145 }
118 146
119-/// Fills `dir` with the snapshot, the photos and the manifest, then fsyncs the directory.147+/// Fills `dir` with the snapshot, the photos, the manifest and its MAC, then fsyncs the directory.
120-async fn write_into(store: &Store, data_dir: &Path, dir: &Path) -> Result<()> {148+async fn write_into(store: &Store, data_dir: &Path, dir: &Path, key: &[u8; 32]) -> Result<()> {
121 let db_path = dir.join(DB_FILE);149 let db_path = dir.join(DB_FILE);
122 store.snapshot_to(&db_path).await?;150 store.snapshot_to(&db_path).await?;
151+ // The snapshot holds every row, so it is private like the live database.
152+ std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o600))?;
123 let database = file_entry(DB_FILE, &db_path)?;153 let database = file_entry(DB_FILE, &db_path)?;
124 154
125 let photos_out = dir.join(PHOTOS_DIR);155 let photos_out = dir.join(PHOTOS_DIR);
@@ -127,7 +157,7 @@ async fn write_into(store: &Store, data_dir: &Path, dir: &Path) -> Result<()> {
127 let mut photos = Vec::new();157 let mut photos = Vec::new();
128 let photos_in = data_dir.join(PHOTOS_DIR);158 let photos_in = data_dir.join(PHOTOS_DIR);
129 if std::fs::symlink_metadata(&photos_in).is_ok() {159 if std::fs::symlink_metadata(&photos_in).is_ok() {
130- for name in plain_names(&photos_in)? {160+ for name in photo_names(&photos_in)? {
131 let source = photos_in.join(&name);161 let source = photos_in.join(&name);
132 let target = photos_out.join(&name);162 let target = photos_out.join(&name);
133 let mut out = private_file(&target)?;163 let mut out = private_file(&target)?;
@@ -149,20 +179,26 @@ async fn write_into(store: &Store, data_dir: &Path, dir: &Path) -> Result<()> {
149 let mut file = private_file(&dir.join(MANIFEST_FILE))?;179 let mut file = private_file(&dir.join(MANIFEST_FILE))?;
150 file.write_all(text.as_bytes())?;180 file.write_all(text.as_bytes())?;
151 file.sync_all()?;181 file.sync_all()?;
182+ // The MAC is written after the manifest it covers, so a set with a MAC always has its manifest.
183+ let tag = hex::encode(manifest_mac(key, text.as_bytes()).finalize().into_bytes());
184+ let mut mac_file = private_file(&dir.join(MAC_FILE))?;
185+ mac_file.write_all(tag.as_bytes())?;
186+ mac_file.sync_all()?;
152 std::fs::File::open(&photos_out)?.sync_all()?;187 std::fs::File::open(&photos_out)?.sync_all()?;
153 std::fs::File::open(dir)?.sync_all()?;188 std::fs::File::open(dir)?.sync_all()?;
154 Ok(())189 Ok(())
155 }190 }
156 191
157-/// The names of the regular files directly in `dir`. Links and sub-directories are skipped.192+/// The names of the photo files directly in `dir` when copying from the data directory. Links,
158-fn plain_names(dir: &Path) -> Result<Vec<String>> {193+/// sub-directories and any name that is not a photo name are skipped, so only real photos are backed up.
194+fn photo_names(dir: &Path) -> Result<Vec<String>> {
159 let mut names = Vec::new();195 let mut names = Vec::new();
160 for entry in std::fs::read_dir(dir)? {196 for entry in std::fs::read_dir(dir)? {
161 let entry = entry?;197 let entry = entry?;
162 let meta = std::fs::symlink_metadata(entry.path())?;198 let meta = std::fs::symlink_metadata(entry.path())?;
163 if meta.file_type().is_file()199 if meta.file_type().is_file()
164 && let Some(name) = entry.file_name().to_str()200 && let Some(name) = entry.file_name().to_str()
165- && is_plain_name(name)201+ && is_photo_name(name)
166 {202 {
167 names.push(name.to_owned());203 names.push(name.to_owned());
168 }204 }
@@ -171,14 +207,15 @@ fn plain_names(dir: &Path) -> Result<Vec<String>> {
171 Ok(names)207 Ok(names)
172 }208 }
173 209
174-/// True for a name that is one ordinary path component: letters, digits, `-` and `_`, no dots, no210+/// Reads a file that must be a regular file, not a link. Returns its bytes.
175-/// separators. Photo files are named by ULID, so anything else is refused.211+fn read_regular(path: &Path) -> Result<Vec<u8>> {
176-pub fn is_plain_name(name: &str) -> bool {212+ if !std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_file()) {
177- !name.is_empty()213+ return Err(Error::Invalid(format!(
178- && name.len() <= 128214+ "{} is not a regular file",
179- && name215+ path.display()
180- .bytes()216+ )));
181- .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')217+ }
218+ Ok(std::fs::read(path)?)
182 }219 }
183 220
184 /// Size and SHA-256 of a file, read in chunks.221 /// Size and SHA-256 of a file, read in chunks.
@@ -239,12 +276,20 @@ pub fn prune(root: &Path, keep: usize) -> Result<usize> {
239 Ok(excess)276 Ok(excess)
240 }277 }
241 278
242-/// Reads and checks the shape of a manifest: it must parse, be the known format, and name the snapshot279+/// Reads a manifest, checking its MAC first. The MAC is compared in constant time over the exact bytes of
243-/// `im.db`.280+/// `manifest.json`, and nothing in the manifest is parsed or trusted until it passes. Then the manifest must
244-pub fn read_manifest(set: &Path) -> Result<Manifest> {281+/// parse, be the known format, and name the snapshot `im.db`.
245- let text = std::fs::read_to_string(set.join(MANIFEST_FILE))282+pub fn read_manifest(set: &Path, key: &[u8; 32]) -> Result<Manifest> {
283+ let bytes = read_regular(&set.join(MANIFEST_FILE))
246 .map_err(|_| Error::Invalid("backup manifest is missing".into()))?;284 .map_err(|_| Error::Invalid("backup manifest is missing".into()))?;
247- let manifest: Manifest = serde_json::from_str(&text)285+ let tag = read_regular(&set.join(MAC_FILE))
286+ .map_err(|_| Error::Invalid("backup manifest has no MAC".into()))?;
287+ let tag = hex::decode(String::from_utf8_lossy(&tag).trim())
288+ .map_err(|_| Error::Invalid("backup manifest MAC is not valid".into()))?;
289+ manifest_mac(key, &bytes)
290+ .verify_slice(&tag)
291+ .map_err(|_| Error::Invalid("backup manifest does not match its MAC".into()))?;
292+ let manifest: Manifest = serde_json::from_slice(&bytes)
248 .map_err(|_| Error::Invalid("backup manifest is not valid".into()))?;293 .map_err(|_| Error::Invalid("backup manifest is not valid".into()))?;
249 if manifest.format != FORMAT || manifest.database.name != DB_FILE {294 if manifest.format != FORMAT || manifest.database.name != DB_FILE {
250 return Err(Error::Invalid("backup manifest is not valid".into()));295 return Err(Error::Invalid("backup manifest is not valid".into()));
@@ -252,11 +297,12 @@ pub fn read_manifest(set: &Path) -> Result<Manifest> {
252 Ok(manifest)297 Ok(manifest)
253 }298 }
254 299
255-/// Checks a set without changing it: every listed file matches its hash, no file is missing or unlisted,300+/// Checks a set without changing it: the manifest MAC, every listed file matches its hash, no file is missing
256-/// and the snapshot passes `PRAGMA integrity_check` with contiguous migrations. The snapshot is checked301+/// or unlisted, every entry in `photos/` is a regular file with a photo name, and the snapshot passes
257-/// on a copy in `scratch`, so opening it cannot write WAL files into the set.302+/// `PRAGMA integrity_check` with contiguous migrations. The snapshot is checked on a copy in `scratch`, so
258-pub async fn verify_set(set: &Path, scratch: &Path) -> Result<Manifest> {303+/// opening it cannot write WAL files into the set.
259- let manifest = read_manifest(set)?;304+pub async fn verify_set(set: &Path, scratch: &Path, key: &[u8; 32]) -> Result<Manifest> {
305+ let manifest = read_manifest(set, key)?;
260 check_entry(set, &manifest.database)?;306 check_entry(set, &manifest.database)?;
261 let mut listed = Vec::new();307 let mut listed = Vec::new();
262 for photo in &manifest.photos {308 for photo in &manifest.photos {
@@ -265,16 +311,44 @@ pub async fn verify_set(set: &Path, scratch: &Path) -> Result<Manifest> {
265 "backup manifest names a file outside photos".into(),311 "backup manifest names a file outside photos".into(),
266 ));312 ));
267 };313 };
268- if !is_plain_name(id) {314+ if !is_photo_name(id) {
269 return Err(Error::Invalid("backup manifest names an odd file".into()));315 return Err(Error::Invalid("backup manifest names an odd file".into()));
270 }316 }
271 check_entry(set, photo)?;317 check_entry(set, photo)?;
272 listed.push(id.to_owned());318 listed.push(id.to_owned());
273 }319 }
274- // Nothing may be in the set that the manifest does not name.320+ // Nothing may be in the set that the manifest does not name. Every entry of photos/ is checked, not
321+ // only the ones that look like photos: a stray name, a dot-file or a link is a refusal.
275 let photos_dir = set.join(PHOTOS_DIR);322 let photos_dir = set.join(PHOTOS_DIR);
323+ // The manifest, its MAC and the snapshot, plus the photo directory when there is one.
324+ let mut expected = 3;
276 if std::fs::symlink_metadata(&photos_dir).is_ok() {325 if std::fs::symlink_metadata(&photos_dir).is_ok() {
277- let mut found = plain_names(&photos_dir)?;326+ if !std::fs::symlink_metadata(&photos_dir)?.file_type().is_dir() {
327+ return Err(Error::Invalid("backup photos is not a directory".into()));
328+ }
329+ expected += 1;
330+ let mut found = Vec::new();
331+ for entry in std::fs::read_dir(&photos_dir)? {
332+ let entry = entry?;
333+ let name = entry
334+ .file_name()
335+ .into_string()
336+ .map_err(|_| Error::Invalid("backup photos hold an odd file name".into()))?;
337+ if !is_photo_name(&name) {
338+ return Err(Error::Invalid(
339+ "backup photos hold a file that is not a photo".into(),
340+ ));
341+ }
342+ if !std::fs::symlink_metadata(entry.path())?
343+ .file_type()
344+ .is_file()
345+ {
346+ return Err(Error::Invalid(
347+ "backup photos hold a file that is not a regular file".into(),
348+ ));
349+ }
350+ found.push(name);
351+ }
278 listed.sort();352 listed.sort();
279 found.sort();353 found.sort();
280 if found != listed {354 if found != listed {
@@ -284,7 +358,6 @@ pub async fn verify_set(set: &Path, scratch: &Path) -> Result<Manifest> {
284 }358 }
285 }359 }
286 let on_disk = std::fs::read_dir(set)?.count();360 let on_disk = std::fs::read_dir(set)?.count();
287- let expected = 2 + usize::from(std::fs::symlink_metadata(&photos_dir).is_ok());
288 if on_disk != expected {361 if on_disk != expected {
289 return Err(Error::Invalid(362 return Err(Error::Invalid(
290 "backup set holds files its manifest does not list".into(),363 "backup set holds files its manifest does not list".into(),
@@ -360,6 +433,7 @@ pub async fn restore(
360 database: &Path,433 database: &Path,
361 set: &Path,434 set: &Path,
362 stamp: &str,435 stamp: &str,
436+ key: &[u8; 32],
363 ) -> Result<RestoreOutcome> {437 ) -> Result<RestoreOutcome> {
364 let data_dir = std::fs::canonicalize(data_dir)?;438 let data_dir = std::fs::canonicalize(data_dir)?;
365 let parent = database439 let parent = database
@@ -379,7 +453,7 @@ pub async fn restore(
379 )));453 )));
380 }454 }
381 let scratch = data_dir.join(format!(".verify-{stamp}"));455 let scratch = data_dir.join(format!(".verify-{stamp}"));
382- let manifest = verify_set(set, &scratch).await;456+ let manifest = verify_set(set, &scratch, key).await;
383 let _ = std::fs::remove_dir_all(&scratch);457 let _ = std::fs::remove_dir_all(&scratch);
384 let manifest = manifest?;458 let manifest = manifest?;
385 459
@@ -387,6 +461,7 @@ pub async fn restore(
387 // The database moves aside with its sidecars; the set's copy is staged and then renamed in.461 // The database moves aside with its sidecars; the set's copy is staged and then renamed in.
388 let staged = previous.join("incoming.db");462 let staged = previous.join("incoming.db");
389 std::fs::copy(set.join(DB_FILE), &staged)?;463 std::fs::copy(set.join(DB_FILE), &staged)?;
464+ std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o600))?;
390 std::fs::File::open(&staged)?.sync_all()?;465 std::fs::File::open(&staged)?.sync_all()?;
391 for suffix in ["", "-wal", "-shm"] {466 for suffix in ["", "-wal", "-shm"] {
392 let mut from = database.as_os_str().to_owned();467 let mut from = database.as_os_str().to_owned();
@@ -422,6 +497,9 @@ pub async fn restore(
422 mod tests {497 mod tests {
423 use super::*;498 use super::*;
424 499
500+ /// The instance key the test sets are written and checked with.
501+ const KEY: [u8; 32] = [9u8; 32];
502+
425 /// A store with one user and one photo, written as a set under `dir`.503 /// A store with one user and one photo, written as a set under `dir`.
426 async fn sample_set(dir: &Path) -> (Store, PathBuf) {504 async fn sample_set(dir: &Path) -> (Store, PathBuf) {
427 let store = Store::open(&dir.join("im.db")).await.unwrap();505 let store = Store::open(&dir.join("im.db")).await.unwrap();
@@ -431,9 +509,15 @@ mod tests {
431 .unwrap();509 .unwrap();
432 std::fs::create_dir_all(dir.join(PHOTOS_DIR)).unwrap();510 std::fs::create_dir_all(dir.join(PHOTOS_DIR)).unwrap();
433 std::fs::write(dir.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO"), b"png-bytes").unwrap();511 std::fs::write(dir.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO"), b"png-bytes").unwrap();
434- let set = write_set(&store, dir, &dir.join("backups"), "2026-10-28T10-00-00")512+ let set = write_set(
435- .await513+ &store,
436- .unwrap();514+ dir,
515+ &dir.join("backups"),
516+ "2026-10-28T10-00-00",
517+ &KEY,
518+ )
519+ .await
520+ .unwrap();
437 (store, set)521 (store, set)
438 }522 }
439 523
@@ -448,14 +532,14 @@ mod tests {
448 // A changed photo in the set makes the whole set refuse, and nothing is replaced.532 // A changed photo in the set makes the whole set refuse, and nothing is replaced.
449 let photo = set.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO");533 let photo = set.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO");
450 std::fs::write(&photo, b"evil-bytes").unwrap();534 std::fs::write(&photo, b"evil-bytes").unwrap();
451- assert!(verify_set(&set, &scratch).await.is_err());535+ assert!(verify_set(&set, &scratch, &KEY).await.is_err());
452- let refused = restore(&data, &data.join("im.db"), &set, "t1").await;536+ let refused = restore(&data, &data.join("im.db"), &set, "t1", &KEY).await;
453 assert!(refused.is_err());537 assert!(refused.is_err());
454 assert!(!data.join("restore-t1").exists());538 assert!(!data.join("restore-t1").exists());
455 539
456 // Put the original bytes back: the set verifies and restores.540 // Put the original bytes back: the set verifies and restores.
457 std::fs::write(&photo, b"png-bytes").unwrap();541 std::fs::write(&photo, b"png-bytes").unwrap();
458- let outcome = restore(&data, &data.join("im.db"), &set, "t2")542+ let outcome = restore(&data, &data.join("im.db"), &set, "t2", &KEY)
459 .await543 .await
460 .unwrap();544 .unwrap();
461 assert_eq!(outcome.photos, 1);545 assert_eq!(outcome.photos, 1);
@@ -465,6 +549,23 @@ mod tests {
465 );549 );
466 }550 }
467 551
552+ #[tokio::test]
553+ async fn a_set_is_refused_under_another_key_or_with_a_stray_photo_entry() {
554+ let dir = tempfile::tempdir().unwrap();
555+ let data = dir.path().join("data");
556+ std::fs::create_dir_all(&data).unwrap();
557+ let (_store, set) = sample_set(&data).await;
558+ let scratch = data.join("scratch");
559+
560+ // The MAC is keyed: the same set does not verify under any other instance key.
561+ assert!(verify_set(&set, &scratch, &KEY).await.is_ok());
562+ assert!(verify_set(&set, &scratch, &[1u8; 32]).await.is_err());
563+
564+ // A dot-file in photos/ is refused, even though every listed photo is still there.
565+ std::fs::write(set.join(PHOTOS_DIR).join(".stray"), b"x").unwrap();
566+ assert!(verify_set(&set, &scratch, &KEY).await.is_err());
567+ }
568+
468 #[tokio::test]569 #[tokio::test]
469 async fn prune_touches_only_real_sets_with_a_manifest() {570 async fn prune_touches_only_real_sets_with_a_manifest() {
470 let dir = tempfile::tempdir().unwrap();571 let dir = tempfile::tempdir().unwrap();
crates/im-core/src/oauth.rsmodified+19 -1
@@ -69,8 +69,14 @@ pub fn is_valid_registered_uri(uri: &str) -> bool {
69 let Some((scheme, rest)) = uri.split_once("://") else {69 let Some((scheme, rest)) = uri.split_once("://") else {
70 return false;70 return false;
71 };71 };
72+ // Any `@` before the first `/` after `//` is userinfo, even one that sits where a query would start.
73+ // Such a URI names one host to a reader and another to a browser, so it is refused outright.
74+ let before_path = &rest[..rest.find('/').unwrap_or(rest.len())];
75+ if before_path.contains('@') {
76+ return false;
77+ }
72 let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())];78 let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())];
73- if authority.is_empty() || authority.contains('@') {79+ if authority.is_empty() {
74 return false;80 return false;
75 }81 }
76 let host = host_of(authority);82 let host = host_of(authority);
@@ -93,6 +99,10 @@ fn is_loopback(host: &str) -> bool {
93 matches!(host, "localhost" | "127.0.0.1" | "::1")99 matches!(host, "localhost" | "127.0.0.1" | "::1")
94 }100 }
95 101
102+/// The family key of im's own switcher row. No client may carry it, so a family app can never take the
103+/// row that names this service.
104+pub const HOME_KEY: &str = "im";
105+
96 /// True for a family key: `^[a-z][a-z0-9-]{0,31}$`, the same rule as `services.key`.106 /// True for a family key: `^[a-z][a-z0-9-]{0,31}$`, the same rule as `services.key`.
97 pub fn is_valid_family_key(key: &str) -> bool {107 pub fn is_valid_family_key(key: &str) -> bool {
98 let bytes = key.as_bytes();108 let bytes = key.as_bytes();
@@ -103,6 +113,12 @@ pub fn is_valid_family_key(key: &str) -> bool {
103 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')113 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
104 }114 }
105 115
116+/// True for a family key a client may carry: a valid family key other than [`HOME_KEY`]. The admin page and
117+/// `im client add` both use this, so the reserved key is refused the same way everywhere.
118+pub fn is_client_family_key(key: &str) -> bool {
119+ key != HOME_KEY && is_valid_family_key(key)
120+}
121+
106 #[cfg(test)]122 #[cfg(test)]
107 mod tests {123 mod tests {
108 use super::*;124 use super::*;
@@ -127,6 +143,8 @@ mod tests {
127 for bad in [143 for bad in [
128 "http://in.example.com/auth/callback",144 "http://in.example.com/auth/callback",
129 "https://in.example.com@evil.example/auth/callback",145 "https://in.example.com@evil.example/auth/callback",
146+ "https://in.example.com?@evil.example/auth/callback",
147+ "https://in.example.com?x=@evil.example/auth/callback",
130 "https://in.example.com/auth/callback#frag",148 "https://in.example.com/auth/callback#frag",
131 "https:///auth/callback",149 "https:///auth/callback",
132 "https://in.example.com/a b",150 "https://in.example.com/a b",
crates/im-core/src/photo.rsmodified+8 -4
@@ -97,15 +97,19 @@ fn decode_error(_: image::ImageError) -> Error {
97 /// The file that holds the photo of `user_id`. The id must be a plain identifier, so no id can97 /// The file that holds the photo of `user_id`. The id must be a plain identifier, so no id can
98 /// name a path outside the photo directory.98 /// name a path outside the photo directory.
99 pub fn photo_path(data_dir: &Path, user_id: &str) -> Result<PathBuf> {99 pub fn photo_path(data_dir: &Path, user_id: &str) -> Result<PathBuf> {
100- let plain = !user_id.is_empty()100+ if !is_photo_name(user_id) {
101- && user_id.len() <= 64
102- && user_id.bytes().all(|b| b.is_ascii_alphanumeric());
103- if !plain {
104 return Err(Error::Invalid("photo id is not valid".into()));101 return Err(Error::Invalid("photo id is not valid".into()));
105 }102 }
106 Ok(data_dir.join(PHOTO_DIR).join(user_id))103 Ok(data_dir.join(PHOTO_DIR).join(user_id))
107 }104 }
108 105
106+/// True for a file name the photo directory holds: the user id, 1 to 64 ASCII letters and digits. A
107+/// name with a separator, a dot, a dash or any other character is never a photo, so backup and restore
108+/// refuse it.
109+pub fn is_photo_name(name: &str) -> bool {
110+ !name.is_empty() && name.len() <= 64 && name.bytes().all(|b| b.is_ascii_alphanumeric())
111+}
112+
109 /// Replaces the stored photo of `user_id` with `bytes`, which must already be normalised.113 /// Replaces the stored photo of `user_id` with `bytes`, which must already be normalised.
110 ///114 ///
111 /// The bytes go to a temporary file in the same directory, which is fsynced and renamed over the115 /// The bytes go to a temporary file in the same directory, which is fsynced and renamed over the
crates/im-core/src/secret.rsmodified+3 -1
@@ -59,7 +59,9 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
59 Ok(key)59 Ok(key)
60 }60 }
61 61
62-fn read_key(path: &Path) -> Result<[u8; 32]> {62+/// Reads an existing instance key, with the same permission check as the start-up load. A missing key is
63+/// an error here: an operator command that needs the key must not invent one.
64+pub fn read_key(path: &Path) -> Result<[u8; 32]> {
63 #[cfg(unix)]65 #[cfg(unix)]
64 {66 {
65 use std::os::unix::fs::PermissionsExt;67 use std::os::unix::fs::PermissionsExt;
crates/im-core/src/store/admin.rsmodified+44 -16
@@ -17,7 +17,7 @@ use turso::Row;
17 use crate::error::{Error, Result};17 use crate::error::{Error, Result};
18 use crate::model::User;18 use crate::model::User;
19 use crate::store::backchannel::{self, EndReason};19 use crate::store::backchannel::{self, EndReason};
20-use crate::store::clients::{CLIENT_COLS, map_client};20+use crate::store::clients::{CLIENT_COLS, map_client, upsert_service_link};
21 use crate::store::directory::{ChangeKind, record_change};21 use crate::store::directory::{ChangeKind, record_change};
22 use crate::store::invites::{Invite, map_invite};22 use crate::store::invites::{Invite, map_invite};
23 use crate::store::users::{USER_COLS, map_user};23 use crate::store::users::{USER_COLS, map_user};
@@ -190,6 +190,14 @@ impl Store {
190 "the last enabled administrator cannot be deleted".into(),190 "the last enabled administrator cannot be deleted".into(),
191 ));191 ));
192 }192 }
193+ // Revoked explicitly, not only by the cascade below, so no refresh can succeed for this account
194+ // after the delete, whatever the foreign keys do.
195+ tx.execute(
196+ "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL",
197+ (user_id.to_string(), now.clone()),
198+ )
199+ .await
200+ .map_err(db_err)?;
193 tx.execute(201 tx.execute(
194 "DELETE FROM settings WHERE key = ?1",202 "DELETE FROM settings WHERE key = ?1",
195 (format!("totp_pending:{user_id}"),),203 (format!("totp_pending:{user_id}"),),
@@ -353,21 +361,7 @@ impl Store {
353 client_id: &str,361 client_id: &str,
354 ) -> Result<()> {362 ) -> Result<()> {
355 let conn = self.inner.conn.lock().await;363 let conn = self.inner.conn.lock().await;
356- conn.execute(364+ upsert_service_link(&conn, key, name, url, client_id).await
357- "INSERT INTO services (key, name, url, position, client_id) \
358- VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), 0) + 1 FROM services), ?4) \
359- ON CONFLICT(key) DO UPDATE SET name = excluded.name, url = excluded.url, \
360- client_id = excluded.client_id",
361- (
362- key.to_string(),
363- name.to_string(),
364- url.to_string(),
365- client_id.to_string(),
366- ),
367- )
368- .await
369- .map_err(db_err)?;
370- Ok(())
371 }365 }
372 366
373 /// The client with this id, enabled or not. Used by the admin client pages.367 /// The client with this id, enabled or not. Used by the admin client pages.
@@ -467,6 +461,40 @@ impl Store {
467 Ok(changed == 1)461 Ok(changed == 1)
468 }462 }
469 463
464+ /// Reads the saved `policy.` values, lets `change` decide which of them to write, and writes those in one
465+ /// transaction. `change` gets the saved values as they are inside the transaction, so a read-modify-write
466+ /// of the policy cannot lose an update made by another request in between. An error from `change` rolls
467+ /// the transaction back and is returned unchanged.
468+ pub async fn update_policy_settings(
469+ &self,
470+ change: impl FnOnce(&[(String, String)]) -> Result<Vec<(String, String)>>,
471+ ) -> Result<()> {
472+ let conn = self.inner.conn.lock().await;
473+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
474+ let outcome: Result<()> = async {
475+ let saved = fetch_all(
476+ &tx,
477+ "SELECT key, value FROM settings WHERE substr(key, 1, length('policy.')) = 'policy.' ORDER BY key",
478+ (),
479+ |row: &Row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
480+ )
481+ .await?;
482+ let writes = change(&saved)?;
483+ for (key, value) in writes {
484+ tx.execute(
485+ "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \
486+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
487+ (key, value, now_stamp()),
488+ )
489+ .await
490+ .map_err(db_err)?;
491+ }
492+ Ok(())
493+ }
494+ .await;
495+ finish(tx, outcome).await
496+ }
497+
470 /// Removes a setting. Returns false when there was no such setting.498 /// Removes a setting. Returns false when there was no such setting.
471 pub async fn delete_setting(&self, key: &str) -> Result<bool> {499 pub async fn delete_setting(&self, key: &str) -> Result<bool> {
472 let conn = self.inner.conn.lock().await;500 let conn = self.inner.conn.lock().await;
crates/im-core/src/store/clients.rsmodified+93 -35
@@ -4,11 +4,11 @@
4 //! logout URIs are JSON arrays that are matched exactly, never by prefix. A disabled client keeps its4 //! logout URIs are JSON arrays that are matched exactly, never by prefix. A disabled client keeps its
5 //! row, so its history stays readable, and it authenticates nowhere.5 //! row, so its history stays readable, and it authenticates nowhere.
6 6
7-use turso::Row;7+use turso::{Connection, Row};
8 8
9 use crate::error::{Error, Result};9 use crate::error::{Error, Result};
10 use crate::model::Client;10 use crate::model::Client;
11-use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};11+use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
12 use crate::time::now_stamp;12 use crate::time::now_stamp;
13 13
14 /// The columns of a client row, in the order [`map_client`] reads them.14 /// The columns of a client row, in the order [`map_client`] reads them.
@@ -57,41 +57,99 @@ pub struct NewClient<'a> {
57 pub service_key: Option<&'a str>,57 pub service_key: Option<&'a str>,
58 }58 }
59 59
60+/// Inserts one client row. A family key that is already used is a conflict. Takes a connection or a
61+/// transaction, so the same insert serves both the plain and the linked registration.
62+async fn insert_client(conn: &Connection, id: &str, new: &NewClient<'_>) -> Result<()> {
63+ let now = now_stamp();
64+ let redirect_uris =
65+ serde_json::to_string(new.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?;
66+ let post_logout = serde_json::to_string(new.post_logout_redirect_uris)
67+ .map_err(|e| Error::Invalid(e.to_string()))?;
68+ conn.execute(
69+ "INSERT INTO clients (id, name, secret_hash, secret_rotated_at, redirect_uris, \
70+ post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, \
71+ created_at) \
72+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?4)",
73+ (
74+ id.to_string(),
75+ new.name.to_string(),
76+ new.secret_hash.to_string(),
77+ now,
78+ redirect_uris,
79+ post_logout,
80+ new.backchannel_logout_uri.map(str::to_owned),
81+ new.allowed_scopes.to_string(),
82+ new.service_key.map(str::to_owned),
83+ ),
84+ )
85+ .await
86+ .map_err(|e| {
87+ if e.to_string().contains("UNIQUE") {
88+ Error::Conflict("that family key is already used by another client".into())
89+ } else {
90+ db_err(e)
91+ }
92+ })?;
93+ Ok(())
94+}
95+
96+/// Creates or updates the switcher row of a family key and points it at `client_id`. The caller decides
97+/// whether it runs alone or inside a transaction.
98+pub(crate) async fn upsert_service_link(
99+ conn: &Connection,
100+ key: &str,
101+ name: &str,
102+ url: &str,
103+ client_id: &str,
104+) -> Result<()> {
105+ conn.execute(
106+ "INSERT INTO services (key, name, url, position, client_id) \
107+ VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), 0) + 1 FROM services), ?4) \
108+ ON CONFLICT(key) DO UPDATE SET name = excluded.name, url = excluded.url, \
109+ client_id = excluded.client_id",
110+ (
111+ key.to_string(),
112+ name.to_string(),
113+ url.to_string(),
114+ client_id.to_string(),
115+ ),
116+ )
117+ .await
118+ .map_err(db_err)?;
119+ Ok(())
120+}
121+
60 impl Store {122 impl Store {
61 /// Registers a client and returns its row. A family key that is already used is a conflict.123 /// Registers a client and returns its row. A family key that is already used is a conflict.
62 pub async fn create_client(&self, new: &NewClient<'_>) -> Result<Client> {124 pub async fn create_client(&self, new: &NewClient<'_>) -> Result<Client> {
63 let id = new_id();125 let id = new_id();
64- let now = now_stamp();
65- let redirect_uris =
66- serde_json::to_string(new.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?;
67- let post_logout = serde_json::to_string(new.post_logout_redirect_uris)
68- .map_err(|e| Error::Invalid(e.to_string()))?;
69 let conn = self.inner.conn.lock().await;126 let conn = self.inner.conn.lock().await;
70- conn.execute(127+ insert_client(&conn, &id, new).await?;
71- "INSERT INTO clients (id, name, secret_hash, secret_rotated_at, redirect_uris, \128+ drop(conn);
72- post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, \129+ self.client_by_id(&id).await?.ok_or(Error::NotFound)
73- created_at) \130+ }
74- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?4)",131+
75- (132+ /// Registers a family client and creates or updates its switcher row, linked to the client, in one
76- id.clone(),133+ /// transaction. Either both are written or neither is, so a family key never exists without its
77- new.name.to_string(),134+ /// switcher link and a link never names a client that failed to register.
78- new.secret_hash.to_string(),135+ pub async fn create_family_client(
79- now,136+ &self,
80- redirect_uris,137+ new: &NewClient<'_>,
81- post_logout,138+ service_name: &str,
82- new.backchannel_logout_uri.map(str::to_owned),139+ service_url: &str,
83- new.allowed_scopes.to_string(),140+ ) -> Result<Client> {
84- new.service_key.map(str::to_owned),141+ let id = new_id();
85- ),142+ let conn = self.inner.conn.lock().await;
86- )143+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
87- .await144+ let outcome: Result<()> = async {
88- .map_err(|e| {145+ insert_client(&tx, &id, new).await?;
89- if e.to_string().contains("UNIQUE") {146+ let key = new
90- Error::Conflict("that family key is already used by another client".into())147+ .service_key
91- } else {148+ .ok_or_else(|| Error::Invalid("a family client needs a family key".into()))?;
92- db_err(e)149+ upsert_service_link(&tx, key, service_name, service_url, &id).await
93- }150+ }
94- })?;151+ .await;
152+ finish(tx, outcome).await?;
95 drop(conn);153 drop(conn);
96 self.client_by_id(&id).await?.ok_or(Error::NotFound)154 self.client_by_id(&id).await?.ok_or(Error::NotFound)
97 }155 }
@@ -120,13 +178,13 @@ impl Store {
120 .await178 .await
121 }179 }
122 180
123- /// True when a registered client carries this family key, so the key names a known service. Machine181+ /// True when an enabled client carries this family key, so the key names a known service. Machine
124- /// tokens are issued only for known audiences (contracts.md 2.6).182+ /// tokens are issued only for known audiences (contracts.md 2.6). A disabled client no longer names one.
125 pub async fn family_key_known(&self, key: &str) -> Result<bool> {183 pub async fn family_key_known(&self, key: &str) -> Result<bool> {
126 let conn = self.read_conn().await;184 let conn = self.read_conn().await;
127 let found = fetch_opt(185 let found = fetch_opt(
128 &conn,186 &conn,
129- "SELECT 1 FROM clients WHERE service_key = ?1",187+ "SELECT 1 FROM clients WHERE service_key = ?1 AND disabled_at IS NULL",
130 (key.to_string(),),188 (key.to_string(),),
131 |_row| Ok(()),189 |_row| Ok(()),
132 )190 )
crates/im-core/src/store/mod.rsmodified+18 -0
@@ -82,6 +82,7 @@ impl Store {
82 apply_query_only(&reader).await?;82 apply_query_only(&reader).await?;
83 readers.push(Mutex::new(reader));83 readers.push(Mutex::new(reader));
84 }84 }
85+ restrict_database_files(path)?;
85 Ok(Store {86 Ok(Store {
86 inner: Arc::new(Inner {87 inner: Arc::new(Inner {
87 _db: db,88 _db: db,
@@ -154,6 +155,23 @@ impl Store {
154 }155 }
155 }156 }
156 157
158+/// Makes the database file and its `-wal` and `-shm` sidecars private (mode 0600). They hold every row,
159+/// including sealed secrets, so no other local user may read them whatever the process umask was. Runs
160+/// after the connections are open, when the sidecars exist.
161+fn restrict_database_files(path: &Path) -> Result<()> {
162+ use std::os::unix::fs::PermissionsExt;
163+
164+ for suffix in ["", "-wal", "-shm"] {
165+ let mut name = path.as_os_str().to_owned();
166+ name.push(suffix);
167+ let file = std::path::PathBuf::from(name);
168+ if std::fs::symlink_metadata(&file).is_ok_and(|meta| meta.file_type().is_file()) {
169+ std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?;
170+ }
171+ }
172+ Ok(())
173+}
174+
157 /// Ends a transaction: commits when `outcome` is `Ok`, rolls back otherwise, and returns the175 /// Ends a transaction: commits when `outcome` is `Ok`, rolls back otherwise, and returns the
158 /// outcome. Every multi-statement write ends with this, so no path leaves a transaction open.176 /// outcome. Every multi-statement write ends with this, so no path leaves a transaction open.
159 pub async fn finish<T>(tx: Transaction<'_>, outcome: Result<T>) -> Result<T> {177 pub async fn finish<T>(tx: Transaction<'_>, outcome: Result<T>) -> Result<T> {
crates/im-web/src/auth.rsmodified+46 -0
@@ -320,6 +320,52 @@ pub fn clear_pending_login(cx: &Cx) {
320 jar(cx).remove(Cookie::build((PENDING_COOKIE, "")).path("/"));320 jar(cx).remove(Cookie::build((PENDING_COOKIE, "")).path("/"));
321 }321 }
322 322
323+/// Logical name of the one-time secret cookie. It carries a client secret from the POST that made the secret
324+/// to the GET that shows it, so the secret never sits in a response to the POST or in a URL.
325+pub const SECRET_FLASH_COOKIE: &str = "im_secret";
326+
327+/// How long a one-time secret waits in its cookie. Long enough for the redirect to be followed; a secret that
328+/// is not shown in that time is not kept.
329+pub const SECRET_FLASH_TTL: Duration = Duration::from_secs(2 * 60);
330+
331+/// Parks a client secret for the page that shows it once. The payload is sealed with the instance key, names
332+/// the client it belongs to, and expires after [`SECRET_FLASH_TTL`]. Same cookie attributes as the pending
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<()> {
335+ let expires = unix_now() + SECRET_FLASH_TTL.as_secs();
336+ let sealed = secret::seal(key, format!("{client_id}|{expires}|{secret}").as_bytes())?;
337+ let max_age = time::Duration::seconds(i64::try_from(SECRET_FLASH_TTL.as_secs()).unwrap_or(0));
338+ jar(cx).add(
339+ Cookie::build((SECRET_FLASH_COOKIE, sealed))
340+ .path("/")
341+ .secure(true)
342+ .http_only(true)
343+ .same_site(SameSite::Strict)
344+ .max_age(max_age)
345+ .build(),
346+ );
347+ Ok(())
348+}
349+
350+/// Takes the secret parked for `client_id`. The cookie is removed whether or not it matches, so a secret is
351+/// shown at most once. Returns `None` when the cookie is missing, tampered with, expired or for another client.
352+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();
354+ clear_secret_flash(cx);
355+ let plain = secret::open(key, &sealed).ok()?;
356+ let text = String::from_utf8(plain).ok()?;
357+ let mut parts = text.splitn(3, '|');
358+ let id = parts.next()?;
359+ let expires: u64 = parts.next()?.parse().ok()?;
360+ let secret = parts.next()?;
361+ (id == client_id && unix_now() < expires).then(|| secret.to_owned())
362+}
363+
364+/// Removes the one-time secret cookie.
365+pub fn clear_secret_flash(cx: &Cx) {
366+ jar(cx).remove(Cookie::build((SECRET_FLASH_COOKIE, "")).path("/"));
367+}
368+
323 /// Checks one six-digit TOTP code for `user`, with the replay guard. True only when the code is369 /// Checks one six-digit TOTP code for `user`, with the replay guard. True only when the code is
324 /// valid and its step was not used before. Returns false when two-factor sign-in is off.370 /// valid and its step was not used before. Returns false when two-factor sign-in is off.
325 pub async fn verify_totp(store: &Store, key: &[u8; 32], user: &User, code: &str) -> Result<bool> {371 pub async fn verify_totp(store: &Store, key: &[u8; 32], user: &User, code: &str) -> Result<bool> {
crates/im-web/src/backchannel.rsmodified+20 -5
@@ -7,12 +7,16 @@
7 //! until 24 hours after the row was queued; then it is abandoned and logged. Redirects are never7 //! until 24 hours after the row was queued; then it is abandoned and logged. Redirects are never
8 //! followed. A failure never affects the logout that queued the row: that already committed.8 //! followed. A failure never affects the logout that queued the row: that already committed.
9 //!9 //!
10+//! Due rows are delivered a few at a time (see [`DELIVERY_CONCURRENCY`]), so one slow client does not hold up
11+//! the others. Their outcomes are recorded in the order the rows were due.
12+//!
10 //! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), a fresh `jti`, the logout13 //! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), a fresh `jti`, the logout
11 //! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`.14 //! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`.
12 15
13 use std::sync::Arc;16 use std::sync::Arc;
14 use std::time::Duration;17 use std::time::Duration;
15 18
19+use futures_util::{StreamExt, stream};
16 use im_core::model::Client;20 use im_core::model::Client;
17 use im_core::store::Store;21 use im_core::store::Store;
18 use im_core::store::backchannel::{Attempt, Delivery};22 use im_core::store::backchannel::{Attempt, Delivery};
@@ -41,6 +45,10 @@ const TICK: Duration = Duration::from_secs(5);
41 /// The most rows one pass delivers.45 /// The most rows one pass delivers.
42 const BATCH: i64 = 20;46 const BATCH: i64 = 20;
43 47
48+/// How many deliveries run at once. Each waits up to [`DELIVERY_TIMEOUT`] on its client, so they run together
49+/// and the pass takes about as long as its slowest client, not the sum of all of them.
50+pub const DELIVERY_CONCURRENCY: usize = 8;
51+
44 /// How long to wait before the next try after `failures` failed tries (contracts.md 2.5).52 /// How long to wait before the next try after `failures` failed tries (contracts.md 2.5).
45 pub fn backoff(failures: i64) -> Duration {53 pub fn backoff(failures: i64) -> Duration {
46 match failures {54 match failures {
@@ -95,9 +103,18 @@ pub async fn process_due(
95 now: &str,103 now: &str,
96 ) -> im_core::Result<usize> {104 ) -> im_core::Result<usize> {
97 let due = store.due_deliveries(now, BATCH).await?;105 let due = store.due_deliveries(now, BATCH).await?;
106+ // The deliveries are built in a loop and polled `DELIVERY_CONCURRENCY` at a time. `buffered` keeps the
107+ // order of `due`, so the outcomes are recorded oldest first.
108+ let mut pending = Vec::with_capacity(due.len());
98 for job in &due {109 for job in &due {
99- let attempt = deliver(store, key, issuer, http, job).await;110+ pending.push(deliver(store, key, issuer, http, job));
100- match &attempt {111+ }
112+ let attempts: Vec<Attempt> = stream::iter(pending)
113+ .buffered(DELIVERY_CONCURRENCY)
114+ .collect()
115+ .await;
116+ for (job, attempt) in due.iter().zip(&attempts) {
117+ match attempt {
101 Attempt::Delivered => tracing::info!(row = %job.id, "back-channel logout delivered"),118 Attempt::Delivered => tracing::info!(row = %job.id, "back-channel logout delivered"),
102 Attempt::Retry {119 Attempt::Retry {
103 attempts,120 attempts,
@@ -112,9 +129,7 @@ pub async fn process_due(
112 "back-channel logout abandoned"129 "back-channel logout abandoned"
113 ),130 ),
114 }131 }
115- store132+ store.record_attempt(&job.id, attempt, &now_stamp()).await?;
116- .record_attempt(&job.id, &attempt, &now_stamp())
117- .await?;
118 }133 }
119 Ok(due.len())134 Ok(due.len())
120 }135 }
crates/im-web/src/backups.rsmodified+9 -4
@@ -44,7 +44,7 @@ pub fn spawn(state: AppState) -> Option<JoinHandle<()>> {
44 () = stopped(&mut stop) => break,44 () = stopped(&mut stop) => break,
45 }45 }
46 if due(&state.store, &state.config).await46 if due(&state.store, &state.config).await
47- && let Err(error) = run_and_record(&state.config, &state.store).await47+ && let Err(error) = run_and_record(&state.config, &state.store, &state.key).await
48 {48 {
49 tracing::error!(error = %error, "scheduled backup failed");49 tracing::error!(error = %error, "scheduled backup failed");
50 }50 }
@@ -69,7 +69,11 @@ async fn due(store: &Store, config: &Config) -> bool {
69 ///69 ///
70 /// The outcome is recorded in `settings`, so the health page can show it. A failure is returned to the70 /// The outcome is recorded in `settings`, so the health page can show it. A failure is returned to the
71 /// caller as well, so `im backup now` can exit with status 1.71 /// caller as well, so `im backup now` can exit with status 1.
72-pub async fn run_and_record(config: &Config, store: &Store) -> im_core::Result<std::path::PathBuf> {72+pub async fn run_and_record(
73+ config: &Config,
74+ store: &Store,
75+ key: &[u8; 32],
76+) -> im_core::Result<std::path::PathBuf> {
73 let http = http_client();77 let http = http_client();
74 let base = config78 let base = config
75 .backup79 .backup
@@ -84,7 +88,7 @@ pub async fn run_and_record(config: &Config, store: &Store) -> im_core::Result<s
84 if has_ping {88 if has_ping {
85 ping(&http, &format!("{base}/start")).await;89 ping(&http, &format!("{base}/start")).await;
86 }90 }
87- let outcome = write_and_prune(config, store, &stamp).await;91+ let outcome = write_and_prune(config, store, key, &stamp).await;
88 match &outcome {92 match &outcome {
89 Ok(set) => {93 Ok(set) => {
90 tracing::info!(set = %set.display(), "backup written");94 tracing::info!(set = %set.display(), "backup written");
@@ -109,9 +113,10 @@ pub async fn run_and_record(config: &Config, store: &Store) -> im_core::Result<s
109 async fn write_and_prune(113 async fn write_and_prune(
110 config: &Config,114 config: &Config,
111 store: &Store,115 store: &Store,
116+ key: &[u8; 32],
112 stamp: &str,117 stamp: &str,
113 ) -> im_core::Result<std::path::PathBuf> {118 ) -> im_core::Result<std::path::PathBuf> {
114- let set = backup::write_set(store, &config.data_dir, &config.backup.dir, stamp).await?;119+ let set = backup::write_set(store, &config.data_dir, &config.backup.dir, stamp, key).await?;
115 let removed = backup::prune(&config.backup.dir, config.backup.keep as usize)?;120 let removed = backup::prune(&config.backup.dir, config.backup.keep as usize)?;
116 if removed > 0 {121 if removed > 0 {
117 tracing::info!(removed, "old backup sets removed");122 tracing::info!(removed, "old backup sets removed");
crates/im-web/src/boot.rsmodified+15 -5
@@ -33,7 +33,7 @@ use crate::sweeper;
33 use crate::throttle::Throttle;33 use crate::throttle::Throttle;
34 34
35 /// Name of the instance key file inside the data directory.35 /// Name of the instance key file inside the data directory.
36-const KEY_FILE: &str = "im.key";36+pub(crate) const KEY_FILE: &str = "im.key";
37 37
38 /// Name of the lock file inside the data directory. The server holds it for its whole life, and so does38 /// Name of the lock file inside the data directory. The server holds it for its whole life, and so does
39 /// every operator command, so the two never open the database at once.39 /// 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<AppState> {
155 anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),155 anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),
156 // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves.156 // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves.
157 stop: watch::channel(false).1,157 stop: watch::channel(false).1,
158+ settings_lock: Arc::new(tokio::sync::Mutex::new(())),
158 })159 })
159 }160 }
160 161
@@ -165,17 +166,25 @@ pub(crate) async fn effective_policy(
165 config: &im_core::config::Config,166 config: &im_core::config::Config,
166 store: &Store,167 store: &Store,
167 ) -> im_core::Result<PolicyConfig> {168 ) -> im_core::Result<PolicyConfig> {
168- let mut policy = config.policy.clone();169+ let saved = store.settings_with_prefix("policy.").await?;
169- for (key, value) in store.settings_with_prefix("policy.").await? {170+ Ok(merge_saved_policy(&config.policy, &saved))
171+}
172+
173+/// The policy that the file values and the saved `policy.` values give. A saved value that does not parse
174+/// or is out of range is logged and ignored, so one bad row cannot keep the server from starting. The
175+/// settings page calls this on the values it reads inside its transaction.
176+pub(crate) fn merge_saved_policy(file: &PolicyConfig, saved: &[(String, String)]) -> PolicyConfig {
177+ let mut policy = file.clone();
178+ for (key, value) in saved {
170 let name = key.trim_start_matches("policy.");179 let name = key.trim_start_matches("policy.");
171- match policy.set(name, &value) {180+ match policy.set(name, value) {
172 Ok(next) => policy = next,181 Ok(next) => policy = next,
173 Err(error) => {182 Err(error) => {
174 tracing::warn!(setting = %key, error = %error, "stored policy setting ignored");183 tracing::warn!(setting = %key, error = %error, "stored policy setting ignored");
175 }184 }
176 }185 }
177 }186 }
178- Ok(policy)187+ policy
179 }188 }
180 189
181 /// The request body limit of the photo upload: the picture plus room for the multipart framing and190 /// The request body limit of the photo upload: the picture plus room for the multipart framing and
@@ -259,6 +268,7 @@ mod tests {
259 stream_slots: Arc::new(StreamSlots::default()),268 stream_slots: Arc::new(StreamSlots::default()),
260 anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),269 anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),
261 stop: watch::channel(false).1,270 stop: watch::channel(false).1,
271+ settings_lock: Arc::new(tokio::sync::Mutex::new(())),
262 };272 };
263 (dir, state)273 (dir, state)
264 }274 }
crates/im-web/src/cli.rsmodified+26 -26
@@ -12,12 +12,12 @@ use std::process::ExitCode;
12 use im_core::config::Config;12 use im_core::config::Config;
13 use im_core::names::parse_display_name;13 use im_core::names::parse_display_name;
14 use im_core::oauth::{14 use im_core::oauth::{
15- SUPPORTED_SCOPES, is_supported_scope, is_valid_family_key, is_valid_registered_uri,15+ SUPPORTED_SCOPES, is_client_family_key, is_supported_scope, is_valid_registered_uri,
16 };16 };
17 use im_core::store::clients::NewClient;17 use im_core::store::clients::NewClient;
18 use im_core::token::{generate_token, hash_token};18 use im_core::token::{generate_token, hash_token};
19 19
20-use crate::boot::{lock_data_dir, open_state};20+use crate::boot::{KEY_FILE, lock_data_dir, open_state};
21 use crate::pages::admin::clients::is_origin;21 use crate::pages::admin::clients::is_origin;
22 use crate::state::AppState;22 use crate::state::AppState;
23 23
@@ -145,10 +145,10 @@ async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String>
145 }145 }
146 }146 }
147 if let Some(key) = &args.family_key147 if let Some(key) = &args.family_key
148- && !is_valid_family_key(key)148+ && !is_client_family_key(key)
149 {149 {
150 return Err(format!(150 return Err(format!(
151- "family key {key} must be lowercase letters, digits and hyphens"151+ "family key {key} must be lowercase letters, digits and hyphens, and not im (the home row)"
152 ));152 ));
153 }153 }
154 match (&args.family_key, &args.public_url) {154 match (&args.family_key, &args.public_url) {
@@ -164,26 +164,22 @@ async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String>
164 let scopes = scope_list(args.scopes.as_deref().unwrap_or(DEFAULT_SCOPES))?;164 let scopes = scope_list(args.scopes.as_deref().unwrap_or(DEFAULT_SCOPES))?;
165 165
166 let secret = generate_token();166 let secret = generate_token();
167- let client = state167+ let secret_hash = hash_token(&secret);
168- .store168+ let new = NewClient {
169- .create_client(&NewClient {169+ name: &name,
170- name: &name,170+ secret_hash: &secret_hash,
171- secret_hash: &hash_token(&secret),171+ redirect_uris: &args.redirect_uris,
172- redirect_uris: &args.redirect_uris,172+ post_logout_redirect_uris: &args.post_logout_uris,
173- post_logout_redirect_uris: &args.post_logout_uris,173+ backchannel_logout_uri: args.backchannel_uri.as_deref(),
174- backchannel_logout_uri: args.backchannel_uri.as_deref(),174+ allowed_scopes: &scopes,
175- allowed_scopes: &scopes,175+ service_key: args.family_key.as_deref(),
176- service_key: args.family_key.as_deref(),176+ };
177- })177+ // A family client and its switcher row are written in one transaction, as the admin page does.
178- .await178+ let client = match (&args.family_key, &args.public_url) {
179- .map_err(|e| e.to_string())?;179+ (Some(_), Some(url)) => state.store.create_family_client(&new, &name, url).await,
180- if let (Some(key), Some(url)) = (&args.family_key, &args.public_url) {180+ _ => state.store.create_client(&new).await,
181- state
182- .store
183- .link_service(key, &name, url, &client.id)
184- .await
185- .map_err(|e| e.to_string())?;
186 }181 }
182+ .map_err(|e| e.to_string())?;
187 println!("client_id: {}", client.id);183 println!("client_id: {}", client.id);
188 println!("client_secret: {secret}");184 println!("client_secret: {secret}");
189 eprintln!("im: the client secret is shown once; store it now");185 eprintln!("im: the client secret is shown once; store it now");
@@ -255,7 +251,7 @@ pub async fn backup(config: &Path, words: &[String]) -> ExitCode {
255 match words {251 match words {
256 [verb] if verb == "now" => {252 [verb] if verb == "now" => {
257 with_state(config, |state| async move {253 with_state(config, |state| async move {
258- let set = crate::backups::run_and_record(&state.config, &state.store)254+ let set = crate::backups::run_and_record(&state.config, &state.store, &state.key)
259 .await255 .await
260 .map_err(|e| e.to_string())?;256 .map_err(|e| e.to_string())?;
261 println!("im: backup written to {}", set.display());257 println!("im: backup written to {}", set.display());
@@ -285,8 +281,12 @@ pub async fn restore(config: &Path, words: &[String]) -> ExitCode {
285 let outcome = async {281 let outcome = async {
286 let config = Config::load(config).map_err(|e| e.to_string())?;282 let config = Config::load(config).map_err(|e| e.to_string())?;
287 let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?;283 let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?;
284+ // The manifest MAC is keyed with the instance key, so a restore needs the key that made the set. A
285+ // missing key is an error: a new key could never verify the set.
286+ let key = im_core::secret::read_key(&config.data_dir.join(KEY_FILE))
287+ .map_err(|e| e.to_string())?;
288 let stamp = im_core::time::now_stamp().replace([':', '.'], "-");288 let stamp = im_core::time::now_stamp().replace([':', '.'], "-");
289- im_core::backup::restore(&config.data_dir, &config.database, &set, &stamp)289+ im_core::backup::restore(&config.data_dir, &config.database, &set, &stamp, &key)
290 .await290 .await
291 .map_err(|e| e.to_string())291 .map_err(|e| e.to_string())
292 }292 }
@@ -335,7 +335,7 @@ pub async fn keys(config: &Path, words: &[String]) -> ExitCode {
335 .await335 .await
336 .map_err(|e| e.to_string())?;336 .map_err(|e| e.to_string())?;
337 println!(337 println!(
338- "im: new signing key {kid}; the previous key stays published for the overlap"338+ "im: new signing key {kid} is published now and starts signing after the publish lead"
339 );339 );
340 Ok(())340 Ok(())
341 })341 })
crates/im-web/src/i18n/admin.rsmodified+2 -2
@@ -613,8 +613,8 @@ fn pair(key: A) -> (&'static str, &'static str) {
613 A::RotateNow => ("Rotate now", "Şimdi döndür"),613 A::RotateNow => ("Rotate now", "Şimdi döndür"),
614 A::RetireKey => ("Retire", "Emekli yap"),614 A::RetireKey => ("Retire", "Emekli yap"),
615 A::NoticeKeyRotated => (615 A::NoticeKeyRotated => (
616- "A new signing key is current. The old key is retired.",616+ "A new signing key is published. It starts signing in one day, and the old key signs until then.",
617- "Yeni imzalama anahtarı güncel. Eski anahtar emekli yapıldı.",617+ "Yeni imzalama anahtarı yayımlandı. Bir gün sonra imzalamaya başlar; o zamana kadar eski anahtar imzalar.",
618 ),618 ),
619 A::NoticeKeyRetired => (619 A::NoticeKeyRetired => (
620 "The key is retired. It stays published for the usual overlap.",620 "The key is retired. It stays published for the usual overlap.",
crates/im-web/src/mail/message.rsmodified+15 -3
@@ -69,8 +69,20 @@ impl Sender {
69 }69 }
70 }70 }
71 71
72-/// Builds a `multipart/alternative` message with a plain-text and an HTML part. The subject is the72+/// The subject as it goes on the wire: every control character, line breaks included, is removed, and the
73-/// only other text, and it comes from fixed strings.73+/// ends are trimmed, so no subject can end a header early. Enqueueing checks the same thing, but a row
74+/// written by any other path still cannot break the header, so this runs again right before sending.
75+pub fn clean_subject(subject: &str) -> String {
76+ subject
77+ .chars()
78+ .filter(|c| !c.is_control())
79+ .collect::<String>()
80+ .trim()
81+ .to_owned()
82+}
83+
84+/// Builds a `multipart/alternative` message with a plain-text and an HTML part. The subject is cleaned by
85+/// [`clean_subject`] first.
74 pub fn build(86 pub fn build(
75 sender: &Sender,87 sender: &Sender,
76 to: &Recipient,88 to: &Recipient,
@@ -81,7 +93,7 @@ pub fn build(
81 Message::builder()93 Message::builder()
82 .from(sender.mailbox.clone())94 .from(sender.mailbox.clone())
83 .to(to.mailbox()?)95 .to(to.mailbox()?)
84- .subject(subject)96+ .subject(clean_subject(subject))
85 .multipart(MultiPart::alternative_plain_html(text, html))97 .multipart(MultiPart::alternative_plain_html(text, html))
86 .map_err(|_| "message could not be built")98 .map_err(|_| "message could not be built")
87 }99 }
crates/im-web/src/oidc/logout.rsmodified+3 -2
@@ -94,8 +94,9 @@ async fn verify_hint(
94 if jwt::check_issuer(&claims, issuer).is_err() {94 if jwt::check_issuer(&claims, issuer).is_err() {
95 return Ok(None);95 return Ok(None);
96 }96 }
97- // An access token has `azp` and `scope`; an ID token has neither. Only ID tokens are hints.97+ // An access token has `azp` and `scope`; an ID token has neither. Only ID tokens are hints. A logout
98- if claims.contains_key("azp") || claims.contains_key("scope") {98+ // token carries `events` and is never a hint either: it would otherwise pass for an ID token here.
99+ if claims.contains_key("azp") || claims.contains_key("scope") || claims.contains_key("events") {
99 return Ok(None);100 return Ok(None);
100 }101 }
101 let Some(client_id) = jwt::single_audience(&claims) else {102 let Some(client_id) = jwt::single_audience(&claims) else {
crates/im-web/src/oidc/signing.rsmodified+9 -5
@@ -13,7 +13,7 @@ use im_core::keys::{self, OVERLAP};
13 use im_core::model::KeyRecord;13 use im_core::model::KeyRecord;
14 use im_core::secret;14 use im_core::secret;
15 use im_core::store::Store;15 use im_core::store::Store;
16-use im_core::time::{now_stamp, stamp_minus};16+use im_core::time::{now_stamp, stamp_minus, stamp_plus};
17 use serde_json::Value;17 use serde_json::Value;
18 use tokio::sync::watch;18 use tokio::sync::watch;
19 19
@@ -66,17 +66,21 @@ pub fn spawn(
66 })66 })
67 }67 }
68 68
69-/// Makes a new key the signing key now. The previous key stops signing at once and stays published for the69+/// Makes a new key the signing key, one publish lead from now. It is published first and only then used: the
70-/// usual overlap, so tokens it signed still verify. Returns the new key id.70+/// JWKS carries it before the first token it signs, and the previous key keeps signing until then. Returns the
71+/// new key id.
71 pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<String> {72 pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<String> {
72 let fresh = keys::generate();73 let fresh = keys::generate();
73 let now = now_stamp();74 let now = now_stamp();
75+ 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())
77+ })?;
74 let record = KeyRecord {78 let record = KeyRecord {
75 kid: fresh.kid.clone(),79 kid: fresh.kid.clone(),
76 private_sealed: secret::seal(instance_key, &fresh.seed)?,80 private_sealed: secret::seal(instance_key, &fresh.seed)?,
77 public_raw: fresh.public.to_vec(),81 public_raw: fresh.public.to_vec(),
78- created_at: now.clone(),82+ created_at: now,
79- activates_at: now,83+ activates_at,
80 retires_at: None,84 retires_at: None,
81 };85 };
82 store.add_signing_key(&record).await?;86 store.add_signing_key(&record).await?;
crates/im-web/src/pages/admin/clients.rsmodified+95 -101
@@ -2,16 +2,18 @@
2 //! `/admin/services/{id}`: one client's settings, with rotate and disable.2 //! `/admin/services/{id}`: one client's settings, with rotate and disable.
3 //!3 //!
4 //! Registering a client here does what `im client add` does, with the same rules (`check`): the secret is4 //! Registering a client here does what `im client add` does, with the same rules (`check`): the secret is
5-//! generated, shown once on the page that created it, and only its hash is stored. A family key also5+//! generated and only its hash is stored. A family key also needs a public address, because that is the link
6-//! needs a public address, because that is the link the switcher shows; the address is kept in the6+//! the switcher shows; the client and that switcher row are written in one transaction. A rejected form is
7-//! switcher row of the same key. A rejected form is shown again with what was typed in it.7+//! shown again with what was typed in it.
8 //!8 //!
9-//! The rotate action shows the new secret once on the same page, for the same reason.9+//! A successful register or rotate is Post/Redirect/Get. The secret travels to the client's page in a short
10+//! sealed cookie (`auth::set_secret_flash`), and that page shows it once and clears the cookie, so the secret is
11+//! never in a response to the POST or in a URL.
10 12
11 use im_core::Error as CoreError;13 use im_core::Error as CoreError;
12 use im_core::model::{AuditAction, Client, Service};14 use im_core::model::{AuditAction, Client, Service};
13 use im_core::names::parse_display_name;15 use im_core::names::parse_display_name;
14-use im_core::oauth::{is_supported_scope, is_valid_family_key, is_valid_registered_uri};16+use im_core::oauth::{is_client_family_key, is_supported_scope, is_valid_registered_uri};
15 use im_core::store::admin::ClientEdit;17 use im_core::store::admin::ClientEdit;
16 use im_core::store::clients::NewClient;18 use im_core::store::clients::NewClient;
17 use im_core::token::{generate_token, hash_token};19 use im_core::token::{generate_token, hash_token};
@@ -20,12 +22,12 @@ use serde_json::json;
20 use topcoat::Result;22 use topcoat::Result;
21 use topcoat::context::{Cx, app_context};23 use topcoat::context::{Cx, app_context};
22 use topcoat::router::content::Form;24 use topcoat::router::content::Form;
23-use topcoat::router::error::{SeeOther, not_found};25+use topcoat::router::error::{SeeOther, not_found, see_other};
24 use topcoat::router::{page, route};26 use topcoat::router::{page, route};
25 use topcoat::view::{View, component, view};27 use topcoat::view::{View, component, view};
26 28
27 use crate::audit::{Actor, record};29 use crate::audit::{Actor, record};
28-use crate::auth::{require_admin, require_admin_csrf};30+use crate::auth::{require_admin, require_admin_csrf, set_secret_flash, take_secret_flash};
29 use crate::i18n::Lang;31 use crate::i18n::Lang;
30 use crate::i18n::admin::{A, text};32 use crate::i18n::admin::{A, text};
31 use crate::pages::admin::{33 use crate::pages::admin::{
@@ -39,9 +41,6 @@ use crate::views::{ViewerInfo, field, shell};
39 /// The scopes a new client gets when the form leaves them as they are: what a family app signs in with.41 /// The scopes a new client gets when the form leaves them as they are: what a family app signs in with.
40 const DEFAULT_SCOPES: &str = "openid profile email";42 const DEFAULT_SCOPES: &str = "openid profile email";
41 43
42-/// The key of im's own switcher row. A family app may not take it.
43-const HOME_KEY: &str = "im";
44-
45 /// The fields of the client form. Every field is text, as typed; [`check`] turns it into values.44 /// The fields of the client form. Every field is text, as typed; [`check`] turns it into values.
46 #[derive(Deserialize, Default, Clone)]45 #[derive(Deserialize, Default, Clone)]
47 struct ClientForm {46 struct ClientForm {
@@ -114,7 +113,7 @@ fn check(form: &ClientForm) -> std::result::Result<Checked, &'static str> {
114 let key = form.family_key.trim();113 let key = form.family_key.trim();
115 let family_key = if key.is_empty() {114 let family_key = if key.is_empty() {
116 None115 None
117- } else if key == HOME_KEY || !is_valid_family_key(key) {116+ } else if !is_client_family_key(key) {
118 return Err("family-key");117 return Err("family-key");
119 } else {118 } else {
120 Some(key.to_owned())119 Some(key.to_owned())
@@ -199,89 +198,93 @@ async fn services_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl Vi
199 defaults,198 defaults,
200 notice_text(lang, &query.notice).map(str::to_owned),199 notice_text(lang, &query.notice).map(str::to_owned),
201 error_text(lang, &query.error).map(str::to_owned),200 error_text(lang, &query.error).map(str::to_owned),
202- None,
203 ))201 ))
204 }202 }
205 203
206-/// `POST /admin/services`: registers a client. On success the secret is shown on this page, once.204+/// `POST /admin/services`: registers a client. On success the secret goes to the client's page in a sealed
205+/// cookie and the browser is redirected there, so the secret is shown once and never in this response.
207 #[page(POST "/admin/services")]206 #[page(POST "/admin/services")]
208 async fn create_client(cx: &Cx, Form(form): Form<ClientForm>) -> Result<impl View> {207 async fn create_client(cx: &Cx, Form(form): Form<ClientForm>) -> Result<impl View> {
209 let viewer = require_admin_csrf(cx, &form.csrf).await?;208 let viewer = require_admin_csrf(cx, &form.csrf).await?;
210 let (lang, info) = frame_info(cx, &viewer);209 let (lang, info) = frame_info(cx, &viewer);
211 let state = app_context::<AppState>(cx);210 let state = app_context::<AppState>(cx);
212 let csrf = viewer.session.csrf_token.clone();211 let csrf = viewer.session.csrf_token.clone();
213- let mut success = None;212+ let checked = match check(&form) {
214- let mut problem = None;213+ Ok(checked) => checked,
215- let mut created = None;214+ Err(code) => return services_again(cx, lang, info, csrf, form, code).await,
216- let mut shown = ClientForm {
217- scopes: DEFAULT_SCOPES.to_owned(),
218- ..ClientForm::default()
219 };215 };
220- match check(&form) {216+ let secret = generate_token();
221- Err(code) => {217+ let secret_hash = hash_token(&secret);
222- problem = error_text(lang, code).map(str::to_owned);218+ let new = NewClient {
223- shown = ClientForm {219+ name: &checked.name,
224- csrf: String::new(),220+ secret_hash: &secret_hash,
225- ..form221+ redirect_uris: &checked.redirect_uris,
226- };222+ post_logout_redirect_uris: &checked.post_logout_uris,
227- }223+ backchannel_logout_uri: checked.backchannel_uri.as_deref(),
228- Ok(checked) => {224+ allowed_scopes: &checked.scopes,
229- let secret = generate_token();225+ service_key: checked.family_key.as_deref(),
230- match state226+ };
227+ // A family client and its switcher row are one transaction, so neither exists without the other.
228+ let registered = match (&checked.family_key, &checked.public_url) {
229+ (Some(_), Some(url)) => {
230+ state
231 .store231 .store
232- .create_client(&NewClient {232+ .create_family_client(&new, &checked.name, url)
233- name: &checked.name,
234- secret_hash: &hash_token(&secret),
235- redirect_uris: &checked.redirect_uris,
236- post_logout_redirect_uris: &checked.post_logout_uris,
237- backchannel_logout_uri: checked.backchannel_uri.as_deref(),
238- allowed_scopes: &checked.scopes,
239- service_key: checked.family_key.as_deref(),
240- })
241 .await233 .await
242- {
243- Ok(client) => {
244- if let (Some(key), Some(url)) = (&checked.family_key, &checked.public_url) {
245- state
246- .store
247- .link_service(key, &checked.name, url, &client.id)
248- .await?;
249- }
250- record(
251- cx,
252- Actor::User(&viewer.user.id),
253- AuditAction::ClientCreated,
254- Some(("client", &client.id)),
255- json!({ "family": checked.family_key.is_some() }),
256- )
257- .await;
258- changed(&state.live);
259- success = Some(text(lang, A::ClientSaved).to_owned());
260- created = Some(Created {
261- id: client.id,
262- name: client.name,
263- secret,
264- });
265- }
266- Err(CoreError::Conflict(_)) => {
267- problem = error_text(lang, "family-taken").map(str::to_owned);
268- shown = ClientForm {
269- csrf: String::new(),
270- ..form
271- };
272- }
273- Err(error) => return Err(error.into()),
274- }
275 }234 }
276- }235+ _ => state.store.create_client(&new).await,
236+ };
237+ let client = match registered {
238+ Ok(client) => client,
239+ Err(CoreError::Conflict(_)) => {
240+ return services_again(cx, lang, info, csrf, form, "family-taken").await;
241+ }
242+ Err(error) => return Err(error.into()),
243+ };
244+ record(
245+ cx,
246+ Actor::User(&viewer.user.id),
247+ AuditAction::ClientCreated,
248+ Some(("client", &client.id)),
249+ json!({ "family": checked.family_key.is_some() }),
250+ )
251+ .await;
252+ changed(&state.live);
253+ set_secret_flash(cx, &state.key, &client.id, &secret)?;
254+ Err(see_other(format!("/admin/services/{}?notice=client-saved", client.id)).into())
255+}
256+
257+/// The services page again, with the form as it was typed and the reason it was refused. The arguments are
258+/// owned, because the view is returned from the handler and must not borrow from it.
259+async fn services_again(
260+ cx: &Cx,
261+ lang: Lang,
262+ info: ViewerInfo,
263+ csrf: String,
264+ form: ClientForm,
265+ code: &str,
266+) -> Result<impl View> {
267+ let state = app_context::<AppState>(cx);
277 let services = state.store.list_services().await?;268 let services = state.store.list_services().await?;
278 let clients = state.store.list_clients().await?;269 let clients = state.store.list_clients().await?;
270+ let shown = ClientForm {
271+ csrf: String::new(),
272+ ..form
273+ };
279 Ok(services_view(274 Ok(services_view(
280- cx, lang, info, csrf, services, clients, shown, success, problem, created,275+ cx,
276+ lang,
277+ info,
278+ csrf,
279+ services,
280+ clients,
281+ shown,
282+ None,
283+ error_text(lang, code).map(str::to_owned),
281 ))284 ))
282 }285 }
283 286
284-/// What the page shows once about a new client: its id and its secret.287+/// What the page shows once about a client whose secret was just made: its id, its name and the secret.
285 struct Created {288 struct Created {
286 id: String,289 id: String,
287 name: String,290 name: String,
@@ -296,6 +299,13 @@ async fn client_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View
296 let (lang, info) = frame_info(cx, &viewer);299 let (lang, info) = frame_info(cx, &viewer);
297 let client = client_from_path(cx, state).await?;300 let client = client_from_path(cx, state).await?;
298 let public_url = public_url_of(state, &client).await?;301 let public_url = public_url_of(state, &client).await?;
302+ // The secret of a client made by the redirect that led here. Taking it clears the cookie, so a reload
303+ // does not show it again.
304+ let secret = take_secret_flash(cx, &state.key, &client.id).map(|secret| Created {
305+ id: client.id.clone(),
306+ name: client.name.clone(),
307+ secret,
308+ });
299 Ok(detail_view(309 Ok(detail_view(
300 cx,310 cx,
301 lang,311 lang,
@@ -305,7 +315,7 @@ async fn client_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View
305 public_url,315 public_url,
306 notice_text(lang, &query.notice).map(str::to_owned),316 notice_text(lang, &query.notice).map(str::to_owned),
307 error_text(lang, &query.error).map(str::to_owned),317 error_text(lang, &query.error).map(str::to_owned),
308- None,318+ secret,
309 ))319 ))
310 }320 }
311 321
@@ -378,11 +388,11 @@ async fn edit_client(cx: &Cx, Form(form): Form<ClientForm>) -> Result<SeeOther>
378 Ok(done(&base, "client-saved"))388 Ok(done(&base, "client-saved"))
379 }389 }
380 390
381-/// `POST /admin/services/{id}/rotate`. The old secret stops working at once; the new one is shown here, once.391+/// `POST /admin/services/{id}/rotate`. The old secret stops working at once. The new one is shown once on the
382-#[page(POST "/admin/services/{id}/rotate")]392+/// client's page, which this redirect leads to.
383-async fn rotate_secret(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl View> {393+#[route(POST "/admin/services/{id}/rotate")]
394+async fn rotate_secret(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
384 let viewer = require_admin_csrf(cx, &form.csrf).await?;395 let viewer = require_admin_csrf(cx, &form.csrf).await?;
385- let (lang, info) = frame_info(cx, &viewer);
386 let state = app_context::<AppState>(cx);396 let state = app_context::<AppState>(cx);
387 let client = client_from_path(cx, state).await?;397 let client = client_from_path(cx, state).await?;
388 let secret = generate_token();398 let secret = generate_token();
@@ -399,23 +409,11 @@ async fn rotate_secret(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl View>
399 )409 )
400 .await;410 .await;
401 changed(&state.live);411 changed(&state.live);
402- let public_url = public_url_of(state, &client).await?;412+ set_secret_flash(cx, &state.key, &client.id, &secret)?;
403- let created = Created {413+ Ok(see_other(format!(
404- id: client.id.clone(),414+ "/admin/services/{}?notice=secret-rotated",
405- name: client.name.clone(),415+ client.id
406- secret,416+ )))
407- };
408- Ok(detail_view(
409- cx,
410- lang,
411- info,
412- viewer.session.csrf_token.clone(),
413- client,
414- public_url,
415- Some(text(lang, A::NoticeSecretRotated).to_owned()),
416- None,
417- Some(created),
418- ))
419 }417 }
420 418
421 /// `POST /admin/services/{id}/disable`. A disabled client cannot sign in or exchange tokens.419 /// `POST /admin/services/{id}/disable`. A disabled client cannot sign in or exchange tokens.
@@ -452,7 +450,6 @@ fn services_view(
452 form: ClientForm,450 form: ClientForm,
453 success: Option<String>,451 success: Option<String>,
454 problem: Option<String>,452 problem: Option<String>,
455- created: Option<Created>,
456 ) -> impl View {453 ) -> impl View {
457 view! { cx =>454 view! { cx =>
458 shell(title: text(lang, A::ServicesTitle), lang: lang, viewer: Some(info),455 shell(title: text(lang, A::ServicesTitle), lang: lang, viewer: Some(info),
@@ -461,9 +458,6 @@ fn services_view(
461 <h1>(text(lang, A::ServicesTitle))</h1>458 <h1>(text(lang, A::ServicesTitle))</h1>
462 <p class="muted">(text(lang, A::ServicesIntro))</p>459 <p class="muted">(text(lang, A::ServicesIntro))</p>
463 flash_messages(success: success, problem: problem)460 flash_messages(success: success, problem: problem)
464- if let Some(created) = created {
465- secret_box(lang: lang, created: created)
466- }
467 <h2>(text(lang, A::ServicesList))</h2>461 <h2>(text(lang, A::ServicesList))</h2>
468 if services.is_empty() {462 if services.is_empty() {
469 <p class="muted">(text(lang, A::NoServices))</p>463 <p class="muted">(text(lang, A::NoServices))</p>
crates/im-web/src/pages/admin/settings.rsmodified+42 -27
@@ -21,7 +21,7 @@ use topcoat::view::{View, component, view};
21 21
22 use crate::audit::{Actor, record};22 use crate::audit::{Actor, record};
23 use crate::auth::{require_admin, require_admin_csrf};23 use crate::auth::{require_admin, require_admin_csrf};
24-use crate::boot::effective_policy;24+use crate::boot::{effective_policy, merge_saved_policy};
25 use crate::i18n::Lang;25 use crate::i18n::Lang;
26 use crate::i18n::admin::{A, text};26 use crate::i18n::admin::{A, text};
27 use crate::pages::admin::{27 use crate::pages::admin::{
@@ -167,36 +167,48 @@ async fn settings_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl Vi
167 }167 }
168 168
169 /// `POST /admin/settings`: saves the values that changed. Every value is checked first; if one is wrong,169 /// `POST /admin/settings`: saves the values that changed. Every value is checked first; if one is wrong,
170-/// nothing is saved.170+/// nothing is saved. The read of the saved values, the check and the write are one transaction, under the
171+/// settings lock, so a save made by another request in between cannot be lost.
171 #[route(POST "/admin/settings")]172 #[route(POST "/admin/settings")]
172 async fn save_settings(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<SeeOther> {173 async fn save_settings(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<SeeOther> {
173 let viewer = require_admin_csrf(cx, &form.csrf).await?;174 let viewer = require_admin_csrf(cx, &form.csrf).await?;
174 let state = app_context::<AppState>(cx);175 let state = app_context::<AppState>(cx);
175- let current = state.policy();176+ let names = {
176- let mut next = current.clone();177+ let _guard = state.settings_lock.lock().await;
177- let mut changed_keys: Vec<(&'static str, String)> = Vec::new();178+ let mut names: Vec<&'static str> = Vec::new();
178- for (key, typed) in form.values() {179+ let outcome = state
179- let typed = typed.trim();180+ .store
180- if typed == value_of(&current, key) {181+ .update_policy_settings(|saved| {
181- continue;182+ let current = merge_saved_policy(&state.config.policy, saved);
183+ let mut next = current.clone();
184+ let mut writes = Vec::new();
185+ for (key, typed) in form.values() {
186+ let typed = typed.trim();
187+ if typed == value_of(&current, key) {
188+ continue;
189+ }
190+ next = next.set(key, typed)?;
191+ names.push(key);
192+ writes.push((format!("policy.{key}"), typed.to_owned()));
193+ }
194+ Ok(writes)
195+ })
196+ .await;
197+ match outcome {
198+ Ok(()) => {}
199+ Err(im_core::Error::Invalid(_)) => return Ok(refused("/admin/settings", "settings")),
200+ Err(error) => return Err(error.into()),
182 }201 }
183- next = match next.set(key, typed) {202+ if !names.is_empty() {
184- Ok(policy) => policy,203+ // Refreshed from the committed rows, not from the values typed, so memory matches the database.
185- Err(_) => return Ok(refused("/admin/settings", "settings")),204+ let policy = effective_policy(&state.config, &state.store).await?;
186- };205+ state.set_policy(policy);
187- changed_keys.push((key, typed.to_owned()));206+ }
188- }207+ names
189- if changed_keys.is_empty() {208+ };
209+ if names.is_empty() {
190 return Ok(done("/admin/settings", "settings-saved"));210 return Ok(done("/admin/settings", "settings-saved"));
191 }211 }
192- for (key, value) in &changed_keys {
193- state
194- .store
195- .set_setting(&format!("policy.{key}"), value)
196- .await?;
197- }
198- state.set_policy(next);
199- let names: Vec<&str> = changed_keys.iter().map(|(key, _)| *key).collect();
200 record(212 record(
201 cx,213 cx,
202 Actor::User(&viewer.user.id),214 Actor::User(&viewer.user.id),
@@ -218,9 +230,12 @@ async fn reset_setting(cx: &Cx, Form(form): Form<ResetForm>) -> Result<SeeOther>
218 return Err(not_found().into());230 return Err(not_found().into());
219 };231 };
220 let state = app_context::<AppState>(cx);232 let state = app_context::<AppState>(cx);
221- state.store.delete_setting(&format!("policy.{key}")).await?;233+ {
222- let policy = effective_policy(&state.config, &state.store).await?;234+ let _guard = state.settings_lock.lock().await;
223- state.set_policy(policy);235+ state.store.delete_setting(&format!("policy.{key}")).await?;
236+ let policy = effective_policy(&state.config, &state.store).await?;
237+ state.set_policy(policy);
238+ }
224 record(239 record(
225 cx,240 cx,
226 Actor::User(&viewer.user.id),241 Actor::User(&viewer.user.id),
crates/im-web/src/state.rsmodified+3 -0
@@ -33,6 +33,9 @@ pub struct AppState {
33 pub anonymous_streams: Arc<Semaphore>,33 pub anonymous_streams: Arc<Semaphore>,
34 /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain.34 /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain.
35 pub stop: watch::Receiver<bool>,35 pub stop: watch::Receiver<bool>,
36+ /// Held by every change to the saved policy, from the write to the refresh of `policy_live`. Two saves
37+ /// then run one after the other, and the in-memory policy always matches what the database last committed.
38+ pub settings_lock: Arc<tokio::sync::Mutex<()>>,
36 }39 }
37 40
38 impl AppState {41 impl AppState {
docs/conventions.mdmodified+3 -2
@@ -61,8 +61,9 @@ tokens, passwords, cookies, or secrets.
61 - Constraints live in the schema (`NOT NULL`, `CHECK`, `UNIQUE`, `REFERENCES ... ON DELETE ...`), not only in Rust.61 - Constraints live in the schema (`NOT NULL`, `CHECK`, `UNIQUE`, `REFERENCES ... ON DELETE ...`), not only in Rust.
62 - Backups: `snapshot_to(path)` with `VACUUM INTO` on the writer, then checkpoint the copy so it is one62 - Backups: `snapshot_to(path)` with `VACUUM INTO` on the writer, then checkpoint the copy so it is one
63 self-contained file, then fsync. `admin backup --out DIR` writes the snapshot, the blob tree (where the app63 self-contained file, then fsync. `admin backup --out DIR` writes the snapshot, the blob tree (where the app
64- has one) and a `manifest.json` with a sha256 per file. `admin backup-verify SET` checks hashes,64+ has one), a `manifest.json` with a sha256 per file and a `manifest.mac`: HMAC-SHA256 of the manifest bytes
65- `integrity_check` and contiguous migrations. Never copy a live DB file.65+ under a subkey of the instance key, which lives outside the backup. Verify and restore check the MAC first
66+ (constant time), then hashes, `integrity_check` and contiguous migrations. Never copy a live DB file.
66 67
67 ## 5. HTTP and pages68 ## 5. HTTP and pages
68 69