diff --git a/README.md b/README.md new file mode 100644 index 0000000..34ae7bf --- /dev/null +++ b/README.md @@ -0,0 +1,173 @@ +# im + +`im` is the family's sign-in provider. It is an OpenID Connect provider (authorization code with PKCE, +EdDSA-signed ID tokens, back-channel logout), and it keeps the people directory, the photos, and the list of +family services. The family's apps (`in`, `iz`) sign people in through `im` and never see a password. + +It is one Rust binary, `im`, with a SQLite-format database (Turso), no external services, and no runtime +dependencies beyond an SMTP server if you want mail to be sent. + +## Build + +```sh +cargo build --release --workspace +install -m 0755 target/release/im /usr/local/bin/im +``` + +Run the checks the same way the project does: + +```sh +cargo fmt --all --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace +``` + +## Configuration + +The configuration is a TOML file. The default path is `config/im.toml`; set `--config ` or the +`IM_CONFIG` variable to use another. When the default file is missing, `im` creates it from +`config/im.example.toml`. + +The settings that matter first: + +| Setting | Meaning | +| --- | --- | +| `database` | The database file. Keep it inside `data_dir`. | +| `data_dir` | Holds the instance key `im.key`, the photos, and the backups. Created with mode 0700. | +| `listen` | The loopback address `im` binds to, for example `127.0.0.1:7650`. | +| `base_url` | The public origin, with no trailing slash. This is the OpenID issuer and the origin of every link in mail. | +| `trusted_proxies` | The proxies whose `X-Forwarded-For` is believed. Leave empty when nothing is in front of `im`. | + +Secrets never go in the file. Client secrets are shown once and stored as hashes. The SMTP password is read +from a file named in the configuration, and the instance key is created on first run. + +The `[policy]` section sets the sign-in policy. The admin UI can change these values at run time; a value +saved there overrides the file, and the settings page shows where each value comes from. + +## First run + +1. Start the server: `im --config /etc/im/im.toml serve`, or run the systemd unit (below). +2. Open `base_url` in a browser. With no account yet, `im` shows the setup page. Create the first + administrator there. Setup is closed once an account exists. +3. Sign in and turn on two-factor sign-in for the administrator account. The policy requires it for + administrators by default. + +## Registering the family services + +Each service that signs people in is an OpenID client. Register it from the shell on the server: + +```sh +im --config /etc/im/im.toml client add --name "in" \ + --redirect-uri https://in.example.com/auth/callback \ + --post-logout-uri https://in.example.com/ \ + --backchannel-uri https://in.example.com/auth/backchannel-logout \ + --family-key in --public-url https://in.example.com \ + --scopes "openid profile email" + +im --config /etc/im/im.toml client add --name "iz" \ + --redirect-uri https://iz.example.com/auth/callback \ + --post-logout-uri https://iz.example.com/ \ + --backchannel-uri https://iz.example.com/auth/backchannel-logout \ + --family-key iz --public-url https://iz.example.com \ + --scopes "openid profile email" +``` + +- The redirect URI is `{base}/auth/callback` of the service. +- The post-logout URI is `{base}/`. +- The back-channel logout URI is `{base}/auth/backchannel-logout`. +- The family key (`in`, `iz`) names the service in the switcher. A family key needs `--public-url`, the + origin the switcher links to. The key `im` is reserved. +- The command prints the `client_id` and the `client_secret`. The secret is shown once; store it in the + service's configuration now. + +The same clients can be managed in the admin UI under Services, where the secret is also shown once, and +where a secret can be rotated (the old one stops working at once) or a client disabled. + +Clients are listed with `im client list`, and disabled with `im client disable `. + +## Mail + +Mail is always queued in the outbox and sent through `[smtp]`. With `host` empty no attempt is made, and mail +waits in the outbox. Set `host`, `port`, `tls` (`implicit` for port 465, `starttls` for 587), `from`, +`from_name`, and, when the relay needs a login, `username` and `password_file` (first line only, not readable +by group or others). + +The admin pages show the SMTP settings (without the password), the outbox by state, and let an administrator +retry a failed mail, give up on one that is not yet sent, and send a test mail to their own address. + +## Backups and restore + +Set `[backup] dir` to a directory to turn scheduled backups on. Each run writes a set named `set-`: +a consistent snapshot of the database (`VACUUM INTO`), the photos, and a `manifest.json` with the SHA-256 of +every file. `interval_hours` sets the schedule and `keep` how many sets are kept; older sets are removed +only when they are real sets with a manifest. An optional `healthcheck_url` is pinged after each run, with +the failure URL on error (a dead-man check). + +```sh +im --config /etc/im/im.toml backup now # write a set now +im --config /etc/im/im.toml fsck # check the database and the signing keys +im --config /etc/im/im.toml restore --from # verify, then restore +``` + +`restore` verifies the set before it changes anything: every file's hash, the manifest's list of files, and +the snapshot's integrity and schema. A tampered set is refused. A verified set replaces the database and the +photos; the previous database and photos are moved into a `restore-` directory inside `data_dir`, so +nothing is lost. `restore` refuses to run while the server (or another `im` command) holds the data directory, +so stop the service first. + +## Signing keys + +`im` signs tokens with Ed25519 keys. A key signs for 90 days; its successor is created and published a day +before it signs, and a retired key stays published for seven days so that tokens it signed still verify. +Keys are maintained automatically. + +To rotate now (for example after a suspected leak of a key file): + +```sh +im --config /etc/im/im.toml keys rotate +``` + +The new key signs at once and the previous key stops signing at once; it stays published for the overlap. +The admin Keys page shows every key, its state, and the same rotation. + +## Command line + +```text +im [--config ] [serve] +im [--config ] client add --name [--redirect-uri ]... [--post-logout-uri ]... + [--backchannel-uri ] [--family-key --public-url ] [--scopes ""] +im [--config ] client list +im [--config ] client disable +im [--config ] backup now +im [--config ] restore --from +im [--config ] fsck +im [--config ] keys rotate +``` + +The commands that open the database hold the data directory's lock, so they refuse to run beside a running +server. + +## Running as a service + +`deploy/im.service` is a hardened systemd unit. It runs as the `im` user with `/etc/im/im.toml` and writes +only to `/var/lib/im`. Create the user and the directories, copy the binary and the configuration, then: + +```sh +useradd --system --home /var/lib/im --shell /usr/sbin/nologin im +install -d -o im -g im -m 0700 /var/lib/im +install -d -m 0750 /etc/im +install -m 0640 config/im.toml /etc/im/im.toml +install -m 0644 deploy/im.service /etc/systemd/system/im.service +systemctl daemon-reload +systemctl enable --now im +``` + +Put a TLS-terminating reverse proxy in front of it. `deploy/ferron.kdl` is an example Ferron site that +forwards to `127.0.0.1:7650`; `base_url` must be the same public origin. + +## Layout + +- `crates/im-core`: the domain, the store and its migrations, the configuration, keys, secrets, backups. +- `crates/im-web`: the `im` binary: pages, OpenID Connect endpoints, the admin area, live updates, the mail + and back-channel workers, and the command line. +- `docs/`: the architecture, the contracts with the family's apps, the conventions, and the attack plan. diff --git a/crates/im-core/src/backup.rs b/crates/im-core/src/backup.rs new file mode 100644 index 0000000..6e29485 --- /dev/null +++ b/crates/im-core/src/backup.rs @@ -0,0 +1,482 @@ +//! 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. +//! +//! 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. + +use std::fs::OpenOptions; +use std::io::{Read, Write}; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use turso::Builder; + +use crate::error::{Error, Result}; +use crate::store::migrate::MIGRATIONS; +use crate::store::{Store, col_int, col_text, db_err, fetch_all}; + +/// 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 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. +pub const SET_PREFIX: &str = "set-"; + +/// One file of a set: its name relative to the set, its size and its SHA-256 in lower-case hex. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FileEntry { + /// `im.db`, or `photos/`. + pub name: String, + /// Size in bytes. + pub size: u64, + /// Lower-case hex SHA-256 of the bytes. + pub sha256: String, +} + +/// The manifest of a set. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Manifest { + /// Format number; see [`FORMAT`]. + pub format: u32, + /// When the set was written, UTC. + pub created_at: String, + /// The snapshot. + pub database: FileEntry, + /// Every photo that existed when the set was written. + pub photos: Vec, +} + +/// What a restore did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RestoreOutcome { + /// Photos put back. + pub photos: usize, + /// The directory that holds the database and photos that were replaced. + pub previous: PathBuf, +} + +/// Creates a directory that only this user may enter. +fn private_dir(path: &Path) -> Result<()> { + std::fs::DirBuilder::new() + .mode(0o700) + .create(path) + .map_err(Error::from) +} + +/// Creates a file that only this user may read, failing if it exists. +fn private_file(path: &Path) -> Result { + OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .map_err(Error::from) +} + +/// 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. +pub async fn write_set( + store: &Store, + data_dir: &Path, + root: &Path, + stamp: &str, +) -> Result { + std::fs::create_dir_all(root)?; + let tmp = root.join(format!(".tmp-{stamp}")); + let final_dir = root.join(format!("{SET_PREFIX}{stamp}")); + if std::fs::symlink_metadata(&final_dir).is_ok() { + return Err(Error::Conflict(format!("set {stamp} already exists"))); + } + private_dir(&tmp)?; + match write_into(store, data_dir, &tmp).await { + Ok(()) => { + std::fs::rename(&tmp, &final_dir)?; + Ok(final_dir) + } + Err(error) => { + // A failed set was never complete. It is ours, so it is removed whole. + let _ = std::fs::remove_dir_all(&tmp); + Err(error) + } + } +} + +/// 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<()> { + let db_path = dir.join(DB_FILE); + store.snapshot_to(&db_path).await?; + let database = file_entry(DB_FILE, &db_path)?; + + let photos_out = dir.join(PHOTOS_DIR); + private_dir(&photos_out)?; + 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)? { + let source = photos_in.join(&name); + let target = photos_out.join(&name); + let mut out = private_file(&target)?; + let mut input = std::fs::File::open(&source)?; + std::io::copy(&mut input, &mut out)?; + out.sync_all()?; + photos.push(file_entry(&format!("{PHOTOS_DIR}/{name}"), &target)?); + } + } + + let manifest = Manifest { + format: FORMAT, + created_at: crate::time::now_stamp(), + database, + photos, + }; + let text = serde_json::to_string_pretty(&manifest) + .map_err(|e| Error::Invalid(format!("manifest: {e}")))?; + let mut file = private_file(&dir.join(MANIFEST_FILE))?; + file.write_all(text.as_bytes())?; + 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> { + 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) + { + names.push(name.to_owned()); + } + } + names.sort(); + 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'_') +} + +/// Size and SHA-256 of a file, read in chunks. +fn file_entry(name: &str, path: &Path) -> Result { + let (size, sha256) = file_digest(path)?; + Ok(FileEntry { + name: name.to_owned(), + size, + sha256, + }) +} + +/// Size and SHA-256 of a file, read in chunks. +fn file_digest(path: &Path) -> Result<(u64, String)> { + let mut file = std::fs::File::open(path)?; + let mut hasher = Sha256::new(); + let mut size = 0u64; + let mut buf = vec![0u8; 1 << 20]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + size += n as u64; + hasher.update(&buf[..n]); + } + Ok((size, hex::encode(hasher.finalize()))) +} + +/// Removes the oldest sets under `root` until `keep` remain. Only real directories (not links) named +/// `set-*` that hold a manifest file are touched, so a wrong `root` cannot cost unrelated data. Returns +/// how many were removed. +pub fn prune(root: &Path, keep: usize) -> Result { + let is_set = |p: &Path| { + let named = p + .file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with(SET_PREFIX)); + let real_dir = std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_dir()); + let manifest = + std::fs::symlink_metadata(p.join(MANIFEST_FILE)).is_ok_and(|m| m.file_type().is_file()); + named && real_dir && manifest + }; + let mut sets: Vec = match std::fs::read_dir(root) { + Ok(entries) => entries + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| is_set(p)) + .collect(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0), + Err(e) => return Err(e.into()), + }; + // Names carry fixed-width UTC stamps, so name order is time order. + sets.sort(); + let excess = sets.len().saturating_sub(keep); + for old in sets.iter().take(excess) { + std::fs::remove_dir_all(old)?; + } + 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)) + .map_err(|_| Error::Invalid("backup manifest is missing".into()))?; + let manifest: Manifest = serde_json::from_str(&text) + .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())); + } + 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)?; + check_entry(set, &manifest.database)?; + let mut listed = Vec::new(); + for photo in &manifest.photos { + let Some(id) = photo.name.strip_prefix("photos/") else { + return Err(Error::Invalid( + "backup manifest names a file outside photos".into(), + )); + }; + if !is_plain_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. + let photos_dir = set.join(PHOTOS_DIR); + if std::fs::symlink_metadata(&photos_dir).is_ok() { + let mut found = plain_names(&photos_dir)?; + listed.sort(); + found.sort(); + if found != listed { + return Err(Error::Invalid( + "backup photos do not match its manifest".into(), + )); + } + } + 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(), + )); + } + std::fs::create_dir_all(scratch)?; + let copy = scratch.join("verify.db"); + std::fs::copy(set.join(DB_FILE), ©)?; + let checked = check_database(©).await; + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", copy.display())); + } + checked?; + Ok(manifest) +} + +/// Checks one listed file against its size and hash. +fn check_entry(set: &Path, entry: &FileEntry) -> Result<()> { + let path = set.join(&entry.name); + let meta = std::fs::symlink_metadata(&path) + .map_err(|_| Error::Invalid(format!("backup file {} is missing", entry.name)))?; + if !meta.file_type().is_file() { + return Err(Error::Invalid(format!( + "backup file {} is not a file", + entry.name + ))); + } + let (size, sha256) = file_digest(&path)?; + if size != entry.size || sha256 != entry.sha256 { + return Err(Error::Invalid(format!( + "backup file {} does not match its manifest", + entry.name + ))); + } + Ok(()) +} + +/// Runs `PRAGMA integrity_check` on the database at `path` and checks that the recorded migrations are +/// exactly `1..=N` for the N this build knows. +pub async fn check_database(path: &Path) -> Result<()> { + let text = path + .to_str() + .ok_or_else(|| Error::Config("database path is not UTF-8".into()))?; + let db = Builder::new_local(text).build().await.map_err(db_err)?; + let conn = db.connect().map_err(db_err)?; + let checks = fetch_all(&conn, "PRAGMA integrity_check", (), |row| col_text(row, 0)).await?; + if checks != ["ok"] { + return Err(Error::Invalid(format!( + "database integrity check failed: {checks:?}" + ))); + } + let versions = fetch_all( + &conn, + "SELECT version FROM schema_migrations ORDER BY version", + (), + |row| col_int(row, 0), + ) + .await?; + let expected: Vec = MIGRATIONS.iter().map(|(v, _)| i64::from(*v)).collect(); + if versions != expected { + return Err(Error::Invalid(format!( + "database migrations are {versions:?}, expected {expected:?}" + ))); + } + Ok(()) +} + +/// Restores the database and photos from `set`. Verifies the whole set first, then moves the current +/// database (with its sidecar files) and photo directory into `data_dir/restore-/`, and puts the +/// set's copies in their place. `database` must lie inside `data_dir`. +pub async fn restore( + data_dir: &Path, + database: &Path, + set: &Path, + stamp: &str, +) -> Result { + let data_dir = std::fs::canonicalize(data_dir)?; + let parent = database + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + if !std::fs::canonicalize(parent)?.starts_with(&data_dir) { + return Err(Error::Config( + "restore only replaces a database inside data_dir".into(), + )); + } + let previous = data_dir.join(format!("restore-{stamp}")); + if std::fs::symlink_metadata(&previous).is_ok() { + return Err(Error::Conflict(format!( + "{} already exists", + previous.display() + ))); + } + let scratch = data_dir.join(format!(".verify-{stamp}")); + let manifest = verify_set(set, &scratch).await; + let _ = std::fs::remove_dir_all(&scratch); + let manifest = manifest?; + + private_dir(&previous)?; + // 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::File::open(&staged)?.sync_all()?; + for suffix in ["", "-wal", "-shm"] { + let mut from = database.as_os_str().to_owned(); + from.push(suffix); + let from = PathBuf::from(from); + if std::fs::symlink_metadata(&from).is_ok() { + let mut to = previous.join("database"); + to.as_mut_os_string().push(suffix); + std::fs::rename(&from, &to)?; + } + } + std::fs::rename(&staged, database)?; + + let photos = data_dir.join(PHOTOS_DIR); + if std::fs::symlink_metadata(&photos).is_ok() { + std::fs::rename(&photos, previous.join(PHOTOS_DIR))?; + } + private_dir(&photos)?; + for photo in &manifest.photos { + let id = photo.name.trim_start_matches("photos/"); + let target = photos.join(id); + std::fs::copy(set.join(&photo.name), &target)?; + std::fs::File::open(&target)?.sync_all()?; + } + std::fs::File::open(&data_dir)?.sync_all()?; + Ok(RestoreOutcome { + photos: manifest.photos.len(), + previous, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 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(); + store + .create_first_admin("ada@example.com", "Ada", "h") + .await + .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(); + (store, set) + } + + #[tokio::test] + async fn a_good_set_restores_and_a_tampered_one_is_refused() { + 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"); + + // 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!(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") + .await + .unwrap(); + assert_eq!(outcome.photos, 1); + assert_eq!( + std::fs::read(data.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO")).unwrap(), + b"png-bytes" + ); + } + + #[tokio::test] + async fn prune_touches_only_real_sets_with_a_manifest() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + for name in ["set-1", "set-2", "set-3"] { + std::fs::create_dir_all(root.join(name)).unwrap(); + std::fs::write(root.join(name).join(MANIFEST_FILE), b"{}").unwrap(); + } + std::fs::create_dir_all(root.join("notes")).unwrap(); + assert_eq!(prune(root, 2).unwrap(), 1); + assert!(!root.join("set-1").exists()); + assert!(root.join("set-2").exists() && root.join("set-3").exists()); + assert!(root.join("notes").exists()); + } +} diff --git a/crates/im-core/src/config.rs b/crates/im-core/src/config.rs index f45df5a..0c7b959 100644 --- a/crates/im-core/src/config.rs +++ b/crates/im-core/src/config.rs @@ -137,9 +137,10 @@ impl BackupConfig { } } -/// Sign-in policy. These are the file values; a value saved in the admin UI wins over them once that -/// UI exists (`docs/architecture.md` section 7). -#[derive(Debug, Clone, Deserialize)] +/// Sign-in policy. These are the file values. A value saved in the admin UI is stored in `settings` +/// under `policy.` and wins over them (`docs/architecture.md` section 7); see +/// [`PolicyConfig::set`] and [`Config::explicit_policy`]. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct PolicyConfig { /// An administrator without two-factor sign-in is sent to enrol it after signing in, and cannot @@ -159,6 +160,16 @@ pub struct PolicyConfig { pub email_change_hours: u32, } +/// The policy keys, in the order the admin page shows them. Each is stored as `policy.`. +pub const POLICY_KEYS: [&str; 6] = [ + "require_2fa_for_admins", + "max_sessions", + "session_max_days", + "invite_days", + "reset_minutes", + "email_change_hours", +]; + impl Default for PolicyConfig { fn default() -> Self { Self { @@ -172,6 +183,66 @@ impl Default for PolicyConfig { } } +impl PolicyConfig { + /// The ranges of the policy values. Used for the file and for every value saved in the UI. + pub fn validate(&self) -> Result<()> { + if self.max_sessions == 0 { + return Err(Error::Config( + "[policy] max_sessions must be at least 1".into(), + )); + } + if !(1..=365).contains(&self.session_max_days) { + return Err(Error::Config( + "[policy] session_max_days must be between 1 and 365".into(), + )); + } + if !(1..=30).contains(&self.invite_days) { + return Err(Error::Config( + "[policy] invite_days must be between 1 and 30".into(), + )); + } + if !(5..=1440).contains(&self.reset_minutes) { + return Err(Error::Config( + "[policy] reset_minutes must be between 5 and 1440".into(), + )); + } + if !(1..=168).contains(&self.email_change_hours) { + return Err(Error::Config( + "[policy] email_change_hours must be between 1 and 168".into(), + )); + } + Ok(()) + } + + /// Returns a copy with `key` set to `value`, checked. A key outside [`POLICY_KEYS`] or a value + /// that does not parse or is out of range is an error that names the key. + pub fn set(&self, key: &str, value: &str) -> Result { + let mut next = self.clone(); + let number = |text: &str| -> Result { + text.trim() + .parse::() + .map_err(|_| Error::Invalid(format!("{key} must be a whole number"))) + }; + match key { + "require_2fa_for_admins" => { + next.require_2fa_for_admins = match value.trim() { + "true" | "on" | "1" => true, + "false" | "off" | "0" | "" => false, + _ => return Err(Error::Invalid(format!("{key} must be true or false"))), + }; + } + "max_sessions" => next.max_sessions = number(value)?, + "session_max_days" => next.session_max_days = number(value)?, + "invite_days" => next.invite_days = number(value)?, + "reset_minutes" => next.reset_minutes = number(value)?, + "email_change_hours" => next.email_change_hours = number(value)?, + other => return Err(Error::Invalid(format!("{other} is not a policy setting"))), + } + next.validate().map_err(|e| Error::Invalid(e.to_string()))?; + Ok(next) + } +} + /// The whole file. Field names are the TOML keys. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] @@ -201,6 +272,10 @@ pub struct Config { /// Sign-in policy. #[serde(default)] pub policy: PolicyConfig, + /// The policy keys that the file sets explicitly, so the admin page can say "file" rather than + /// "default". Not read from TOML: [`Config::parse`] fills it. + #[serde(skip)] + pub explicit_policy: Vec, } impl Config { @@ -225,8 +300,14 @@ impl Config { /// Parses and validates TOML text. Used by [`Config::load`] and by tests. pub fn parse(text: &str) -> Result { - let config: Config = toml::from_str(text).map_err(|e| Error::Config(format!("{e}")))?; + let mut config: Config = toml::from_str(text).map_err(|e| Error::Config(format!("{e}")))?; config.validate()?; + // A second, loose read of the same text: which [policy] keys the file names. + if let Ok(table) = text.parse::() + && let Some(toml::Value::Table(policy)) = table.get("policy") + { + config.explicit_policy = policy.keys().cloned().collect(); + } Ok(config) } @@ -249,31 +330,7 @@ impl Config { return Err(Error::Config("[backup] keep must be at least 1".into())); } } - if self.policy.max_sessions == 0 { - return Err(Error::Config( - "[policy] max_sessions must be at least 1".into(), - )); - } - if !(1..=365).contains(&self.policy.session_max_days) { - return Err(Error::Config( - "[policy] session_max_days must be between 1 and 365".into(), - )); - } - if !(1..=30).contains(&self.policy.invite_days) { - return Err(Error::Config( - "[policy] invite_days must be between 1 and 30".into(), - )); - } - if !(5..=1440).contains(&self.policy.reset_minutes) { - return Err(Error::Config( - "[policy] reset_minutes must be between 5 and 1440".into(), - )); - } - if !(1..=168).contains(&self.policy.email_change_hours) { - return Err(Error::Config( - "[policy] email_change_hours must be between 1 and 168".into(), - )); - } + self.policy.validate()?; self.validate_smtp()?; let hc = &self.backup.healthcheck_url; if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) { diff --git a/crates/im-core/src/lib.rs b/crates/im-core/src/lib.rs index 2eb4541..c55feac 100644 --- a/crates/im-core/src/lib.rs +++ b/crates/im-core/src/lib.rs @@ -3,6 +3,7 @@ //! This crate has no HTTP code. It holds the pieces every other part of `im` depends on, so that //! the web binary cannot get a security primitive or a database rule wrong by re-implementing it. +pub mod backup; pub mod config; pub mod error; pub mod jwt; diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index a67f30e..200e83d 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -158,6 +158,46 @@ pub enum AuditAction { EmailChangeCancelled, /// The address of an account was changed. EmailChanged, + /// An administrator disabled an account. + UserDisabled, + /// An administrator enabled an account again. + UserEnabled, + /// An administrator made an account an administrator. + AdminGranted, + /// An administrator removed the administrator flag of an account. + AdminRemoved, + /// An administrator reset the two-factor sign-in of an account. + AdminTwoFactorReset, + /// An administrator ended every session of an account. + AdminSessionsRevoked, + /// An administrator deleted an account. + UserDeleted, + /// An administrator revoked an invitation. + InviteRevoked, + /// An administrator registered an OpenID client. + ClientCreated, + /// An administrator changed a client's settings. + ClientUpdated, + /// An administrator issued a new client secret. + ClientSecretRotated, + /// An administrator disabled a client. + ClientDisabled, + /// An administrator sent a failed mail again. + MailRetried, + /// An administrator gave up on a mail. + MailAbandoned, + /// An administrator queued a test mail. + MailTestQueued, + /// An administrator queued a message to everyone or to one address. + MessageSent, + /// An administrator saved policy settings. + SettingsChanged, + /// An administrator rotated the signing key. + KeyRotated, + /// An administrator retired a signing key. + KeyRetired, + /// A backup set was written (scheduled, or by `im backup now`). + BackupWritten, } impl AuditAction { @@ -187,6 +227,26 @@ impl AuditAction { AuditAction::EmailChangeConfirmed => "email_change.confirmed", AuditAction::EmailChangeCancelled => "email_change.cancelled", AuditAction::EmailChanged => "email.changed", + AuditAction::UserDisabled => "user.disabled", + AuditAction::UserEnabled => "user.enabled", + AuditAction::AdminGranted => "admin.granted", + AuditAction::AdminRemoved => "admin.removed", + AuditAction::AdminTwoFactorReset => "admin.2fa_reset", + AuditAction::AdminSessionsRevoked => "admin.sessions_revoked", + AuditAction::UserDeleted => "user.deleted", + AuditAction::InviteRevoked => "invite.revoked", + AuditAction::ClientCreated => "client.created", + AuditAction::ClientUpdated => "client.updated", + AuditAction::ClientSecretRotated => "client.secret_rotated", + AuditAction::ClientDisabled => "client.disabled", + AuditAction::MailRetried => "mail.retried", + AuditAction::MailAbandoned => "mail.abandoned", + AuditAction::MailTestQueued => "mail.test", + AuditAction::MessageSent => "message.sent", + AuditAction::SettingsChanged => "settings.changed", + AuditAction::KeyRotated => "keys.rotated", + AuditAction::KeyRetired => "keys.retired", + AuditAction::BackupWritten => "backup.written", } } } diff --git a/crates/im-core/src/store/admin.rs b/crates/im-core/src/store/admin.rs new file mode 100644 index 0000000..5c2d8f2 --- /dev/null +++ b/crates/im-core/src/store/admin.rs @@ -0,0 +1,542 @@ +//! Writes and listings that only the administrator pages make: admin rights, enabling and deleting +//! accounts, the user search, clients and their services, the mail outbox, signing keys and the policy +//! overrides. +//! +//! The rules that must hold under concurrency are single conditional statements, so two requests cannot +//! both succeed: +//! +//! - the last enabled administrator cannot be demoted, disabled or deleted (`set_admin`, `delete_user`, +//! and the same guard in `users::disable_user`); +//! - the signing key that is current cannot be retired (`retire_signing_key`); +//! - a mail row is retried or abandoned only in the states that allow it (`retry_mail`, `abandon_mail`). +//! +//! Who may call these is decided by the web layer. Nothing here knows about the session. + +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::directory::{ChangeKind, record_change}; +use crate::store::invites::{Invite, map_invite}; +use crate::store::users::{USER_COLS, map_user}; +use crate::store::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish}; +use crate::time::now_stamp; + +/// The result of [`Store::set_admin`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AdminChange { + /// The flag was changed. + Changed, + /// The account already had that flag. + Unchanged, + /// The change would leave no enabled administrator, so it was refused. + LastAdmin, +} + +/// One row of the mail outbox, as the administrator sees it. The body is never included. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OutboxRow { + /// ULID. Newer rows have larger ids. + pub id: String, + /// The mail kind. + pub kind: String, + /// The recipient address. + pub to_addr: String, + /// The subject. + pub subject: String, + /// `pending`, `sent`, `failed` or `abandoned`. + pub state: String, + /// Attempts made so far. + pub attempts: i64, + /// When the row is next due. + pub next_attempt_at: String, + /// The last failure, without secrets. + pub last_error: Option, + /// When the row was queued. + pub created_at: String, +} + +/// The fields of a client that an administrator can edit. The URIs must already be checked. +#[derive(Debug, Clone)] +pub struct ClientEdit<'a> { + /// Display name. + pub name: &'a str, + /// Exact redirect URIs. + pub redirect_uris: &'a [String], + /// Exact post-logout redirect URIs. + pub post_logout_redirect_uris: &'a [String], + /// Back-channel logout endpoint, if any. + pub backchannel_logout_uri: Option<&'a str>, + /// Space-separated scopes. + pub allowed_scopes: &'a str, + /// Family key, if the client is a family service. Unique. + pub service_key: Option<&'a str>, +} + +impl Store { + /// Grants or removes instance administration. Removing it from the last enabled administrator is + /// refused by the same statement that would do it, so two parallel demotions cannot both succeed. + pub async fn set_admin(&self, user_id: &str, is_admin: bool) -> Result { + let flag = i64::from(is_admin); + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE users SET is_admin = ?2, updated_at = ?3 \ + WHERE id = ?1 AND is_admin <> ?2 \ + AND (?2 = 1 OR disabled_at IS NOT NULL \ + OR (SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", + (user_id.to_string(), flag, now_stamp()), + ) + .await + .map_err(db_err)?; + if changed == 1 { + return Ok(AdminChange::Changed); + } + let current = fetch_opt( + &conn, + "SELECT is_admin FROM users WHERE id = ?1", + (user_id.to_string(),), + |row| col_int(row, 0), + ) + .await?; + match current { + None => Err(Error::NotFound), + Some(value) if value == flag => Ok(AdminChange::Unchanged), + Some(_) => Ok(AdminChange::LastAdmin), + } + } + + /// Number of enabled administrators. The admin pages show it and refuse to leave none. + pub async fn enabled_admin_count(&self) -> Result { + let conn = self.read_conn().await; + let count = fetch_opt( + &conn, + "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL", + (), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + u64::try_from(count).map_err(|_| Error::Database("negative count".into())) + } + + /// Clears the disabled mark of an account. The directory feed records the change. Returns false when + /// the account is missing or was not disabled. + pub async fn enable_user(&self, user_id: &str) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let changed = tx + .execute( + "UPDATE users SET disabled_at = NULL, updated_at = ?2 \ + WHERE id = ?1 AND disabled_at IS NOT NULL", + (user_id.to_string(), now), + ) + .await + .map_err(db_err)?; + if changed != 1 { + return Ok(false); + } + record_change(&tx, user_id, ChangeKind::Member).await?; + Ok(true) + } + .await; + let result = finish(tx, outcome).await; + if matches!(result, Ok(true)) { + self.announce_directory(); + } + result + } + + /// Deletes an account and everything that belonged to it: sessions and their client links, recovery + /// codes, reset and email-change links, and a pending two-factor enrolment. The rows that remain + /// name the person only by id (audit entries and invitations that person sent). Back-channel logouts + /// are queued first, and the directory feed records a `deleted` change. The last enabled + /// administrator cannot be deleted. Returns false when there was no such account. + /// + /// The caller removes the profile photo file after this returns. + pub async fn delete_user(&self, user_id: &str) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let exists = fetch_opt( + &tx, + "SELECT id FROM users WHERE id = ?1", + (user_id.to_string(),), + |row| col_text(row, 0), + ) + .await?; + if exists.is_none() { + return Ok(false); + } + // Queued before the sessions go, because the client links are read from them. + backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; + let removed = tx + .execute( + "DELETE FROM users WHERE id = ?1 \ + AND (is_admin = 0 OR disabled_at IS NOT NULL \ + OR (SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", + (user_id.to_string(),), + ) + .await + .map_err(db_err)?; + if removed != 1 { + // Returned as an error so the transaction, with its queued logouts, is rolled back. + return Err(Error::Conflict( + "the last enabled administrator cannot be deleted".into(), + )); + } + tx.execute( + "DELETE FROM settings WHERE key = ?1", + (format!("totp_pending:{user_id}"),), + ) + .await + .map_err(db_err)?; + record_change(&tx, user_id, ChangeKind::Deleted).await?; + Ok(true) + } + .await; + let result = finish(tx, outcome).await; + if matches!(result, Ok(true)) { + self.announce_directory(); + } + result + } + + /// A page of accounts, newest first. `search` matches a part of the address or the name, in any + /// case. `after` is the `(created_at, id)` of the last account of the previous page. Returns up to + /// `limit` accounts. + pub async fn list_users( + &self, + search: Option<&str>, + after: Option<(&str, &str)>, + limit: u32, + ) -> Result> { + let term = search + .map(|s| s.trim().to_lowercase()) + .filter(|s| !s.is_empty()); + let (after_at, after_id) = match after { + Some((at, id)) => (Some(at.to_owned()), Some(id.to_owned())), + None => (None, None), + }; + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {USER_COLS} FROM users \ + WHERE (?1 IS NULL OR instr(email_folded, ?1) > 0 OR instr(lower(name), ?1) > 0) \ + AND (?2 IS NULL OR created_at < ?2 OR (created_at = ?2 AND id < ?3)) \ + ORDER BY created_at DESC, id DESC LIMIT ?4" + ), + (term, after_at, after_id, i64::from(limit)), + map_user, + ) + .await + } + + /// Invitations that can still be used, newest first. + pub async fn pending_invites(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT token_hash, email_folded, is_admin, expires_at, accepted_at FROM invites \ + WHERE accepted_at IS NULL AND expires_at > ?1 ORDER BY created_at DESC, token_hash", + (now_stamp(),), + map_invite, + ) + .await + } + + /// The invitation with this token hash, while it can still be used. + pub async fn pending_invite(&self, token_hash: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT token_hash, email_folded, is_admin, expires_at, accepted_at FROM invites \ + WHERE token_hash = ?1 AND accepted_at IS NULL AND expires_at > ?2", + (token_hash.to_string(), now_stamp()), + map_invite, + ) + .await + } + + /// Deletes an invitation that was not used. Returns false when it was used or is unknown. + pub async fn revoke_invite(&self, token_hash: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "DELETE FROM invites WHERE token_hash = ?1 AND accepted_at IS NULL", + (token_hash.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// Ends every live session of a person, with their back-channel logouts. Returns the ids ended. + pub async fn end_all_sessions(&self, user_id: &str, reason: EndReason) -> Result> { + self.end_matching(user_id, None, reason).await + } + + /// Updates the editable fields of a client. A family key that another client holds is a conflict. + /// Services that pointed to this client under another key are unlinked in the same transaction. + /// Returns false when there is no such client. + pub async fn update_client(&self, id: &str, edit: &ClientEdit<'_>) -> Result { + let redirect_uris = + serde_json::to_string(edit.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?; + let post_logout = serde_json::to_string(edit.post_logout_redirect_uris) + .map_err(|e| Error::Invalid(e.to_string()))?; + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let changed = tx + .execute( + "UPDATE clients SET name = ?2, redirect_uris = ?3, post_logout_redirect_uris = ?4, \ + backchannel_logout_uri = ?5, allowed_scopes = ?6, service_key = ?7 \ + WHERE id = ?1", + ( + id.to_string(), + edit.name.to_string(), + redirect_uris, + post_logout, + edit.backchannel_logout_uri.map(str::to_owned), + edit.allowed_scopes.to_string(), + edit.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) + } + })?; + if changed != 1 { + return Ok(false); + } + tx.execute( + "UPDATE services SET client_id = NULL WHERE client_id = ?1 AND key IS NOT ?2", + (id.to_string(), edit.service_key.map(str::to_owned)), + ) + .await + .map_err(db_err)?; + Ok(true) + } + .await; + finish(tx, outcome).await + } + + /// Replaces the secret hash of a client. The old secret stops working at once. + pub async fn rotate_client_secret(&self, id: &str, secret_hash: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE clients SET secret_hash = ?2, secret_rotated_at = ?3 WHERE id = ?1", + (id.to_string(), secret_hash.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// Creates or updates the switcher row of a family service and links it to its client. + pub async fn link_service( + &self, + key: &str, + name: &str, + url: &str, + 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(()) + } + + /// The client with this id, enabled or not. Used by the admin client pages. + pub async fn client_row(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {} FROM clients WHERE id = ?1", CLIENT_COLS), + (id.to_string(),), + map_client, + ) + .await + } + + /// One page of the mail outbox, newest first, optionally only one state. `after` is the id of the + /// last row of the previous page. + pub async fn outbox_page( + &self, + state: Option<&str>, + after: Option<&str>, + limit: u32, + ) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT id, kind, to_addr, subject, state, attempts, next_attempt_at, last_error, created_at \ + FROM mail_outbox \ + WHERE (?1 IS NULL OR state = ?1) AND (?2 IS NULL OR id < ?2) \ + ORDER BY id DESC LIMIT ?3", + ( + state.map(str::to_owned), + after.map(str::to_owned), + i64::from(limit), + ), + map_outbox, + ) + .await + } + + /// How many rows the outbox holds in each state. + pub async fn outbox_counts(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT state, COUNT(*) FROM mail_outbox GROUP BY state ORDER BY state", + (), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + ) + .await + } + + /// Sends a failed row again now. Only a `failed` row whose body is still held can be retried. + pub async fn retry_mail(&self, id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE mail_outbox SET state = 'pending', next_attempt_at = ?2 \ + WHERE id = ?1 AND state = 'failed' AND body_text <> ''", + (id.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// Gives up on a row that is not yet sent: its body is blanked, as the worker does on abandonment. + pub async fn abandon_mail(&self, id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE mail_outbox SET state = 'abandoned', body_text = '', \ + last_error = 'abandoned by an administrator' \ + WHERE id = ?1 AND state IN ('pending', 'failed')", + (id.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// Retires a published signing key that is not the current one. Its public key stays published for + /// the usual overlap, so tokens it signed still verify. The current key cannot be retired: the + /// statement excludes it, so a token can always be signed. + pub async fn retire_signing_key(&self, kid: &str) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE signing_keys SET retires_at = ?2 \ + WHERE kid = ?1 AND retires_at IS NULL AND activates_at <= ?2 \ + AND kid <> (SELECT kid FROM signing_keys WHERE retires_at IS NULL AND activates_at <= ?2 \ + ORDER BY activates_at DESC, kid DESC LIMIT 1)", + (kid.to_string(), now), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// 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; + let changed = conn + .execute("DELETE FROM settings WHERE key = ?1", (key.to_string(),)) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + + /// The settings whose key starts with `prefix`, in key order. + pub async fn settings_with_prefix(&self, prefix: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT key, value FROM settings WHERE substr(key, 1, length(?1)) = ?1 ORDER BY key", + (prefix.to_string(),), + |row: &Row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await + } +} + +/// Maps a row selected as `id, kind, to_addr, subject, state, attempts, next_attempt_at, last_error, +/// created_at`. +fn map_outbox(row: &Row) -> Result { + Ok(OutboxRow { + id: col_text(row, 0)?, + kind: col_text(row, 1)?, + to_addr: col_text(row, 2)?, + subject: col_text(row, 3)?, + state: col_text(row, 4)?, + attempts: col_int(row, 5)?, + next_attempt_at: col_text(row, 6)?, + last_error: crate::store::col_opt_text(row, 7)?, + created_at: col_text(row, 8)?, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + async fn store_with_users() -> (tempfile::TempDir, Store, String, String) { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + let first = store + .create_first_admin("ada@example.com", "Ada", "h") + .await + .unwrap(); + let second = store + .create_user("bob@example.com", "Bob", "h", true) + .await + .unwrap(); + (dir, store, first.id, second.id) + } + + #[tokio::test] + async fn the_last_enabled_admin_cannot_be_demoted_disabled_or_deleted() { + let (_dir, store, first, second) = store_with_users().await; + // Two admins: one may go. + assert!(store.disable_user(&second).await.unwrap()); + // `second` is disabled now, so `first` is the last enabled admin. + assert_eq!( + store.set_admin(&first, false).await.unwrap(), + AdminChange::LastAdmin + ); + assert!(!store.disable_user(&first).await.unwrap()); + assert!(store.delete_user(&first).await.is_err()); + assert_eq!(store.enabled_admin_count().await.unwrap(), 1); + assert!(store.user_by_id(&first).await.unwrap().is_some()); + } +} diff --git a/crates/im-core/src/store/clients.rs b/crates/im-core/src/store/clients.rs index 33d487c..d07231e 100644 --- a/crates/im-core/src/store/clients.rs +++ b/crates/im-core/src/store/clients.rs @@ -12,7 +12,7 @@ use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, use crate::time::now_stamp; /// The columns of a client row, in the order [`map_client`] reads them. -const CLIENT_COLS: &str = "id, name, secret_hash, secret_rotated_at, redirect_uris, \ +pub(crate) const CLIENT_COLS: &str = "id, name, secret_hash, secret_rotated_at, redirect_uris, \ post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, created_at, \ disabled_at"; @@ -22,7 +22,7 @@ fn uri_list(row: &Row, i: usize) -> Result> { } /// Maps a row selected with [`CLIENT_COLS`]. -fn map_client(row: &Row) -> Result { +pub(crate) fn map_client(row: &Row) -> Result { Ok(Client { id: col_text(row, 0)?, name: col_text(row, 1)?, diff --git a/crates/im-core/src/store/invites.rs b/crates/im-core/src/store/invites.rs index 986be40..3e4ad51 100644 --- a/crates/im-core/src/store/invites.rs +++ b/crates/im-core/src/store/invites.rs @@ -43,7 +43,7 @@ pub enum AcceptOutcome { Refused, } -fn map_invite(row: &turso::Row) -> Result { +pub(crate) fn map_invite(row: &turso::Row) -> Result { Ok(Invite { token_hash: col_text(row, 0)?, email_folded: col_text(row, 1)?, diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index f09e3e2..43c9503 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -6,6 +6,7 @@ //! connection gets WAL, `synchronous = FULL`, `foreign_keys = ON` and a busy timeout, and the values //! in effect are logged at boot. +pub mod admin; pub mod audit; pub mod backchannel; pub mod clients; diff --git a/crates/im-core/src/store/sessions.rs b/crates/im-core/src/store/sessions.rs index 9327026..b1a9195 100644 --- a/crates/im-core/src/store/sessions.rs +++ b/crates/im-core/src/store/sessions.rs @@ -365,7 +365,8 @@ impl Store { .await } - async fn end_matching( + /// Ends every live session of `user_id`, with their back-channel logouts. Returns the ids ended. + pub(crate) async fn end_matching( &self, user_id: &str, keep: Option<&str>, diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs index 4450fa6..bcda7cd 100644 --- a/crates/im-core/src/store/users.rs +++ b/crates/im-core/src/store/users.rs @@ -334,7 +334,8 @@ impl Store { Ok(()) } - /// Disables an account. In one transaction: the account is marked disabled, the directory feed + /// Disables an account. The last enabled administrator cannot be disabled: that is part of the + /// same conditional `UPDATE`, so two parallel requests cannot both disable the last two. In one transaction: the account is marked disabled, the directory feed /// records the change, one `sub`-only back-channel logout is queued for every client the person /// used (contracts.md 2.5), the refresh tokens are revoked and every session is deleted. Returns /// false, with nothing changed, when the account is missing or already disabled. @@ -346,7 +347,9 @@ impl Store { let changed = tx .execute( "UPDATE users SET disabled_at = ?2, updated_at = ?2 \ - WHERE id = ?1 AND disabled_at IS NULL", + WHERE id = ?1 AND disabled_at IS NULL \ + AND (is_admin = 0 OR (SELECT COUNT(*) FROM users \ + WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", (user_id.to_string(), now.clone()), ) .await diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index a21bb4b..d09e99a 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -105,16 +105,13 @@ pub async fn require_user(cx: &Cx) -> Result { /// The signed-in administrator. A person who is not an administrator gets 404, the same answer as a /// page that does not exist. An administrator without two-factor sign-in, while the policy requires /// it, is sent to the security page instead. -/// -/// Not every handler needs it yet; the admin pages that use it come after the account pages. -#[allow(dead_code)] pub async fn require_admin(cx: &Cx) -> Result { let viewer = require_user(cx).await?; if !viewer.user.is_admin { return Err(not_found().into()); } let state = app_context::(cx); - if state.config.policy.require_2fa_for_admins && !viewer.user.totp_enabled() { + if state.policy().require_2fa_for_admins && !viewer.user.totp_enabled() { return Err(see_other("/account/security?notice=enrol").into()); } Ok(viewer) @@ -131,6 +128,17 @@ pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result { } } +/// The signed-in administrator, when the submitted `csrf` field matches their session. A member gets 404 +/// first, before the token is looked at, so a form of the admin area gives no hint to a member. +pub async fn require_admin_csrf(cx: &Cx, submitted: &str) -> Result { + let viewer = require_admin(cx).await?; + if check_csrf(&viewer.session, submitted) { + Ok(viewer) + } else { + Err(forbidden().into()) + } +} + /// True only when `submitted` is the session's CSRF token, compared in constant time. An empty /// stored token never matches, not even an empty submission. pub fn check_csrf(session: &Session, submitted: &str) -> bool { @@ -146,7 +154,7 @@ pub fn check_csrf(session: &Session, submitted: &str) -> bool { /// applied inside the store, in the same write. pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { let state = app_context::(cx); - let max_age = Duration::from_secs(u64::from(state.config.policy.session_max_days) * DAY); + let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY); if let Some(old) = presented_session(cx) .await? .filter(|old| old.user_id == user.id) @@ -173,7 +181,7 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { idle: SESSION_IDLE, max_age, }, - state.config.policy.max_sessions, + state.policy().max_sessions, ) .await?; // Sessions ended by the cap were queued for back-channel logout in the store's transaction. @@ -346,7 +354,7 @@ pub async fn check_second_factor( /// Where a person goes after signing in. An administrator without two-factor sign-in goes to the /// security page to enrol it, while the policy requires that. Anyone else goes to `next`. pub fn after_sign_in(state: &AppState, user: &User, next: &str) -> String { - if user.is_admin && state.config.policy.require_2fa_for_admins && !user.totp_enabled() { + if user.is_admin && state.policy().require_2fa_for_admins && !user.totp_enabled() { "/account/security?notice=enrol".to_owned() } else { safe_next(Some(next)).to_owned() diff --git a/crates/im-web/src/backups.rs b/crates/im-web/src/backups.rs new file mode 100644 index 0000000..457add0 --- /dev/null +++ b/crates/im-web/src/backups.rs @@ -0,0 +1,131 @@ +//! Scheduled backups: when a run is due, the set is written, older sets are pruned, and the outcome is +//! recorded and sent to the dead-man URL. +//! +//! The worker runs only when `[backup] dir` is set. A run is due when none was attempted yet, or when the +//! last attempt is at least `interval_hours` old. The attempt time is recorded before the run, so a failing +//! run is retried at the interval and not every minute. The same [`run_and_record`] serves `im backup now`. +//! +//! The dead-man URL gets `/start` before a run, `` after a good run and `/fail` after a bad +//! one. A ping that fails is logged and never fails the backup. + +use std::time::Duration; + +use im_core::backup; +use im_core::config::Config; +use im_core::store::Store; +use im_core::time::{now_stamp, unix_now, unix_seconds}; +use tokio::task::JoinHandle; + +use crate::backchannel::http_client; +use crate::live::stopped; +use crate::state::AppState; + +/// How often the worker checks whether a run is due. +const TICK: Duration = Duration::from_secs(60); + +/// Settings key: when a run was last attempted (a stamp). +pub const LAST_ATTEMPT: &str = "backup.last_attempt"; +/// Settings key: when a run last succeeded (a stamp). +pub const LAST_SUCCESS: &str = "backup.last_success"; +/// Settings key: the reason the last run failed, when it did. Never a path to a secret. +pub const LAST_ERROR: &str = "backup.last_error"; + +/// Starts the worker when backups are configured. Returns `None` when they are off. The task ends when +/// the stop flag is set. +pub fn spawn(state: AppState) -> Option> { + if !state.config.backup.enabled() { + return None; + } + let mut stop = state.stop.clone(); + Some(tokio::spawn(async move { + loop { + tokio::select! { + () = tokio::time::sleep(TICK) => {} + () = stopped(&mut stop) => break, + } + if due(&state.store, &state.config).await + && let Err(error) = run_and_record(&state.config, &state.store).await + { + tracing::error!(error = %error, "scheduled backup failed"); + } + } + })) +} + +/// True when no run was attempted yet, or the last attempt is at least `interval_hours` old. +async fn due(store: &Store, config: &Config) -> bool { + let Ok(last) = store.setting(LAST_ATTEMPT).await else { + return false; + }; + let Some(last) = last.and_then(|stamp| unix_seconds(&stamp)) else { + return true; + }; + let interval = + i64::try_from(config.backup.interval_hours.saturating_mul(3600)).unwrap_or(i64::MAX); + unix_now().saturating_sub(last) >= interval +} + +/// Writes one set, prunes the old ones and records the outcome. Returns the set's directory on success. +/// +/// 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 { + let http = http_client(); + let base = config + .backup + .healthcheck_url + .trim_end_matches('/') + .to_owned(); + let has_ping = !base.is_empty(); + let stamp = now_stamp().replace([':', '.'], "-"); + if let Err(error) = store.set_setting(LAST_ATTEMPT, &now_stamp()).await { + tracing::error!(error = %error, "backup attempt not recorded"); + } + if has_ping { + ping(&http, &format!("{base}/start")).await; + } + let outcome = write_and_prune(config, store, &stamp).await; + match &outcome { + Ok(set) => { + tracing::info!(set = %set.display(), "backup written"); + let _ = store.set_setting(LAST_SUCCESS, &now_stamp()).await; + let _ = store.set_setting(LAST_ERROR, "").await; + if has_ping { + ping(&http, &base).await; + } + } + Err(error) => { + tracing::error!(error = %error, "backup failed"); + let _ = store.set_setting(LAST_ERROR, &error.to_string()).await; + if has_ping { + ping(&http, &format!("{base}/fail")).await; + } + } + } + outcome +} + +/// Writes the set and removes the sets beyond `keep`. +async fn write_and_prune( + config: &Config, + store: &Store, + stamp: &str, +) -> im_core::Result { + let set = backup::write_set(store, &config.data_dir, &config.backup.dir, stamp).await?; + let removed = backup::prune(&config.backup.dir, config.backup.keep as usize)?; + if removed > 0 { + tracing::info!(removed, "old backup sets removed"); + } + Ok(set) +} + +/// Sends one dead-man ping. Failures are logged; they never fail the backup. +async fn ping(http: &reqwest::Client, url: &str) { + match http.get(url).send().await { + Ok(response) if response.status().is_success() => {} + Ok(response) => { + tracing::warn!(status = %response.status(), "dead-man ping answered with an error"); + } + Err(error) => tracing::warn!(error = %error, "dead-man ping failed"), + } +} diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index 4ef1216..ece966d 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -3,14 +3,14 @@ //! The order follows `docs/conventions.md` section 2: load the configuration, create the data //! directory with mode 0700, load or create the instance key, open the database (which applies //! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or -//! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them. +//! Ctrl-C. Stored UI overrides of the policy are layered on the file values here, once, at boot. use std::fs::{File, OpenOptions, TryLockError}; use std::os::unix::fs::PermissionsExt; use std::path::Path; -use std::sync::Arc; +use std::sync::{Arc, RwLock}; -use im_core::config::Config; +use im_core::config::{Config, PolicyConfig}; use im_core::photo::MAX_UPLOAD_BYTES; use im_core::secret; use im_core::store::Store; @@ -83,6 +83,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { stop: stop_rx.clone(), ..state }; + let backup_task = crate::backups::spawn(state.clone()); tokio::spawn(async move { shutdown_signal().await; tracing::info!("shutdown signal received"); @@ -113,6 +114,9 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { let _ = backchannel_worker.await; let _ = sweeper_task.await; let _ = mail_worker.await; + if let Some(task) = backup_task { + let _ = task.await; + } tracing::info!("im stopped"); Ok(()) } @@ -134,6 +138,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { } let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; let store = Store::open(&config.database).await?; + let policy = effective_policy(&config, &store).await?; signing::maintain(&store, &key).await?; // im is in its own switcher list. The row follows the configured origin at every boot. store @@ -141,6 +146,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { .await?; Ok(AppState { config: Arc::new(config), + policy_live: Arc::new(RwLock::new(policy)), store, key: Arc::new(key), live: Arc::new(LiveHub::default()), @@ -151,6 +157,26 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { }) } +/// The policy in effect at boot: the file values, with each `policy.` setting saved in the admin UI +/// layered on top. A stored value that no longer validates is logged and ignored, so a bad row cannot stop +/// the server from starting; the file value applies instead. +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 name = key.trim_start_matches("policy."); + match policy.set(name, &value) { + Ok(next) => policy = next, + Err(error) => { + tracing::warn!(setting = %key, error = %error, "stored policy setting ignored"); + } + } + } + Ok(policy) +} + /// The request body limit of the photo upload: the picture plus room for the multipart framing and /// the CSRF field. The handler enforces the picture limit itself while streaming. const PHOTO_BODY_LIMIT: usize = MAX_UPLOAD_BYTES + 64 * 1024; @@ -223,6 +249,7 @@ mod tests { let key = secret::load_or_create_key(&dir.path().join(KEY_FILE)).expect("key"); let store = Store::open(&config.database).await.expect("store"); let state = AppState { + policy_live: Arc::new(RwLock::new(config.policy.clone())), config: Arc::new(config), store, key: Arc::new(key), diff --git a/crates/im-web/src/cli.rs b/crates/im-web/src/cli.rs index 99e56d0..830f828 100644 --- a/crates/im-web/src/cli.rs +++ b/crates/im-web/src/cli.rs @@ -6,7 +6,7 @@ //! is stored. The redirect, logout and back-channel URIs are checked by the same rules the endpoints use. use std::fmt::Display; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::ExitCode; use im_core::config::Config; @@ -18,12 +18,13 @@ use im_core::store::clients::NewClient; use im_core::token::{generate_token, hash_token}; use crate::boot::{lock_data_dir, open_state}; +use crate::pages::admin::clients::is_origin; use crate::state::AppState; /// Printed with a usage error. const USAGE: &str = "usage: im client add --name [--redirect-uri ]... [--post-logout-uri ]... - [--backchannel-uri ] [--family-key ] [--scopes ] + [--backchannel-uri ] [--family-key --public-url ] [--scopes ] im client list im client disable "; @@ -93,6 +94,7 @@ struct AddArgs { post_logout_uris: Vec, backchannel_uri: Option, family_key: Option, + public_url: Option, scopes: Option, } @@ -118,6 +120,7 @@ fn parse_add(words: &[String]) -> std::result::Result { "--post-logout-uri" => args.post_logout_uris.push(value), "--backchannel-uri" => once(&mut args.backchannel_uri)?, "--family-key" => once(&mut args.family_key)?, + "--public-url" => once(&mut args.public_url)?, "--scopes" => once(&mut args.scopes)?, other => return Err(format!("unknown option {other}")), } @@ -148,6 +151,16 @@ async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> "family key {key} must be lowercase letters, digits and hyphens" )); } + match (&args.family_key, &args.public_url) { + (Some(_), None) => { + return Err("a family key needs --public-url, the origin of its service".into()); + } + (None, Some(_)) => return Err("--public-url is only for a family key".into()), + (Some(_), Some(url)) if !is_origin(url) => { + return Err(format!("{url} is not an origin (scheme and host, no path)")); + } + _ => {} + } let scopes = scope_list(args.scopes.as_deref().unwrap_or(DEFAULT_SCOPES))?; let secret = generate_token(); @@ -164,6 +177,13 @@ async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> }) .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())?; + } println!("client_id: {}", client.id); println!("client_secret: {secret}"); eprintln!("im: the client secret is shown once; store it now"); @@ -229,6 +249,105 @@ async fn disable(state: AppState, id: &str) -> std::result::Result<(), String> { } } +/// Runs `im backup now`: writes a snapshot set now, and waits for it. The outcome is recorded in the +/// settings, so the health page shows it too. +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) + .await + .map_err(|e| e.to_string())?; + println!("im: backup written to {}", set.display()); + Ok(()) + }) + .await + } + _ => { + eprintln!("im: usage: im backup now"); + ExitCode::from(2) + } + } +} + +/// Runs `im restore --from `. The set is verified first (every file's hash, and the database's +/// integrity and schema); a tampered set is refused and nothing is replaced. The current database and +/// photos move into a `restore-` directory inside the data directory. Refused while the server or +/// another command holds the data directory. +pub async fn restore(config: &Path, words: &[String]) -> ExitCode { + let set = match words { + [flag, set] if flag == "--from" => PathBuf::from(set), + _ => { + eprintln!("im: usage: im restore --from "); + return ExitCode::from(2); + } + }; + 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())?; + let stamp = im_core::time::now_stamp().replace([':', '.'], "-"); + im_core::backup::restore(&config.data_dir, &config.database, &set, &stamp) + .await + .map_err(|e| e.to_string()) + } + .await; + match outcome { + Ok(outcome) => { + println!( + "im: restored {} photo(s); the previous database and photos are in {}", + outcome.photos, + outcome.previous.display() + ); + ExitCode::SUCCESS + } + Err(message) => fail(message), + } +} + +/// Runs `im fsck`: checks the database's integrity and schema, and that every signing key can be opened +/// with the instance key. Refused while the server runs. +pub async fn fsck(config: &Path) -> ExitCode { + with_state(config, |state| async move { + im_core::backup::check_database(&state.config.database) + .await + .map_err(|e| e.to_string())?; + for key in state + .store + .signing_keys() + .await + .map_err(|e| e.to_string())? + { + im_core::secret::open(&state.key, &key.private_sealed) + .map_err(|e| format!("signing key {} cannot be opened: {e}", key.kid))?; + } + println!("im: database and signing keys ok"); + Ok(()) + }) + .await +} + +/// Runs `im keys rotate`: makes a new key the signing key now. +pub async fn keys(config: &Path, words: &[String]) -> ExitCode { + match words { + [verb] if verb == "rotate" => { + with_state(config, |state| async move { + let kid = crate::oidc::signing::rotate_now(&state.store, &state.key) + .await + .map_err(|e| e.to_string())?; + println!( + "im: new signing key {kid}; the previous key stays published for the overlap" + ); + Ok(()) + }) + .await + } + _ => { + eprintln!("im: usage: im keys rotate"); + ExitCode::from(2) + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/im-web/src/i18n/admin.rs b/crates/im-web/src/i18n/admin.rs new file mode 100644 index 0000000..4b71c56 --- /dev/null +++ b/crates/im-web/src/i18n/admin.rs @@ -0,0 +1,672 @@ +//! Strings of the administrator area: the navigation, the user, invitation, client, mail, message, settings, +//! key, audit and health pages. +//! +//! Each key has its English and its Turkish text in one match arm of [`pair`], so a key without a Turkish +//! text does not compile. Sentences with values use the helpers at the end of the file. + +use super::Lang; + +/// One variant per phrase of the administrator area. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum A { + StatePending, + StateSent, + StateFailed, + StateAbandoned, + NoticeMessageSent, + NavUsers, + NavInvites, + NavServices, + NavMail, + NavMessage, + NavSettings, + NavKeys, + NavAudit, + NavHealth, + Save, + Create, + Search, + Apply, + NextPage, + Open, + Retry, + Abandon, + Yes, + No, + UsersTitle, + UsersIntro, + SearchLabel, + NoUsers, + Name, + Email, + Status, + Active, + Disabled, + Administrator, + Created, + SessionsLabel, + TwoFactor, + UserTitle, + YouLabel, + DisableAccount, + EnableAccount, + MakeAdmin, + RemoveAdmin, + ResetTwoFactor, + TwoFactorOn, + TwoFactorOff, + RevokeSessions, + DeleteAccount, + DeleteWarning, + ConfirmEmail, + NoOwnAccountHere, + ErrLastAdmin, + ErrSelfDisable, + ErrSelfAdmin, + ErrSelfDelete, + ErrConfirmEmail, + NoticeDisabled, + NoticeEnabled, + NoticeAdminGranted, + NoticeAdminRemoved, + NoticeTwoFactorReset, + NoticeSessionsRevoked, + NoticeDeleted, + InvitesTitle, + InvitesIntro, + InviteNew, + InviteEmailLabel, + InviteAsAdmin, + InviteSendButton, + InviteQueued, + PendingInvites, + NoInvites, + Expires, + RevokeInvite, + ResendInvite, + NoticeInviteRevoked, + NoticeInviteResent, + ErrInviteGone, + ErrInviteTaken, + ErrInviteAddress, + ServicesTitle, + ServicesIntro, + ServicesList, + NoServices, + ClientsList, + NoClients, + ClientCreateTitle, + ClientName, + RedirectUris, + PostLogoutUris, + BackchannelUri, + ScopesLabel, + FamilyKey, + PublicUrl, + UriHint, + FamilyKeyHint, + PublicUrlHint, + ClientEditTitle, + ClientSaved, + SecretShown, + SecretOnce, + SecretLabel, + ClientIdLabel, + RotateSecret, + NoticeSecretRotated, + DisableClient, + NoticeClientDisabled, + ClientDisabledLabel, + Healthy, + Unhealthy, + NotChecked, + ErrClientName, + ErrUri, + ErrFamilyKey, + ErrFamilyKeyTaken, + ErrPublicUrl, + ErrScopes, + ErrNoSuchClient, + ErrSettingsInvalid, + TestMailSubject, + TestMailBody, + UseFileValue, + NoticeFileValue, + MailTitle, + MailIntro, + SmtpStatus, + SmtpNotConfigured, + SmtpHost, + SmtpSender, + SmtpLogin, + SendTest, + NoticeTestQueued, + OutboxTitle, + OutboxFilter, + AllStates, + Attempts, + NextAttempt, + LastError, + NoMail, + NoticeMailRetried, + NoticeMailAbandoned, + ErrMailNotRetryable, + ErrMailNotAbandonable, + MessageTitle, + MessageIntro, + MessageSubject, + MessageBody, + MessageBodyHint, + MessageSend, + ErrMessageEmpty, + ErrMessageSubjectLong, + ErrMessageBodyLong, + ErrMessageEmailInvalid, + ErrMessageRateLimited, + SettingsTitle, + SettingsIntro, + SettingName, + SettingValue, + SettingSource, + SourceUi, + SourceFile, + SourceDefault, + FileOnlyTitle, + FileOnlyIntro, + NoticeSettingsSaved, + SettingLabelRequire2fa, + SettingLabelMaxSessions, + SettingLabelSessionDays, + SettingLabelInviteDays, + SettingLabelResetMinutes, + SettingLabelEmailHours, + SettingHintRequire2fa, + SettingHintMaxSessions, + SettingHintSessionDays, + SettingHintInviteDays, + SettingHintResetMinutes, + SettingHintEmailHours, + FileBaseUrl, + FileListen, + FileDatabase, + FileDataDir, + FileTrustedProxies, + KeysTitle, + KeysIntro, + KeyCreated, + KeyActivates, + KeyRetires, + KeyCurrent, + KeyPublished, + KeyRetired, + KeyPending, + RotateNow, + RetireKey, + NoticeKeyRotated, + NoticeKeyRetired, + ErrKeyNotRetirable, + AuditTitle, + AuditIntro, + AuditAction, + AuditActor, + AuditTarget, + AuditFrom, + AuditTo, + AuditWhen, + AuditWho, + AuditIp, + AuditDetails, + AuditNoEntries, + AuditNewer, + AuditOlder, + HealthTitle, + HealthIntro, + HealthServices, + HealthOutbox, + HealthDatabase, + HealthBackups, + HealthBackupLast, + HealthBackupError, + HealthBackupOff, + HealthUsers, + HealthAdmins, + HealthBytes, +} + +/// The English and the Turkish text of `key`. +fn pair(key: A) -> (&'static str, &'static str) { + match key { + A::StatePending => ("Pending", "Bekliyor"), + A::StateSent => ("Sent", "Gönderildi"), + A::StateFailed => ("Failed", "BaÅŸarısız"), + A::StateAbandoned => ("Abandoned", "Vazgeçildi"), + A::NoticeMessageSent => ( + "The message was queued for every enabled account.", + "İleti etkin tüm hesaplar için kuyruÄŸa alındı.", + ), + A::NavUsers => ("Users", "Kullanıcılar"), + A::NavInvites => ("Invitations", "Davetler"), + A::NavServices => ("Services", "Hizmetler"), + A::NavMail => ("Mail", "E-posta"), + A::NavMessage => ("Message", "İleti"), + A::NavSettings => ("Settings", "Ayarlar"), + A::NavKeys => ("Keys", "Anahtarlar"), + A::NavAudit => ("Audit log", "Denetim günlüğü"), + A::NavHealth => ("Health", "SaÄŸlık"), + A::Save => ("Save", "Kaydet"), + A::Create => ("Create", "OluÅŸtur"), + A::Search => ("Search", "Ara"), + A::Apply => ("Apply", "Uygula"), + A::NextPage => ("Next page", "Sonraki sayfa"), + A::Open => ("Open", "Aç"), + A::Retry => ("Retry", "Yeniden dene"), + A::Abandon => ("Abandon", "Vazgeç"), + A::Yes => ("Yes", "Evet"), + A::No => ("No", "Hayır"), + A::UsersTitle => ("Users", "Kullanıcılar"), + A::UsersIntro => ( + "Everyone who has an account. Search by part of an address or a name.", + "Hesabı olan herkes. Adresin veya adın bir parçasıyla arayın.", + ), + A::SearchLabel => ("Address or name", "Adres veya ad"), + A::NoUsers => ("No account matches.", "EÅŸleÅŸen hesap yok."), + A::Name => ("Name", "Ad"), + A::Email => ("Email", "E-posta"), + A::Status => ("Status", "Durum"), + A::Active => ("Active", "Etkin"), + A::Disabled => ("Disabled", "Devre dışı"), + A::Administrator => ("Administrator", "Yönetici"), + A::Created => ("Created", "OluÅŸturuldu"), + A::SessionsLabel => ("Sessions", "Oturumlar"), + A::TwoFactor => ("Two-factor sign-in", "İki adımlı giriÅŸ"), + A::UserTitle => ("Account", "Hesap"), + A::YouLabel => ("This is you", "Bu sizsiniz"), + A::DisableAccount => ("Disable account", "Hesabı devre dışı bırak"), + A::EnableAccount => ("Enable account", "Hesabı etkinleÅŸtir"), + A::MakeAdmin => ("Make administrator", "Yönetici yap"), + A::RemoveAdmin => ("Remove administrator", "Yöneticilikten çıkar"), + A::ResetTwoFactor => ("Reset two-factor sign-in", "İki adımlı giriÅŸi sıfırla"), + A::TwoFactorOn => ("Two-factor sign-in is on.", "İki adımlı giriÅŸ açık."), + A::TwoFactorOff => ("Two-factor sign-in is off.", "İki adımlı giriÅŸ kapalı."), + A::RevokeSessions => ("Sign out every session", "Tüm oturumları kapat"), + A::DeleteAccount => ("Delete account", "Hesabı sil"), + A::DeleteWarning => ( + "Deleting removes the account, its sessions, its photo and its links. This cannot be undone.", + "Silme; hesabı, oturumlarını, fotoÄŸrafını ve baÄŸlantılarını kaldırır. Geri alınamaz.", + ), + A::ConfirmEmail => ("Type the address to confirm", "Onaylamak için adresi yazın"), + A::NoOwnAccountHere => ( + "You cannot change your own account here. Another administrator must do it.", + "Kendi hesabınızı burada deÄŸiÅŸtiremezsiniz. BaÅŸka bir yönetici yapmalı.", + ), + A::ErrLastAdmin => ( + "This is the last enabled administrator. Make another administrator first.", + "Bu, etkin son yönetici. Önce baÅŸka bir yönetici atayın.", + ), + A::ErrSelfDisable => ( + "You cannot disable your own account.", + "Kendi hesabınızı devre dışı bırakamazsınız.", + ), + A::ErrSelfAdmin => ( + "You cannot change your own administrator status. Another administrator must do it.", + "Kendi yönetici durumunuzu deÄŸiÅŸtiremezsiniz. BaÅŸka bir yönetici yapmalı.", + ), + A::ErrSelfDelete => ( + "You cannot delete your own account.", + "Kendi hesabınızı silemezsiniz.", + ), + A::ErrConfirmEmail => ( + "The address you typed does not match the account. Nothing was deleted.", + "Yazdığınız adres hesapla eÅŸleÅŸmiyor. Hiçbir ÅŸey silinmedi.", + ), + A::NoticeDisabled => ( + "The account is disabled and its sessions have ended.", + "Hesap devre dışı; oturumları kapandı.", + ), + A::NoticeEnabled => ( + "The account is enabled again.", + "Hesap yeniden etkinleÅŸtirildi.", + ), + A::NoticeAdminGranted => ( + "The account is now an administrator.", + "Hesap artık bir yönetici.", + ), + A::NoticeAdminRemoved => ( + "The account is no longer an administrator.", + "Hesap artık yönetici deÄŸil.", + ), + A::NoticeTwoFactorReset => ( + "Two-factor sign-in and the recovery codes were reset. The person has been told by mail.", + "İki adımlı giriÅŸ ve kurtarma kodları sıfırlandı. KiÅŸiye e-postayla bildirildi.", + ), + A::NoticeSessionsRevoked => ( + "Every session of the account has ended.", + "Hesabın tüm oturumları kapandı.", + ), + A::NoticeDeleted => ("The account was deleted.", "Hesap silindi."), + A::InvitesTitle => ("Invitations", "Davetler"), + A::InvitesIntro => ( + "An invitation is a link that creates an account. Only the newest link for an address works.", + "Davet, hesap oluÅŸturan bir baÄŸlantıdır. Bir adres için yalnızca en yeni baÄŸlantı çalışır.", + ), + A::InviteNew => ("New invitation", "Yeni davet"), + A::InviteEmailLabel => ("Email", "E-posta"), + A::InviteAsAdmin => ("Make the account an administrator", "Hesabı yönetici yap"), + A::InviteSendButton => ("Send invitation", "Daveti gönder"), + A::InviteQueued => ( + "The invitation is queued for sending.", + "Davet gönderilmek üzere kuyruÄŸa alındı.", + ), + A::PendingInvites => ("Pending invitations", "Bekleyen davetler"), + A::NoInvites => ("No invitation is waiting.", "Bekleyen davet yok."), + A::Expires => ("Expires", "Sona erer"), + A::RevokeInvite => ("Revoke", "İptal et"), + A::ResendInvite => ("Send a new link", "Yeni baÄŸlantı gönder"), + A::NoticeInviteRevoked => ("The invitation was revoked.", "Davet iptal edildi."), + A::NoticeInviteResent => ( + "A new invitation was sent. The old link stopped working.", + "Yeni davet gönderildi. Eski baÄŸlantı çalışmıyor.", + ), + A::ErrInviteTaken => ( + "That address already has an account.", + "Bu adresin zaten bir hesabı var.", + ), + A::ErrInviteAddress => ( + "That is not an email address.", + "Bu bir e-posta adresi deÄŸil.", + ), + A::ErrInviteGone => ( + "That invitation was already used or has expired.", + "Bu davet zaten kullanıldı veya süresi doldu.", + ), + A::ServicesTitle => ("Services and clients", "Hizmetler ve istemciler"), + A::ServicesIntro => ( + "Family apps are clients with a family key. Their public address is what the switcher links to.", + "Aile uygulamaları, aile anahtarı olan istemcilerdir. GeçiÅŸ menüsü onların genel adresine baÄŸlanır.", + ), + A::ServicesList => ("Switcher", "GeçiÅŸ menüsü"), + A::NoServices => ("No service is listed.", "Listelenen hizmet yok."), + A::ClientsList => ("OpenID clients", "OpenID istemcileri"), + A::NoClients => ("No client is registered.", "Kayıtlı istemci yok."), + A::ClientCreateTitle => ("Register a client", "İstemci kaydet"), + A::ClientName => ("Name", "Ad"), + A::RedirectUris => ("Redirect URIs", "Yönlendirme adresleri"), + A::PostLogoutUris => ("Post-logout URIs", "Çıkış sonrası adresleri"), + A::BackchannelUri => ("Back-channel logout URI", "Arka kanal çıkış adresi"), + A::ScopesLabel => ("Scopes", "Kapsamlar"), + A::FamilyKey => ("Family key", "Aile anahtarı"), + A::PublicUrl => ("Public address", "Genel adres"), + A::UriHint => ( + "One per line. Exact matches only.", + "Her satıra bir tane. Yalnızca birebir eÅŸleÅŸme.", + ), + A::FamilyKeyHint => ( + "Such as in or iz. Leave empty for a client that is not a family app.", + "ÖrneÄŸin in veya iz. Aile uygulaması deÄŸilse boÅŸ bırakın.", + ), + A::PublicUrlHint => ( + "The origin of the app, such as https://in.example.com. Needs a family key.", + "Uygulamanın kökü, örneÄŸin https://in.example.com. Aile anahtarı gerektirir.", + ), + A::ClientEditTitle => ("Client", "İstemci"), + A::ClientSaved => ("The client was saved.", "İstemci kaydedildi."), + A::SecretShown => ( + "Client created. The secret is shown once; copy it now.", + "İstemci oluÅŸturuldu. Gizli anahtar yalnızca bir kez gösterilir; ÅŸimdi kopyalayın.", + ), + A::SecretOnce => ( + "Shown once. It is not stored and cannot be shown again.", + "Yalnızca bir kez gösterilir. Saklanmaz ve tekrar gösterilemez.", + ), + A::SecretLabel => ("Client secret", "İstemci gizli anahtarı"), + A::ClientIdLabel => ("Client id", "İstemci kimliÄŸi"), + A::RotateSecret => ("Rotate secret", "Gizli anahtarı döndür"), + A::NoticeSecretRotated => ( + "A new secret was issued. The old one no longer works.", + "Yeni gizli anahtar üretildi. Eskisi artık çalışmıyor.", + ), + A::DisableClient => ("Disable client", "İstemciyi devre dışı bırak"), + A::NoticeClientDisabled => ( + "The client is disabled. It cannot sign in or exchange tokens.", + "İstemci devre dışı. GiriÅŸ yapamaz veya belirteç alamaz.", + ), + A::ClientDisabledLabel => ("Disabled", "Devre dışı"), + A::Healthy => ("Up", "Çalışıyor"), + A::Unhealthy => ("Down", "Çalışmıyor"), + A::NotChecked => ("Not checked yet", "Henüz denetlenmedi"), + A::ErrClientName => ("The name is empty or too long.", "Ad boÅŸ veya çok uzun."), + A::ErrUri => ( + "A URI is not valid. Use https, or http on loopback, with no fragment.", + "Bir adres geçerli deÄŸil. https kullanın; yalnızca yerel adreste http, parça (#) olmadan.", + ), + A::ErrFamilyKey => ( + "A family key uses lowercase letters, digits and hyphens.", + "Aile anahtarı küçük harf, rakam ve kısa çizgi kullanır.", + ), + A::ErrFamilyKeyTaken => ( + "Another client already uses that family key.", + "Bu aile anahtarını baÅŸka bir istemci kullanıyor.", + ), + A::ErrPublicUrl => ( + "The public address must be an origin such as https://in.example.com.", + "Genel adres https://in.example.com gibi bir kök adres olmalı.", + ), + A::ErrScopes => ( + "Choose at least one known scope.", + "En az bir bilinen kapsam seçin.", + ), + A::ErrNoSuchClient => ("That client does not exist.", "Bu istemci yok."), + A::TestMailSubject => ("im: test mail", "im: deneme e-postası"), + A::TestMailBody => ( + "This is a test of the outgoing mail. If you can read it, sending works.", + "Bu, giden e-postanın bir denemesidir. Bunu okuyabiliyorsanız gönderim çalışıyor.", + ), + A::UseFileValue => ("Use the file value", "Dosya deÄŸerini kullan"), + A::NoticeFileValue => ( + "The setting now follows the file again.", + "Ayar artık yeniden dosyayı izliyor.", + ), + A::ErrSettingsInvalid => ( + "A setting is missing or out of range. Nothing was saved.", + "Bir ayar eksik veya aralık dışında. Hiçbir ÅŸey kaydedilmedi.", + ), + A::MailTitle => ("Mail", "E-posta"), + A::MailIntro => ( + "What is sent, to whom, and what is waiting.", + "Ne gönderildiÄŸi, kime gittiÄŸi ve neyin beklediÄŸi.", + ), + A::SmtpStatus => ("Sending", "Gönderim"), + A::SmtpNotConfigured => ( + "No SMTP server is configured. Mail waits in the outbox and no attempt is spent.", + "SMTP sunucusu yapılandırılmamış. E-postalar kutuda bekler; deneme harcanmaz.", + ), + A::SmtpHost => ("Server", "Sunucu"), + A::SmtpSender => ("Sender", "Gönderen"), + A::SmtpLogin => ("Login", "Oturum adı"), + A::SendTest => ("Send a test mail to me", "Bana bir deneme e-postası gönder"), + A::NoticeTestQueued => ( + "A test mail is queued for your address.", + "Adresinize bir deneme e-postası kuyruÄŸa alındı.", + ), + A::OutboxTitle => ("Outbox", "Giden kutusu"), + A::OutboxFilter => ("State", "Durum"), + A::AllStates => ("All", "Tümü"), + A::Attempts => ("Attempts", "Denemeler"), + A::NextAttempt => ("Next attempt", "Sonraki deneme"), + A::LastError => ("Last error", "Son hata"), + A::NoMail => ( + "Nothing in the outbox for this filter.", + "Bu filtrede giden kutusunda bir ÅŸey yok.", + ), + A::NoticeMailRetried => ( + "The mail will be sent again now.", + "E-posta ÅŸimdi yeniden gönderilecek.", + ), + A::NoticeMailAbandoned => ( + "The mail was abandoned and its body removed.", + "E-posta vazgeçildi ve içeriÄŸi silindi.", + ), + A::ErrMailNotRetryable => ( + "Only a failed mail can be retried.", + "Yalnızca baÅŸarısız bir e-posta yeniden denenebilir.", + ), + A::ErrMailNotAbandonable => ( + "Only a mail that is not yet sent can be abandoned.", + "Yalnızca henüz gönderilmemiÅŸ bir e-posta vazgeçilebilir.", + ), + A::MessageTitle => ("Message", "İleti"), + A::MessageIntro => ( + "A plain mail to everyone with an account, or to one address. It is queued and sent in the background.", + "Hesabı olan herkese veya tek bir adrese düz bir e-posta. KuyruÄŸa alınır ve arka planda gönderilir.", + ), + A::MessageSubject => ("Subject", "Konu"), + A::MessageBody => ("Message", "İleti"), + A::MessageBodyHint => ( + "Paragraphs are separated by an empty line.", + "Paragraflar boÅŸ satırla ayrılır.", + ), + A::MessageSend => ("Queue the message", "İletiyi kuyruÄŸa al"), + A::ErrMessageEmpty => ( + "Write a subject and a message.", + "Bir konu ve bir ileti yazın.", + ), + A::ErrMessageSubjectLong => ( + "The subject is longer than 150 characters or has a line break.", + "Konu 150 karakterden uzun veya satır sonu içeriyor.", + ), + A::ErrMessageBodyLong => ( + "The message is longer than 10000 characters.", + "İleti 10000 karakterden uzun.", + ), + A::ErrMessageEmailInvalid => ( + "That address is not an account's address.", + "Bu adres bir hesaba ait deÄŸil.", + ), + A::ErrMessageRateLimited => ( + "A message was sent a moment ago. Wait a while before the next one.", + "Az önce bir ileti gönderildi. Bir sonrakinden önce biraz bekleyin.", + ), + A::SettingsTitle => ("Settings", "Ayarlar"), + A::SettingsIntro => ( + "A value saved here wins over the configuration file, and applies at once. The file applies to every setting with no saved value.", + "Burada kaydedilen deÄŸer yapılandırma dosyasının önündedir ve hemen uygulanır. Kayıtlı deÄŸeri olmayan her ayar için dosya geçerlidir.", + ), + A::SettingName => ("Setting", "Ayar"), + A::SettingValue => ("Value", "DeÄŸer"), + A::SettingSource => ("Source", "Kaynak"), + A::SourceUi => ("saved here", "burada kaydedildi"), + A::SourceFile => ("config file", "yapılandırma dosyası"), + A::SourceDefault => ("default", "varsayılan"), + A::FileOnlyTitle => ("File settings", "Dosya ayarları"), + A::FileOnlyIntro => ( + "These are read from the configuration file and need a restart to change.", + "Bunlar yapılandırma dosyasından okunur ve deÄŸiÅŸmesi yeniden baÅŸlatma gerektirir.", + ), + A::NoticeSettingsSaved => ( + "The settings were saved and apply now.", + "Ayarlar kaydedildi ve ÅŸimdi uygulanıyor.", + ), + A::SettingLabelRequire2fa => ( + "Two-factor sign-in for administrators", + "Yöneticiler için iki adımlı giriÅŸ", + ), + A::SettingLabelMaxSessions => ("Sessions per person", "KiÅŸi başına oturum"), + A::SettingLabelSessionDays => ("Session lifetime, days", "Oturum süresi, gün"), + A::SettingLabelInviteDays => ("Invitation lifetime, days", "Davet süresi, gün"), + A::SettingLabelResetMinutes => ( + "Reset link lifetime, minutes", + "Sıfırlama baÄŸlantısı süresi, dakika", + ), + A::SettingLabelEmailHours => ( + "Email change lifetime, hours", + "E-posta deÄŸiÅŸikliÄŸi süresi, saat", + ), + A::SettingHintRequire2fa => ( + "true or false. An administrator without it is sent to enrol after signing in.", + "true veya false. Olmadan yönetici giriÅŸ sonrası kaydolmaya yönlendirilir.", + ), + A::SettingHintMaxSessions => ( + "At least 1. The oldest session ends when a new sign-in would exceed it.", + "En az 1. Yeni giriÅŸte sınır aşılırsa en eski oturum kapanır.", + ), + A::SettingHintSessionDays => ("1 to 365.", "1 ile 365 arası."), + A::SettingHintInviteDays => ("1 to 30.", "1 ile 30 arası."), + A::SettingHintResetMinutes => ("5 to 1440.", "5 ile 1440 arası."), + A::SettingHintEmailHours => ("1 to 168.", "1 ile 168 arası."), + A::FileBaseUrl => ("Public address (base_url)", "Genel adres (base_url)"), + A::FileListen => ("Listen address", "Dinleme adresi"), + A::FileDatabase => ("Database file", "Veritabanı dosyası"), + A::FileDataDir => ("Data directory", "Veri dizini"), + A::FileTrustedProxies => ("Trusted proxies", "Güvenilen vekiller"), + A::KeysTitle => ("Signing keys", "İmzalama anahtarları"), + A::KeysIntro => ( + "Tokens are signed with the current key. Retired keys stay published for a while so their tokens still verify.", + "Belirteçler güncel anahtarla imzalanır. Emekli anahtarlar, imzaladıkları belirteçler doÄŸrulansın diye bir süre yayımlı kalır.", + ), + A::KeyCreated => ("Created", "OluÅŸturuldu"), + A::KeyActivates => ("Signs from", "İmzalamaya baÅŸlama"), + A::KeyRetires => ("Retired at", "Emekli olma"), + A::KeyCurrent => ("current", "güncel"), + A::KeyPublished => ("published", "yayımlı"), + A::KeyRetired => ("retired", "emekli"), + A::KeyPending => ("waiting to sign", "imzalamayı bekliyor"), + 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::NoticeKeyRetired => ( + "The key is retired. It stays published for the usual overlap.", + "Anahtar emekli yapıldı. OlaÄŸan örtüşme süresi kadar yayımlı kalır.", + ), + A::ErrKeyNotRetirable => ( + "The current key cannot be retired. Rotate first.", + "Güncel anahtar emekli yapılamaz. Önce döndürün.", + ), + A::AuditTitle => ("Audit log", "Denetim günlüğü"), + A::AuditIntro => ( + "Every change, newest first. Filter, then page with the links below the table.", + "Her deÄŸiÅŸiklik, en yeni önce. Süzün, ardından tablonun altındaki baÄŸlantılarla sayfalayın.", + ), + A::AuditAction => ("Action", "İşlem"), + A::AuditActor => ("Actor id", "Yapan kimlik"), + A::AuditTarget => ("Target id", "Hedef kimlik"), + A::AuditFrom => ("From (UTC date)", "BaÅŸlangıç (UTC tarih)"), + A::AuditTo => ("To (UTC date)", "BitiÅŸ (UTC tarih)"), + A::AuditWhen => ("When", "Zaman"), + A::AuditWho => ("Who", "Kim"), + A::AuditIp => ("Address", "Adres"), + A::AuditDetails => ("Details", "Ayrıntı"), + A::AuditNoEntries => ("No entries match.", "EÅŸleÅŸen kayıt yok."), + A::AuditNewer => ("Newer", "Daha yeni"), + A::AuditOlder => ("Older", "Daha eski"), + A::HealthTitle => ("Health", "SaÄŸlık"), + A::HealthIntro => ( + "The state of the server and its outboxes.", + "Sunucunun ve giden kutularının durumu.", + ), + A::HealthServices => ("Services", "Hizmetler"), + A::HealthOutbox => ("Mail outbox", "E-posta giden kutusu"), + A::HealthDatabase => ("Database", "Veritabanı"), + A::HealthBackups => ("Backups", "Yedekler"), + A::HealthBackupLast => ("Last success", "Son baÅŸarılı"), + A::HealthBackupError => ("Last error", "Son hata"), + A::HealthBackupOff => ( + "Backups are off. Set [backup] dir to turn them on.", + "Yedekleme kapalı. Açmak için [backup] dir ayarlayın.", + ), + A::HealthUsers => ("Accounts", "Hesaplar"), + A::HealthAdmins => ("Enabled administrators", "Etkin yöneticiler"), + A::HealthBytes => ("Database size", "Veritabanı boyutu"), + } +} + +/// The text of `key` in `lang`. +pub fn text(lang: Lang, key: A) -> &'static str { + let (en, tr) = pair(key); + match lang { + Lang::En => en, + Lang::Tr => tr, + } +} diff --git a/crates/im-web/src/i18n/flows.rs b/crates/im-web/src/i18n/flows.rs index fe32bcc..24ae3f4 100644 --- a/crates/im-web/src/i18n/flows.rs +++ b/crates/im-web/src/i18n/flows.rs @@ -31,17 +31,11 @@ pub enum Flow { /// The button that creates the account. InviteSubmit, /// Title of the administrator invitation page. - AdminInvitesTitle, /// The sentence under that title. - AdminInvitesIntro, /// Checkbox: the invitee becomes an administrator. - InviteAsAdmin, /// The button that sends the invitation. - InviteSend, /// Notice after an invitation was queued. - InviteQueued, /// Alert: the address already has an account. - InviteAddressTaken, /// The profile link to the email change page. ChangeEmailLink, /// Title of the email change request page. @@ -119,22 +113,6 @@ pub fn text(lang: Lang, key: Flow) -> &'static str { } (Flow::InviteSubmit, Lang::En) => "Create my account", (Flow::InviteSubmit, Lang::Tr) => "Hesabımı oluÅŸtur", - (Flow::AdminInvitesTitle, Lang::En) => "Invitations", - (Flow::AdminInvitesTitle, Lang::Tr) => "Davetler", - (Flow::AdminInvitesIntro, Lang::En) => { - "Send an invitation to an address. The person chooses their own name and password." - } - (Flow::AdminInvitesIntro, Lang::Tr) => { - "Bir adrese davet gönderin. KiÅŸi kendi adını ve parolasını seçer." - } - (Flow::InviteAsAdmin, Lang::En) => "Make this person an administrator", - (Flow::InviteAsAdmin, Lang::Tr) => "Bu kiÅŸiyi yönetici yap", - (Flow::InviteSend, Lang::En) => "Send the invitation", - (Flow::InviteSend, Lang::Tr) => "Daveti gönder", - (Flow::InviteQueued, Lang::En) => "The invitation was queued for sending.", - (Flow::InviteQueued, Lang::Tr) => "Davet gönderilmek üzere kuyruÄŸa alındı.", - (Flow::InviteAddressTaken, Lang::En) => "That address already has an account.", - (Flow::InviteAddressTaken, Lang::Tr) => "Bu adrese ait bir hesap zaten var.", (Flow::ChangeEmailLink, Lang::En) => "Change email address", (Flow::ChangeEmailLink, Lang::Tr) => "E-posta adresini deÄŸiÅŸtir", (Flow::EmailChangeTitle, Lang::En) => "Change email address", diff --git a/crates/im-web/src/i18n/mod.rs b/crates/im-web/src/i18n/mod.rs index 9b3d215..0ac11cf 100644 --- a/crates/im-web/src/i18n/mod.rs +++ b/crates/im-web/src/i18n/mod.rs @@ -8,6 +8,7 @@ //! helper functions next to their keys. pub mod account; +pub mod admin; pub mod flows; pub mod mail; pub mod oidc; diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs index 9d59146..fdd3f47 100644 --- a/crates/im-web/src/live.rs +++ b/crates/im-web/src/live.rs @@ -9,10 +9,8 @@ //! The hub is not a queue and not an authorisation check. Each route that opens a stream //! authenticates and authorises first, then calls [`stream_changes`]. //! -//! The account stream (`/-/alive`) is the only user of the hub so far. [`stream_changes`] waits for -//! the admin pages that follow a list. - -#![allow(dead_code)] // `stream_changes` and `Topic::AdminAudit` wait for the admin pages. +//! Every stream ends when the process stops (the stop flag in [`AppState`]), so a shutdown does not wait +//! for a browser to close its connection. use std::collections::HashMap; use std::future::Future; @@ -42,8 +40,9 @@ pub const KEEP_ALIVE: Duration = Duration::from_secs(30); pub enum Topic { /// A user's own settings, sessions or sign-ins. Keyed by user id. Streamed only to that user. Account(String), - /// The audit log: an entry was written. Global. Admin pages only. - AdminAudit, + /// Anything an administrator page shows: users, invitations, clients, mail, keys, settings, audit + /// entries, health. Bumped by every administrator write. Streamed only to administrators. + Admin, } /// The change counters of all open topics. Cheap to share: every clone of the app state holds the @@ -72,6 +71,14 @@ impl LiveHub { .subscribe() } + /// The change counter of `topic` now. It moves on every bump, so a stream that compares it with the + /// value it sent last sends one event per change. Zero when nobody listens. + pub fn generation(&self, topic: &Topic) -> u64 { + self.topics() + .get(topic) + .map_or(0, |sender| *sender.borrow()) + } + /// Wakes the subscribers of `topic`. Does nothing when nobody listens. pub fn bump(&self, topic: &Topic) { let mut topics = self.topics(); @@ -88,6 +95,7 @@ impl LiveHub { /// The state a stream carries between wakes. struct Follow { wakes: Vec>, + stop: watch::Receiver, fingerprint: F, last: String, } @@ -114,12 +122,17 @@ where let last = fingerprint().await?; let follow = Follow { wakes, + stop: app_context::(cx).stop.clone(), fingerprint, last, }; let events = stream::unfold(follow, |mut follow| async move { loop { - if !wait_any(&mut follow.wakes).await { + let woke = tokio::select! { + woke = wait_any(&mut follow.wakes) => woke, + () = stopped(&mut follow.stop) => false, + }; + if !woke { return None; } match (follow.fingerprint)().await { @@ -143,6 +156,14 @@ fn changed_event() -> Result { Ok(Event::new().event("changed").data("1")) } +/// Resolves when the stop flag is set. A flag whose sender is gone never resolves, so the stream is not +/// ended by mistake. +pub async fn stopped(stop: &mut watch::Receiver) { + if stop.wait_for(|stopped| *stopped).await.is_err() { + std::future::pending::<()>().await; + } +} + /// Resolves when one of `wakes` changes. False when that topic is gone, which ends the stream. /// With no topics at all it never resolves: the stream then only sends keep-alives. async fn wait_any(wakes: &mut [watch::Receiver]) -> bool { @@ -174,6 +195,8 @@ pub fn events_response( struct AccountFollow { /// Woken by every change of the viewer's account (sessions, security). wake: watch::Receiver, + /// Set when the process stops. The stream then ends. + stop: watch::Receiver, /// Checks that the session of this stream still exists. store: Store, /// The session the stream was opened with. @@ -192,18 +215,31 @@ struct AccountFollow { async fn alive(cx: &Cx) -> Result { let state = app_context::(cx); let Some(viewer) = current_user(cx).await? else { - return events_response(cx, stream::pending::>()); + // Anonymous: no events, but the stream still ends when the process stops. + let events = stream::unfold(state.stop.clone(), |mut stop| async move { + stopped(&mut stop).await; + None::<(Result, watch::Receiver)> + }); + return events_response(cx, events); }; let follow = AccountFollow { wake: state .live .subscribe(&Topic::Account(viewer.user.id.clone())), + stop: state.stop.clone(), store: state.store.clone(), session_id: viewer.session.id.clone(), done: false, }; let events = stream::unfold(follow, |mut follow| async move { - if follow.done || follow.wake.changed().await.is_err() { + if follow.done { + return None; + } + let changed = tokio::select! { + changed = follow.wake.changed() => changed.is_ok(), + () = stopped(&mut follow.stop) => false, + }; + if !changed { return None; } match follow.store.session_is_live(&follow.session_id).await { diff --git a/crates/im-web/src/mail/mod.rs b/crates/im-web/src/mail/mod.rs index 61a6192..c38c231 100644 --- a/crates/im-web/src/mail/mod.rs +++ b/crates/im-web/src/mail/mod.rs @@ -79,6 +79,21 @@ pub enum Mail<'a> { }, /// A security notice. Security(Notice), + /// A message from an administrator. The subject and the body are the administrator's own words; they + /// are escaped like every other value, and the body is split into paragraphs at blank lines. + Notice { + /// The subject line. Single line, checked by the caller. + subject: &'a str, + /// The body, plain text. + body: &'a str, + }, + /// A test mail sent from the administrator's mail page. Its text is fixed. + Test { + /// The subject. + subject: &'a str, + /// The body, paragraphs separated by a blank line. + body: &'a str, + }, } impl Mail<'_> { @@ -91,6 +106,8 @@ impl Mail<'_> { Mail::EmailNew { .. } => "email_new", Mail::EmailDone { .. } => "email_done", Mail::Security(_) => "security", + Mail::Notice { .. } => "notice", + Mail::Test { .. } => "test", } } } diff --git a/crates/im-web/src/mail/templates.rs b/crates/im-web/src/mail/templates.rs index cb2a895..d4d65c0 100644 --- a/crates/im-web/src/mail/templates.rs +++ b/crates/im-web/src/mail/templates.rs @@ -110,6 +110,18 @@ fn parts(lang: Lang, name: Option<&str>, mail: &Mail<'_>) -> Parts { closing: vec![signature], } } + Mail::Notice { subject, body } | Mail::Test { subject, body } => Parts { + subject: subject.to_owned(), + greeting, + paragraphs: body + .split("\n\n") + .map(str::trim) + .filter(|paragraph| !paragraph.is_empty()) + .map(str::to_owned) + .collect(), + action: None, + closing: vec![signature], + }, } } diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index f4d16b7..067fd99 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -9,6 +9,7 @@ mod assets; mod audit; mod auth; mod backchannel; +mod backups; mod boot; mod cli; mod client_ip; @@ -30,7 +31,7 @@ use std::process::ExitCode; use tracing_subscriber::EnvFilter; /// Printed with a usage error. -const USAGE: &str = "usage: im [--config ] [serve | client ...]"; +const USAGE: &str = "usage: im [--config ] [serve | client ... | backup now | restore --from | fsck | keys rotate]"; /// The configuration file when neither `--config` nor `IM_CONFIG` names one. const DEFAULT_CONFIG: &str = "config/im.toml"; @@ -100,10 +101,10 @@ async fn main() -> ExitCode { match words.as_slice() { [] | ["serve"] => serve(&config_path(cli.config)).await, ["client", ..] => cli::client(&config_path(cli.config), &cli.words[1..]).await, - ["admin", ..] => { - eprintln!("im: admin commands are not implemented yet"); - ExitCode::from(2) - } + ["backup", ..] => cli::backup(&config_path(cli.config), &cli.words[1..]).await, + ["restore", ..] => cli::restore(&config_path(cli.config), &cli.words[1..]).await, + ["fsck"] => cli::fsck(&config_path(cli.config)).await, + ["keys", ..] => cli::keys(&config_path(cli.config), &cli.words[1..]).await, _ => { eprintln!("im: unknown command\n{USAGE}"); ExitCode::from(2) diff --git a/crates/im-web/src/oidc/authorize.rs b/crates/im-web/src/oidc/authorize.rs index 1accef7..44bd386 100644 --- a/crates/im-web/src/oidc/authorize.rs +++ b/crates/im-web/src/oidc/authorize.rs @@ -195,10 +195,7 @@ async fn authorize(cx: &Cx) -> Result { // An administrator must have two-factor sign-in first (the policy). The security page enrols it; a // prompt=none request cannot show a page, so it is refused instead. - if viewer.user.is_admin - && app.config.policy.require_2fa_for_admins - && !viewer.user.totp_enabled() - { + if viewer.user.is_admin && app.policy().require_2fa_for_admins && !viewer.user.totp_enabled() { if asked.no_prompt { let refused = Refused { code: "interaction_required", diff --git a/crates/im-web/src/oidc/signing.rs b/crates/im-web/src/oidc/signing.rs index d662015..52b2d0c 100644 --- a/crates/im-web/src/oidc/signing.rs +++ b/crates/im-web/src/oidc/signing.rs @@ -66,6 +66,23 @@ 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. +pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result { + let fresh = keys::generate(); + let now = now_stamp(); + 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, + retires_at: None, + }; + store.add_signing_key(&record).await?; + Ok(fresh.kid) +} + /// The keys published now, for the JWKS document and for verifying tokens. pub async fn published_keys(store: &Store) -> im_core::Result> { let rows = store.signing_keys().await?; diff --git a/crates/im-web/src/pages/admin/audit.rs b/crates/im-web/src/pages/admin/audit.rs new file mode 100644 index 0000000..aa53765 --- /dev/null +++ b/crates/im-web/src/pages/admin/audit.rs @@ -0,0 +1,211 @@ +//! `/admin/audit`: the audit log, newest first, with filters and keyset paging. +//! +//! The filters are an action, an actor id, a target id, and a day range. The cursor of the next page is the +//! position of the last entry (`at|id`), so entries written while an administrator pages do not shift the +//! pages. The day range is read in UTC: `from` is the first nanosecond of its day, and `to` is the last +//! nanosecond of its day, so both days are included in full. + +use im_core::model::AuditEntry; +use im_core::store::audit::{AuditCursor, AuditFilter}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::page; +use topcoat::view::{View, component, view}; + +use crate::auth::require_admin; +use crate::i18n::Lang; +use crate::i18n::admin::{A, text}; +use crate::pages::admin::{PAGE_SIZE, Tab, frame_info, tabs}; +use crate::state::AppState; +use crate::views::{ViewerInfo, shell}; + +/// The query: the four filters, and the cursor of the page. +#[derive(Deserialize, Default)] +struct AuditQuery { + #[serde(default)] + action: String, + #[serde(default)] + actor: String, + #[serde(default)] + target: String, + /// A day, `YYYY-MM-DD`. + #[serde(default)] + from: String, + /// A day, `YYYY-MM-DD`, included. + #[serde(default)] + to: String, + /// `at|id` of the last entry of the previous page. + #[serde(default)] + after: String, +} + +/// `GET /admin/audit`. +#[page("/admin/audit")] +async fn audit_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let filter = AuditFilter { + action: non_empty(&query.action), + actor_id: non_empty(&query.actor), + target_id: non_empty(&query.target), + from: day_stamp(&query.from, false), + to: day_stamp(&query.to, true), + }; + let cursor = cursor_of(&query.after); + let (entries, next) = state + .store + .list_audit(&filter, cursor.as_ref(), PAGE_SIZE) + .await?; + let base = filter_query(&query); + let next_href = next.map(|next| { + format!( + "/admin/audit?{base}&after={}", + encode(&format!("{}|{}", next.at, next.id)) + ) + }); + Ok(audit_view(cx, lang, info, base, query, entries, next_href)) +} + +/// Trimmed text, or `None` when it is empty. +fn non_empty(text: &str) -> Option { + let text = text.trim(); + (!text.is_empty()).then(|| text.to_owned()) +} + +/// The stamp of the first (or, with `end`, the last) nanosecond of a `YYYY-MM-DD` day. A day that is not +/// well formed is ignored, so the filter is simply not applied. +fn day_stamp(day: &str, end: bool) -> Option { + let bytes = day.trim().as_bytes(); + let well_formed = bytes.len() == 10 + && bytes.iter().enumerate().all(|(index, byte)| match index { + 4 | 7 => *byte == b'-', + _ => byte.is_ascii_digit(), + }); + if !well_formed { + return None; + } + let day = day.trim(); + Some(if end { + format!("{day}T23:59:59.999999999Z") + } else { + format!("{day}T00:00:00.000000000Z") + }) +} + +/// The cursor of the page, from `at|id`. A cursor that is not well formed starts the first page. +fn cursor_of(after: &str) -> Option { + let (at, id) = after.split_once('|')?; + (!at.is_empty() && !id.is_empty()).then(|| AuditCursor { + at: at.to_owned(), + id: id.to_owned(), + }) +} + +/// The filters as a query string, without the cursor. +fn filter_query(query: &AuditQuery) -> String { + format!( + "action={}&actor={}&target={}&from={}&to={}", + encode(&query.action), + encode(&query.actor), + encode(&query.target), + encode(&query.from), + encode(&query.to), + ) +} + +/// Percent-encodes everything but the unreserved characters, so a filter value cannot add a parameter. +fn encode(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for byte in value.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') { + out.push(char::from(byte)); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} + +/// The audit page: the filters, the entries, and the links to the newest and the next page. +fn audit_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + base: String, + query: AuditQuery, + entries: Vec, + next_href: Option, +) -> impl View { + let newest = format!("/admin/audit?{base}"); + view! { cx => + shell(title: text(lang, A::AuditTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Audit) +
+

(text(lang, A::AuditTitle))

+

(text(lang, A::AuditIntro))

+
+ + + + + + +
+

(text(lang, A::AuditNewer))

+ if entries.is_empty() { +

(text(lang, A::AuditNoEntries))

+ } else { + + + + + + + + + + + for entry in entries { + audit_row(entry: entry) + } + +
(text(lang, A::AuditWhen))(text(lang, A::AuditWho))(text(lang, A::AuditAction))(text(lang, A::AuditTarget))(text(lang, A::AuditIp))(text(lang, A::AuditDetails))
+ } + if let Some(href) = next_href { +

(text(lang, A::AuditOlder))

+ } +
+ ) + } +} + +/// One entry of the log. Its details are text from the store; the view escapes them. +#[component] +async fn audit_row(entry: AuditEntry) -> Result { + let who = entry + .actor_id + .clone() + .unwrap_or_else(|| entry.actor_kind.clone()); + let target = match (&entry.target_kind, &entry.target_id) { + (Some(kind), Some(id)) => format!("{kind}:{id}"), + _ => String::new(), + }; + Ok(view! { + + (entry.at.clone()) + (who) + (entry.action.clone()) + (target) + (entry.ip.clone().unwrap_or_default()) + (entry.data.clone().unwrap_or_default()) + + }) +} diff --git a/crates/im-web/src/pages/admin/clients.rs b/crates/im-web/src/pages/admin/clients.rs new file mode 100644 index 0000000..b2f4116 --- /dev/null +++ b/crates/im-web/src/pages/admin/clients.rs @@ -0,0 +1,646 @@ +//! `/admin/services`: the OpenID clients and the switcher list, with the form that registers a client, and +//! `/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. +//! +//! The rotate action shows the new secret once on the same page, for the same reason. + +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::store::admin::ClientEdit; +use im_core::store::clients::NewClient; +use im_core::token::{generate_token, hash_token}; +use serde::Deserialize; +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::{page, route}; +use topcoat::view::{View, component, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{require_admin, require_admin_csrf}; +use crate::i18n::Lang; +use crate::i18n::admin::{A, text}; +use crate::pages::admin::{ + FlashQuery, Tab, action_button, changed, done, error_text, flash_messages, frame_info, + notice_text, refused, tabs, +}; +use crate::pages::path_param; +use crate::state::AppState; +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 { + #[serde(default)] + csrf: String, + #[serde(default)] + name: String, + /// One URI per line. + #[serde(default)] + redirect_uris: String, + /// One URI per line. + #[serde(default)] + post_logout_uris: String, + #[serde(default)] + backchannel_uri: String, + /// Space-separated scopes. + #[serde(default)] + scopes: String, + #[serde(default)] + family_key: String, + /// The origin of a family app, such as `https://in.example.com`. + #[serde(default)] + public_url: String, +} + +/// A form with only the CSRF token. +#[derive(Deserialize, Default)] +struct CsrfForm { + #[serde(default)] + csrf: String, +} + +/// A client form after its checks: every value is in the form the store takes. +struct Checked { + name: String, + redirect_uris: Vec, + post_logout_uris: Vec, + backchannel_uri: Option, + scopes: String, + family_key: Option, + public_url: Option, +} + +/// Checks a client form the way `im client add` does. Returns the code of the first problem, which +/// [`error_text`] turns into a message. +fn check(form: &ClientForm) -> std::result::Result { + let name = parse_display_name(&form.name).map_err(|_| "client-name")?; + let redirect_uris = uri_lines(&form.redirect_uris)?; + let post_logout_uris = uri_lines(&form.post_logout_uris)?; + let backchannel = form.backchannel_uri.trim(); + let backchannel_uri = if backchannel.is_empty() { + None + } else if is_valid_registered_uri(backchannel) { + Some(backchannel.to_owned()) + } else { + return Err("client-uri"); + }; + let mut scopes: Vec<&str> = Vec::new(); + for word in form.scopes.split_whitespace() { + if !is_supported_scope(word) { + return Err("scopes"); + } + if !scopes.contains(&word) { + scopes.push(word); + } + } + if scopes.is_empty() { + return Err("scopes"); + } + let key = form.family_key.trim(); + let family_key = if key.is_empty() { + None + } else if key == HOME_KEY || !is_valid_family_key(key) { + return Err("family-key"); + } else { + Some(key.to_owned()) + }; + let public = form.public_url.trim(); + let public_url = match (&family_key, public.is_empty()) { + // A family app needs the public address its switcher link goes to. + (Some(_), false) if is_origin(public) => Some(public.to_owned()), + (Some(_), _) => return Err("public-url"), + (None, false) => return Err("public-url"), + (None, true) => None, + }; + Ok(Checked { + name, + redirect_uris, + post_logout_uris, + backchannel_uri, + scopes: scopes.join(" "), + family_key, + public_url, + }) +} + +/// The URIs of a textarea: one per line, blank lines ignored, each checked by the same rule the +/// endpoints use. +fn uri_lines(text: &str) -> std::result::Result, &'static str> { + let mut uris = Vec::new(); + for line in text.lines().map(str::trim).filter(|line| !line.is_empty()) { + if !is_valid_registered_uri(line) { + return Err("client-uri"); + } + uris.push(line.to_owned()); + } + Ok(uris) +} + +/// True for an origin: `http://` or `https://`, a host, and no path, space or query. +pub(crate) fn is_origin(url: &str) -> bool { + let rest = url + .strip_prefix("https://") + .or_else(|| url.strip_prefix("http://")); + rest.is_some_and(|rest| { + !rest.is_empty() + && !rest.contains(['/', '?', '#', '@']) + && !url.chars().any(char::is_whitespace) + }) +} + +/// The form values of a stored client, for the edit form. +fn prefill(client: &Client, public_url: Option<&str>) -> ClientForm { + ClientForm { + csrf: String::new(), + name: client.name.clone(), + redirect_uris: client.redirect_uris.join("\n"), + post_logout_uris: client.post_logout_redirect_uris.join("\n"), + backchannel_uri: client.backchannel_logout_uri.clone().unwrap_or_default(), + scopes: client.allowed_scopes.clone(), + family_key: client.service_key.clone().unwrap_or_default(), + public_url: public_url.unwrap_or_default().to_owned(), + } +} + +/// `GET /admin/services`: the switcher, the clients, and the form that registers one. +#[page("/admin/services")] +async fn services_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let services = state.store.list_services().await?; + let clients = state.store.list_clients().await?; + let defaults = ClientForm { + scopes: DEFAULT_SCOPES.to_owned(), + ..ClientForm::default() + }; + Ok(services_view( + cx, + lang, + info, + viewer.session.csrf_token.clone(), + services, + clients, + defaults, + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), + None, + )) +} + +/// `POST /admin/services`: registers a client. On success the secret is shown on this page, once. +#[page(POST "/admin/services")] +async fn create_client(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 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() + }; + 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 + .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(), + }) + .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()), + } + } + } + let services = state.store.list_services().await?; + let clients = state.store.list_clients().await?; + Ok(services_view( + cx, lang, info, csrf, services, clients, shown, success, problem, created, + )) +} + +/// What the page shows once about a new client: its id and its secret. +struct Created { + id: String, + name: String, + secret: String, +} + +/// `GET /admin/services/{id}`: one client's settings. +#[page("/admin/services/{id}")] +async fn client_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let client = client_from_path(cx, state).await?; + let public_url = public_url_of(state, &client).await?; + Ok(detail_view( + cx, + lang, + info, + viewer.session.csrf_token.clone(), + client, + public_url, + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), + None, + )) +} + +/// The client named by the path, or 404. +async fn client_from_path(cx: &Cx, state: &AppState) -> Result { + let Some(id) = path_param(cx, "id") else { + return Err(not_found().into()); + }; + state + .store + .client_row(&id) + .await? + .ok_or_else(|| not_found().into()) +} + +/// The public address of a family client: the URL of its switcher row, when it has one. +async fn public_url_of(state: &AppState, client: &Client) -> Result> { + let Some(key) = &client.service_key else { + return Ok(None); + }; + Ok(state + .store + .list_services() + .await? + .into_iter() + .find(|service: &Service| &service.key == key) + .map(|service| service.url)) +} + +/// `POST /admin/services/{id}/edit`. A rejected form goes back to the client's page with the reason. +#[route(POST "/admin/services/{id}/edit")] +async fn edit_client(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let client = client_from_path(cx, state).await?; + let base = format!("/admin/services/{}", client.id); + let checked = match check(&form) { + Ok(checked) => checked, + Err(code) => return Ok(refused(&base, code)), + }; + let edit = ClientEdit { + name: &checked.name, + 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(), + }; + match state.store.update_client(&client.id, &edit).await { + Ok(true) => {} + Ok(false) => return Ok(refused("/admin/services", "no-client")), + Err(CoreError::Conflict(_)) => return Ok(refused(&base, "family-taken")), + Err(error) => return Err(error.into()), + } + 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::ClientUpdated, + Some(("client", &client.id)), + json!({}), + ) + .await; + changed(&state.live); + 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 { + 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(); + state + .store + .rotate_client_secret(&client.id, &hash_token(&secret)) + .await?; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::ClientSecretRotated, + Some(("client", &client.id)), + json!({}), + ) + .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), + )) +} + +/// `POST /admin/services/{id}/disable`. A disabled client cannot sign in or exchange tokens. +#[route(POST "/admin/services/{id}/disable")] +async fn disable_client(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let client = client_from_path(cx, state).await?; + let base = format!("/admin/services/{}", client.id); + if !state.store.disable_client(&client.id).await? { + return Ok(refused(&base, "no-client")); + } + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::ClientDisabled, + Some(("client", &client.id)), + json!({}), + ) + .await; + changed(&state.live); + Ok(done(&base, "client-disabled")) +} + +/// The services and clients page. +#[allow(clippy::too_many_arguments)] +fn services_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + services: Vec, + clients: Vec, + form: ClientForm, + success: Option, + problem: Option, + created: Option, +) -> impl View { + view! { cx => + shell(title: text(lang, A::ServicesTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Services) +
+

(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))

+ } else { +
    + for service in services { + service_item(lang: lang, service: service) + } +
+ } +

(text(lang, A::ClientsList))

+ if clients.is_empty() { +

(text(lang, A::NoClients))

+ } else { +
    + for client in clients { + client_item(lang: lang, client: client) + } +
+ } +

(text(lang, A::ClientCreateTitle))

+
+ + client_fields(lang: lang, values: form) + +
+
+ ) + } +} + +/// The one-time secret of a new or rotated client. +#[component] +async fn secret_box(lang: Lang, created: Created) -> Result { + Ok(view! { +
+

(created.name.clone())

+

(text(lang, A::SecretShown))

+
+
(text(lang, A::ClientIdLabel))
(created.id.clone())
+
(text(lang, A::SecretLabel))
(created.secret.clone())
+
+

(text(lang, A::SecretOnce))

+
+ }) +} + +/// One switcher row: the name, its address and its last health check. +#[component] +async fn service_item(lang: Lang, service: Service) -> Result { + let health = match service.healthy { + Some(true) => text(lang, A::Healthy), + Some(false) => text(lang, A::Unhealthy), + None => text(lang, A::NotChecked), + }; + Ok(view! { +
  • +
    + (service.name.clone()) +
    + (service.url.clone()) + " · "(health) +
    +
    +
  • + }) +} + +/// One client row, linking to its page. +#[component] +async fn client_item(lang: Lang, client: Client) -> Result { + let href = format!("/admin/services/{}", client.id); + let status = if client.disabled_at.is_some() { + text(lang, A::ClientDisabledLabel) + } else { + text(lang, A::Active) + }; + Ok(view! { +
  • +
    + (client.name.clone()) + if let Some(key) = client.service_key.clone() { + (key) + } +
    + (client.allowed_scopes.clone()) + " · "(status) +
    +
    + (text(lang, A::Open)) +
  • + }) +} + +/// The fields of a client, shared by the create and the edit forms. +#[component] +async fn client_fields(lang: Lang, values: ClientForm) -> Result { + Ok(view! { + field(label: text(lang, A::ClientName), name: "name", kind: "text", autocomplete: "off", value: values.name.clone()) + + + + + + + }) +} + +/// One client's page: its facts, the edit form, and the rotate and disable actions. +#[allow(clippy::too_many_arguments)] +fn detail_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + client: Client, + public_url: Option, + success: Option, + problem: Option, + secret: Option, +) -> impl View { + let base = format!("/admin/services/{}", client.id); + let values = prefill(&client, public_url.as_deref()); + let status = if client.disabled_at.is_some() { + text(lang, A::ClientDisabledLabel) + } else { + text(lang, A::Active) + }; + view! { cx => + shell(title: text(lang, A::ClientEditTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Services) +
    +

    (text(lang, A::ServicesTitle))

    +

    (client.name.clone())

    + flash_messages(success: success, problem: problem) + if let Some(secret) = secret { + secret_box(lang: lang, created: secret) + } +
    +
    (text(lang, A::ClientIdLabel))
    (client.id.clone())
    +
    (text(lang, A::Status))
    (status)
    +
    (text(lang, A::Created))
    (client.created_at.clone())
    +
    +
    + + client_fields(lang: lang, values: values) + +
    +
    + action_button(action: format!("{base}/rotate"), csrf: csrf.clone(), label: text(lang, A::RotateSecret), class: "button ghost", on: "") + if !client.disabled_at.is_some() { + action_button(action: format!("{base}/disable"), csrf: csrf.clone(), label: text(lang, A::DisableClient), class: "button danger", on: "") + } +
    +
    + ) + } +} diff --git a/crates/im-web/src/pages/admin/health.rs b/crates/im-web/src/pages/admin/health.rs new file mode 100644 index 0000000..d66f700 --- /dev/null +++ b/crates/im-web/src/pages/admin/health.rs @@ -0,0 +1,149 @@ +//! `/admin/health`: the state of the switcher services, the mail outboxes, the database file, the backups, +//! and the account counts. Read only; nothing here changes anything. +//! +//! A service shows the answer of its last health probe, or "not checked" before the first one. + +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::page; +use topcoat::view::{View, component, view}; + +use crate::auth::require_admin; +use crate::i18n::Lang; +use crate::i18n::admin::{A, text}; +use crate::pages::admin::{Tab, frame_info, tabs}; +use crate::state::AppState; +use crate::views::{ViewerInfo, shell}; + +/// `GET /admin/health`. +#[page("/admin/health")] +async fn health_page(cx: &Cx) -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let services = state.store.list_services().await?; + let outbox = state.store.outbox_counts().await?; + let users = state.store.user_count().await?; + let admins = state.store.enabled_admin_count().await?; + let database_bytes = std::fs::metadata(&state.config.database) + .map(|meta| meta.len()) + .unwrap_or(0); + let backups = if state.config.backup.dir.as_os_str().is_empty() { + None + } else { + Some(Backups { + last_success: state.store.setting("backup.last_success").await?, + last_error: state.store.setting("backup.last_error").await?, + }) + }; + Ok(health_view( + cx, + lang, + info, + services + .into_iter() + .map(|service| ServiceRow { + name: service.name, + url: service.url, + healthy: service.healthy, + }) + .collect(), + outbox, + users, + admins, + database_bytes, + backups, + )) +} + +/// The backup settings as the page reads them. +struct Backups { + last_success: Option, + last_error: Option, +} + +/// One switcher service, as the page shows it. +struct ServiceRow { + name: String, + url: String, + healthy: Option, +} + +/// The health page. +#[allow(clippy::too_many_arguments)] +fn health_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + services: Vec, + outbox: Vec<(String, i64)>, + users: u64, + admins: u64, + database_bytes: u64, + backups: Option, +) -> impl View { + view! { cx => + shell(title: text(lang, A::HealthTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Health) +
    +

    (text(lang, A::HealthTitle))

    +

    (text(lang, A::HealthIntro))

    +

    (text(lang, A::HealthServices))

    + if services.is_empty() { +

    (text(lang, A::NoServices))

    + } else { +
      + for service in services { + service_row(lang: lang, service: service) + } +
    + } +

    (text(lang, A::HealthOutbox))

    + if outbox.is_empty() { +

    (text(lang, A::NoMail))

    + } else { +
    + for (state, count) in outbox { +
    (state.clone())
    (count)
    + } +
    + } +

    (text(lang, A::HealthBackups))

    + if let Some(backups) = backups { +
    +
    (text(lang, A::HealthBackupLast))
    (backups.last_success.clone().unwrap_or_else(|| String::from("-")))
    + if let Some(error) = backups.last_error { +
    (text(lang, A::HealthBackupError))
    (error)
    + } +
    + } else { +

    (text(lang, A::HealthBackupOff))

    + } +

    (text(lang, A::HealthDatabase))

    +
    +
    (text(lang, A::HealthBytes))
    (database_bytes.to_string())
    +
    (text(lang, A::HealthUsers))
    (users.to_string())
    +
    (text(lang, A::HealthAdmins))
    (admins.to_string())
    +
    +
    + ) + } +} + +/// One service row: its name, its address, and the answer of its last probe. +#[component] +async fn service_row(lang: Lang, service: ServiceRow) -> Result { + let health = match service.healthy { + Some(true) => text(lang, A::Healthy), + Some(false) => text(lang, A::Unhealthy), + None => text(lang, A::NotChecked), + }; + Ok(view! { +
  • +
    + (service.name.clone()) +
    (service.url.clone())" · "(health)
    +
    +
  • + }) +} diff --git a/crates/im-web/src/pages/admin/invites.rs b/crates/im-web/src/pages/admin/invites.rs new file mode 100644 index 0000000..0e4395a --- /dev/null +++ b/crates/im-web/src/pages/admin/invites.rs @@ -0,0 +1,281 @@ +//! `/admin/invites`: the invitations that can still be used, a form to send a new one, and the two actions on +//! a pending invitation: revoke it, and send a new link (which replaces the old one). +//! +//! A pending invitation is identified in the page by the hash of its token. The hash is not a usable token, +//! so showing it is harmless. Creating an invitation for an address replaces that address's older pending +//! invitations in the store, so only the newest link works. + +use im_core::Error as CoreError; +use im_core::model::AuditAction; +use im_core::names::parse_email; +use im_core::store::invites::invite_lifetime; +use im_core::time::stamp_after; +use im_core::token::{generate_token, hash_token}; +use serde::Deserialize; +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::{page, route}; +use topcoat::view::{View, component, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{Viewer, require_admin, require_admin_csrf}; +use crate::i18n::Lang; +use crate::i18n::admin::{A, text}; +use crate::mail::{self, Mail, Recipient}; +use crate::pages::admin::{ + FlashQuery, Tab, action_button, changed, done, error_text, flash_messages, frame_info, + notice_text, refused, tabs, +}; +use crate::pages::path_param; +use crate::state::AppState; +use crate::views::{ViewerInfo, field, page_lang, shell}; + +/// The form that sends an invitation. +#[derive(Deserialize, Default)] +struct InviteForm { + #[serde(default)] + csrf: String, + #[serde(default)] + email: String, + /// The checkbox: `on` when ticked. + #[serde(default)] + admin: String, +} + +/// The form of a pending invitation's actions: only the CSRF token. +#[derive(Deserialize, Default)] +struct CsrfForm { + #[serde(default)] + csrf: String, +} + +/// One pending invitation, with its text resolved. +struct InviteRow { + email: String, + admin: bool, + expires: String, + hash: String, +} + +/// `GET /admin/invites`. +#[page("/admin/invites")] +async fn invites_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let rows: Vec = state + .store + .pending_invites() + .await? + .into_iter() + .map(|invite| InviteRow { + email: invite.email_folded, + admin: invite.is_admin, + expires: invite.expires_at, + hash: invite.token_hash, + }) + .collect(); + Ok(invites_view( + cx, + lang, + info, + viewer.session.csrf_token.clone(), + rows, + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), + )) +} + +/// `POST /admin/invites`: creates the invitation and queues its mail. +#[route(POST "/admin/invites")] +async fn send_invite(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let email = match parse_email(&form.email) { + Ok(email) => email, + Err(_) => return Ok(refused("/admin/invites", "email")), + }; + let is_admin = form.admin == "on"; + let state = app_context::(cx); + let days = state.policy().invite_days; + let token = generate_token(); + let expires = stamp_after(invite_lifetime(days)); + match state + .store + .create_invite( + &hash_token(&token), + &email, + is_admin, + &viewer.user.id, + &expires, + ) + .await + { + Ok(()) => {} + Err(CoreError::Conflict(_)) => return Ok(refused("/admin/invites", "invite-taken")), + Err(error) => return Err(error.into()), + } + queue_invite(cx, &viewer, &email, &token, days).await; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::InviteCreated, + None, + json!({ "admin": is_admin }), + ) + .await; + changed(&state.live); + Ok(done("/admin/invites", "invite-sent")) +} + +/// Queues the invitation mail for `email`, with the link for `token`. A failure is logged, not returned: +/// the invitation exists and can be sent again from this page. +async fn queue_invite(cx: &Cx, viewer: &Viewer, email: &str, token: &str, days: u32) { + let state = app_context::(cx); + let lang = page_lang(cx, Some(viewer)); + let link = format!("{}/invite/{token}", state.config.base_url); + match Recipient::new(None, email) { + Ok(to) => { + let mail = Mail::Invite { link: &link, days }; + if let Err(error) = mail::queue(&state.store, &state.key, &to, lang, &mail).await { + tracing::error!(error = %error, "invitation mail not queued"); + } + } + Err(error) => tracing::error!(error, "invitation mail not queued"), + } +} + +/// `POST /admin/invites/{hash}/revoke`. +#[route(POST "/admin/invites/{hash}/revoke")] +async fn revoke_invite(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let hash = invite_hash(cx)?; + let state = app_context::(cx); + if state.store.revoke_invite(&hash).await? { + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::InviteRevoked, + None, + json!({}), + ) + .await; + changed(&state.live); + return Ok(done("/admin/invites", "invite-revoked")); + } + Ok(refused("/admin/invites", "invite-gone")) +} + +/// `POST /admin/invites/{hash}/resend`. A new token is made and mailed; the old link stops working, because +/// the store keeps only the newest pending invitation for an address. +#[route(POST "/admin/invites/{hash}/resend")] +async fn resend_invite(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let hash = invite_hash(cx)?; + let state = app_context::(cx); + let Some(old) = state.store.pending_invite(&hash).await? else { + return Ok(refused("/admin/invites", "invite-gone")); + }; + let days = state.policy().invite_days; + let token = generate_token(); + let expires = stamp_after(invite_lifetime(days)); + match state + .store + .create_invite( + &hash_token(&token), + &old.email_folded, + old.is_admin, + &viewer.user.id, + &expires, + ) + .await + { + Ok(()) => {} + Err(CoreError::Conflict(_)) => return Ok(refused("/admin/invites", "invite-taken")), + Err(error) => return Err(error.into()), + } + queue_invite(cx, &viewer, &old.email_folded, &token, days).await; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::InviteCreated, + None, + json!({ "admin": old.is_admin, "resent": true }), + ) + .await; + changed(&state.live); + Ok(done("/admin/invites", "invite-resent")) +} + +/// The hash in the path of an invitation action. Anything that is not 64 hex digits is a 404. +fn invite_hash(cx: &Cx) -> Result { + match path_param(cx, "hash") { + Some(hash) if hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(hash), + _ => Err(not_found().into()), + } +} + +/// The invitations page: the pending list, then the form that sends a new one. +fn invites_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + rows: Vec, + success: Option, + problem: Option, +) -> impl View { + view! { cx => + shell(title: text(lang, A::InvitesTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Invites) +
    +

    (text(lang, A::InvitesTitle))

    +

    (text(lang, A::InvitesIntro))

    + flash_messages(success: success, problem: problem) +

    (text(lang, A::PendingInvites))

    + if rows.is_empty() { +

    (text(lang, A::NoInvites))

    + } else { +
      + for row in rows { + invite_item(lang: lang, csrf: csrf.clone(), row: row) + } +
    + } +

    (text(lang, A::InviteNew))

    +
    + + field(label: text(lang, A::InviteEmailLabel), name: "email", kind: "email", autocomplete: "off", value: String::new()) + + +
    +
    + ) + } +} + +/// One pending invitation with its two actions. +#[component] +async fn invite_item(lang: Lang, csrf: String, row: InviteRow) -> Result { + let base = format!("/admin/invites/{}", row.hash); + Ok(view! { +
  • +
    + (row.email.clone()) + if row.admin { + (text(lang, A::Administrator)) + } +
    + (text(lang, A::Expires))": "(row.expires.clone()) +
    +
    + action_button(action: format!("{base}/resend"), csrf: csrf.clone(), label: text(lang, A::ResendInvite), class: "button ghost", on: "") + action_button(action: format!("{base}/revoke"), csrf: csrf.clone(), label: text(lang, A::RevokeInvite), class: "button danger", on: "") +
  • + }) +} diff --git a/crates/im-web/src/pages/admin/keys.rs b/crates/im-web/src/pages/admin/keys.rs new file mode 100644 index 0000000..d3a8b22 --- /dev/null +++ b/crates/im-web/src/pages/admin/keys.rs @@ -0,0 +1,222 @@ +//! `/admin/keys`: the token-signing keys, with a rotation now and the retirement of a key that is still +//! published. +//! +//! A key's state is read from the same rules the signer uses (`im_core::keys`): the current key signs, the +//! published keys are in the JWKS, and a retired key is no longer published. The store refuses to retire the +//! current key, so a token can always be signed. + +use im_core::model::AuditAction; +use im_core::time::now_stamp; +use serde::Deserialize; +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::{page, route}; +use topcoat::view::{View, component, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{require_admin, require_admin_csrf}; +use crate::i18n::Lang; +use crate::i18n::admin::{A, text}; +use crate::oidc::signing; +use crate::pages::admin::{ + FlashQuery, Tab, action_button, changed, done, error_text, flash_messages, frame_info, + notice_text, refused, tabs, +}; +use crate::pages::path_param; +use crate::state::AppState; +use crate::views::{ViewerInfo, shell}; + +/// The form of the key actions: only the CSRF token. +#[derive(Deserialize, Default)] +struct CsrfForm { + #[serde(default)] + csrf: String, +} + +/// Where a key stands now. +#[derive(Clone, Copy, PartialEq, Eq)] +enum KeyState { + Current, + Published, + Retired, + Pending, +} + +/// One key, with its times and its state resolved. +struct KeyRow { + kid: String, + created: String, + activates: String, + retires: String, + state: KeyState, + /// True when the store will retire the key: not yet retired, not current, and already active. + retirable: bool, +} + +/// `GET /admin/keys`. +#[page("/admin/keys")] +async fn keys_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let now = now_stamp(); + let keys = state.store.signing_keys().await?; + let current = im_core::keys::current(&keys, &now).map(|key| key.kid.clone()); + let published: Vec = im_core::keys::published(&keys, &now) + .iter() + .map(|key| key.kid.clone()) + .collect(); + let rows: Vec = keys + .iter() + .map(|key| { + let is_current = Some(&key.kid) == current.as_ref(); + let state = if is_current { + KeyState::Current + } else if published.contains(&key.kid) { + KeyState::Published + } else if key.activates_at > now { + KeyState::Pending + } else { + KeyState::Retired + }; + KeyRow { + kid: key.kid.clone(), + created: key.created_at.clone(), + activates: key.activates_at.clone(), + retires: key.retires_at.clone().unwrap_or_default(), + state, + retirable: key.retires_at.is_none() && !is_current && key.activates_at <= now, + } + }) + .collect(); + Ok(keys_view( + cx, + lang, + info, + viewer.session.csrf_token.clone(), + rows, + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), + )) +} + +/// `POST /admin/keys/rotate`: makes a new key the signing key now. +#[route(POST "/admin/keys/rotate")] +async fn rotate_keys(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let kid = signing::rotate_now(&state.store, &state.key).await?; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::KeyRotated, + Some(("signing_key", &kid)), + json!({}), + ) + .await; + changed(&state.live); + Ok(done("/admin/keys", "key-rotated")) +} + +/// `POST /admin/keys/{kid}/retire`. +#[route(POST "/admin/keys/{kid}/retire")] +async fn retire_key(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let kid = key_id(cx)?; + let state = app_context::(cx); + if state.store.retire_signing_key(&kid).await? { + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::KeyRetired, + Some(("signing_key", &kid)), + json!({}), + ) + .await; + changed(&state.live); + return Ok(done("/admin/keys", "key-retired")); + } + Ok(refused("/admin/keys", "key-current")) +} + +/// The key id in the path. Key ids are letters, digits, `-` and `_`; anything else is a 404. +fn key_id(cx: &Cx) -> Result { + match path_param(cx, "kid") { + Some(kid) + if !kid.is_empty() + && kid.len() <= 64 + && kid + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') => + { + Ok(kid) + } + _ => Err(not_found().into()), + } +} + +/// The text of a key state. +fn state_text(lang: Lang, state: KeyState) -> &'static str { + match state { + KeyState::Current => text(lang, A::KeyCurrent), + KeyState::Published => text(lang, A::KeyPublished), + KeyState::Retired => text(lang, A::KeyRetired), + KeyState::Pending => text(lang, A::KeyPending), + } +} + +/// The keys page: the rotation button, then one row per key. +fn keys_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + rows: Vec, + success: Option, + problem: Option, +) -> impl View { + view! { cx => + shell(title: text(lang, A::KeysTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Keys) +
    +

    (text(lang, A::KeysTitle))

    +

    (text(lang, A::KeysIntro))

    + flash_messages(success: success, problem: problem) + action_button(action: "/admin/keys/rotate".to_owned(), csrf: csrf.clone(), label: text(lang, A::RotateNow), class: "button primary", on: "") +
      + for row in rows { + key_item(lang: lang, csrf: csrf.clone(), row: row) + } +
    +
    + ) + } +} + +/// One key: its id, its times, its state, and the retire button when the store allows it. +#[component] +async fn key_item(lang: Lang, csrf: String, row: KeyRow) -> Result { + let state = state_text(lang, row.state); + let retire = format!("/admin/keys/{}/retire", row.kid); + Ok(view! { +
  • +
    + (row.kid.clone()) +
    + (text(lang, A::KeyCreated))": "(row.created.clone()) + " · "(text(lang, A::KeyActivates))": "(row.activates.clone()) + if !row.retires.is_empty() { + " · "(text(lang, A::KeyRetires))": "(row.retires.clone()) + } + " · "(state) +
    +
    + if row.retirable { + action_button(action: retire, csrf: csrf.clone(), label: text(lang, A::RetireKey), class: "button danger", on: "") + } +
  • + }) +} diff --git a/crates/im-web/src/pages/admin/mail.rs b/crates/im-web/src/pages/admin/mail.rs new file mode 100644 index 0000000..93cf155 --- /dev/null +++ b/crates/im-web/src/pages/admin/mail.rs @@ -0,0 +1,299 @@ +//! `/admin/mail`: the state of the SMTP settings, the mail outbox with its states, the retry and abandon +//! actions, and a test mail to the administrator's own address. +//! +//! The outbox never shows a body: the store holds it sealed, and the list selects only the header columns. +//! Retrying a failed row sends it again at once; abandoning a row that is not yet sent blanks its body, as +//! the worker does when it gives up. + +use im_core::model::AuditAction; +use serde::Deserialize; +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::{page, route}; +use topcoat::view::{View, component, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{require_admin, require_admin_csrf}; +use crate::i18n::Lang; +use crate::i18n::admin::{A, text}; +use crate::mail::{self, Mail, Recipient}; +use crate::pages::admin::{ + PAGE_SIZE, Tab, action_button, changed, done, error_text, flash_messages, frame_info, + notice_text, refused, tabs, +}; +use crate::pages::path_param; +use crate::state::AppState; +use crate::views::{ViewerInfo, page_lang, shell}; + +/// The query of the mail page: the flash codes, the state filter, and the cursor of the next page. +#[derive(Deserialize, Default)] +struct MailQuery { + #[serde(default)] + notice: String, + #[serde(default)] + error: String, + /// `pending`, `sent`, `failed` or `abandoned`. Anything else shows every state. + #[serde(default)] + state: String, + /// The id of the last row of the previous page. + #[serde(default)] + after: String, +} + +/// The form of the mail actions: only the CSRF token. +#[derive(Deserialize, Default)] +struct CsrfForm { + #[serde(default)] + csrf: String, +} + +/// The SMTP settings as the page shows them. The password is never shown, only whether a login is set. +struct SmtpInfo { + host: String, + sender: String, + login: String, +} + +/// The states the filter links offer. +const STATES: [&str; 4] = ["pending", "sent", "failed", "abandoned"]; + +/// `GET /admin/mail`. +#[page("/admin/mail")] +async fn mail_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let filter = STATES + .contains(&query.state.as_str()) + .then(|| query.state.clone()); + let after = (!query.after.is_empty()).then(|| query.after.clone()); + let mut rows = state + .store + .outbox_page(filter.as_deref(), after.as_deref(), PAGE_SIZE + 1) + .await?; + let next = if rows.len() > PAGE_SIZE as usize { + rows.truncate(PAGE_SIZE as usize); + rows.last().map(|row| row.id.clone()) + } else { + None + }; + let counts = state.store.outbox_counts().await?; + let smtp = state.config.smtp.enabled().then(|| SmtpInfo { + host: format!("{}:{}", state.config.smtp.host, state.config.smtp.port), + sender: format!( + "{} <{}>", + state.config.smtp.from_name, state.config.smtp.from + ), + login: if state.config.smtp.username.is_empty() { + String::from("-") + } else { + state.config.smtp.username.clone() + }, + }); + Ok(mail_view( + cx, + lang, + info, + viewer.session.csrf_token.clone(), + smtp, + counts, + filter.unwrap_or_default(), + rows, + next, + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), + )) +} + +/// `POST /admin/mail/test`: queues a test mail to the administrator's own address. +#[route(POST "/admin/mail/test")] +async fn send_test(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + let Ok(to) = Recipient::new(Some(&viewer.user.name), &viewer.user.email) else { + return Ok(refused("/admin/mail", "email")); + }; + let mail = Mail::Test { + subject: text(lang, A::TestMailSubject), + body: text(lang, A::TestMailBody), + }; + mail::queue(&state.store, &state.key, &to, lang, &mail).await?; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::MailTestQueued, + None, + json!({}), + ) + .await; + changed(&state.live); + Ok(done("/admin/mail", "test-queued")) +} + +/// `POST /admin/mail/{id}/retry`: a failed row is sent again now. +#[route(POST "/admin/mail/{id}/retry")] +async fn retry_mail(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let id = outbox_id(cx)?; + let state = app_context::(cx); + if !state.store.retry_mail(&id).await? { + return Ok(refused("/admin/mail", "mail-retry")); + } + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::MailRetried, + Some(("mail", &id)), + json!({}), + ) + .await; + changed(&state.live); + Ok(done("/admin/mail", "mail-retried")) +} + +/// `POST /admin/mail/{id}/abandon`: a row that is not yet sent is given up, and its body is removed. +#[route(POST "/admin/mail/{id}/abandon")] +async fn abandon_mail(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let id = outbox_id(cx)?; + let state = app_context::(cx); + if !state.store.abandon_mail(&id).await? { + return Ok(refused("/admin/mail", "mail-abandon")); + } + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::MailAbandoned, + Some(("mail", &id)), + json!({}), + ) + .await; + changed(&state.live); + Ok(done("/admin/mail", "mail-abandoned")) +} + +/// The outbox id in the path. Ids are ULIDs: 26 letters and digits. Anything else is a 404. +fn outbox_id(cx: &Cx) -> Result { + match path_param(cx, "id") { + Some(id) if id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) => Ok(id), + _ => Err(not_found().into()), + } +} + +/// The mail page: SMTP status, the state counts, the filter links, the outbox, and the test button. +#[allow(clippy::too_many_arguments)] +fn mail_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + smtp: Option, + counts: Vec<(String, i64)>, + filter: String, + rows: Vec, + next: Option, + success: Option, + problem: Option, +) -> impl View { + let next_href = next.map(|after| { + if filter.is_empty() { + format!("/admin/mail?after={after}") + } else { + format!("/admin/mail?state={filter}&after={after}") + } + }); + view! { cx => + shell(title: text(lang, A::MailTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Mail) +
    +

    (text(lang, A::MailTitle))

    +

    (text(lang, A::MailIntro))

    + flash_messages(success: success, problem: problem) +

    (text(lang, A::SmtpStatus))

    + if let Some(smtp) = smtp { +
    +
    (text(lang, A::SmtpHost))
    (smtp.host.clone())
    +
    (text(lang, A::SmtpSender))
    (smtp.sender.clone())
    +
    (text(lang, A::SmtpLogin))
    (smtp.login.clone())
    +
    + } else { +

    (text(lang, A::SmtpNotConfigured))

    + } + action_button(action: "/admin/mail/test".to_owned(), csrf: csrf.clone(), label: text(lang, A::SendTest), class: "button ghost", on: "") +

    (text(lang, A::OutboxTitle))

    +

    + (text(lang, A::OutboxFilter))": " + (text(lang, A::AllStates)) + for (state, count) in counts { + (state_label(lang, &state))" ("(count)")" + } +

    + if rows.is_empty() { +

    (text(lang, A::NoMail))

    + } else { +
      + for row in rows { + mail_item(lang: lang, csrf: csrf.clone(), row: row) + } +
    + } + if let Some(href) = next_href { +

    (text(lang, A::NextPage))

    + } +
    + ) + } +} + +/// The text of an outbox state. Unknown states are shown as they are stored. +fn state_label(lang: Lang, state: &str) -> String { + match state { + "pending" => text(lang, A::StatePending).to_owned(), + "sent" => text(lang, A::StateSent).to_owned(), + "failed" => text(lang, A::StateFailed).to_owned(), + "abandoned" => text(lang, A::StateAbandoned).to_owned(), + other => other.to_owned(), + } +} + +/// One outbox row: its recipient, subject, state, attempts, and the actions the state allows. +#[component] +async fn mail_item( + lang: Lang, + csrf: String, + row: im_core::store::admin::OutboxRow, +) -> Result { + let state = state_label(lang, &row.state); + let retry = format!("/admin/mail/{}/retry", row.id); + let abandon = format!("/admin/mail/{}/abandon", row.id); + let can_retry = row.state == "failed"; + let can_abandon = row.state == "pending" || row.state == "failed"; + Ok(view! { +
  • +
    + (row.subject.clone()) +
    + (row.to_addr.clone()) + " · "(row.kind.clone()) + " · "(state) + " · "(text(lang, A::Attempts))": "(row.attempts) + " · "(text(lang, A::NextAttempt))": "(row.next_attempt_at.clone()) + " · "(text(lang, A::Created))": "(row.created_at.clone()) +
    + if let Some(error) = row.last_error.clone() { +
    (text(lang, A::LastError))": "(error)
    + } +
    + if can_retry { + action_button(action: retry, csrf: csrf.clone(), label: text(lang, A::Retry), class: "button ghost", on: "") + } + if can_abandon { + action_button(action: abandon, csrf: csrf.clone(), label: text(lang, A::Abandon), class: "button danger", on: "") + } +
  • + }) +} diff --git a/crates/im-web/src/pages/admin/message.rs b/crates/im-web/src/pages/admin/message.rs new file mode 100644 index 0000000..a661760 --- /dev/null +++ b/crates/im-web/src/pages/admin/message.rs @@ -0,0 +1,150 @@ +//! `/admin/message`: a message from the administrator to every enabled account. +//! +//! The message is queued as one mail per account, in that account's language, through the same outbox as +//! every other mail. The subject is one line of at most 150 characters; the body is at most 10 000 +//! characters, and blank lines separate its paragraphs. Each send counts against a small rate limit, so a +//! form that is submitted again and again cannot queue thousands of mails. + +use std::time::Instant; + +use im_core::model::AuditAction; +use serde::Deserialize; +use serde_json::json; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::SeeOther; +use topcoat::router::{page, route}; +use topcoat::view::{View, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{require_admin, require_admin_csrf}; +use crate::i18n::Lang; +use crate::i18n::admin::{A, text}; +use crate::mail::{self, Mail, Recipient}; +use crate::pages::admin::{ + FlashQuery, Tab, changed, done, error_text, flash_messages, frame_info, notice_text, refused, + tabs, +}; +use crate::state::AppState; +use crate::views::{ViewerInfo, field, page_lang, shell}; + +/// The longest subject, in characters. +const SUBJECT_MAX: usize = 150; + +/// The longest body, in characters. +const BODY_MAX: usize = 10_000; + +/// Sends that the limit allows in one window of the throttle. +const SENDS_PER_WINDOW: usize = 5; + +/// The throttle key of the message form. +const THROTTLE_KEY: &str = "admin-message"; + +/// The message form. +#[derive(Deserialize, Default)] +struct MessageForm { + #[serde(default)] + csrf: String, + #[serde(default)] + subject: String, + #[serde(default)] + body: String, +} + +/// `GET /admin/message`. +#[page("/admin/message")] +async fn message_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_admin(cx).await?; + let (lang, info) = frame_info(cx, &viewer); + Ok(message_view( + cx, + lang, + info, + viewer.session.csrf_token.clone(), + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), + )) +} + +/// `POST /admin/message`: queues the message for every enabled account. +#[route(POST "/admin/message")] +async fn send_message(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let subject = form.subject.trim(); + let body = form.body.replace("\r\n", "\n"); + let body = body.trim(); + if subject.is_empty() || body.is_empty() { + return Ok(refused("/admin/message", "message-empty")); + } + if subject.chars().count() > SUBJECT_MAX || subject.contains(['\r', '\n']) { + return Ok(refused("/admin/message", "message-subject")); + } + if body.chars().count() > BODY_MAX { + return Ok(refused("/admin/message", "message-body")); + } + let now = Instant::now(); + if state + .throttle + .check(THROTTLE_KEY, SENDS_PER_WINDOW, now) + .is_some() + { + return Ok(refused("/admin/message", "rate-limited")); + } + let request = page_lang(cx, Some(&viewer)); + let users = state.store.list_users(None, None, u32::MAX).await?; + let mut recipients = 0_usize; + for user in users.iter().filter(|user| user.disabled_at.is_none()) { + let Ok(to) = Recipient::new(Some(&user.name), &user.email) else { + tracing::error!(user = %user.id, "message not queued: stored address is not valid"); + continue; + }; + let lang = mail::lang_for(user, request); + let mail = Mail::Notice { subject, body }; + mail::queue(&state.store, &state.key, &to, lang, &mail).await?; + recipients += 1; + } + state.throttle.record_failure(THROTTLE_KEY, now); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::MessageSent, + None, + json!({ "recipients": recipients }), + ) + .await; + changed(&state.live); + Ok(done("/admin/message", "message-sent")) +} + +/// The message page: the subject and body fields, and the send button. +fn message_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + success: Option, + problem: Option, +) -> impl View { + view! { cx => + shell(title: text(lang, A::MessageTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Message) +
    +

    (text(lang, A::MessageTitle))

    +

    (text(lang, A::MessageIntro))

    + flash_messages(success: success, problem: problem) +
    + + field(label: text(lang, A::MessageSubject), name: "subject", kind: "text", autocomplete: "off", value: String::new()) + + +
    +
    + ) + } +} diff --git a/crates/im-web/src/pages/admin/mod.rs b/crates/im-web/src/pages/admin/mod.rs new file mode 100644 index 0000000..ffacd96 --- /dev/null +++ b/crates/im-web/src/pages/admin/mod.rs @@ -0,0 +1,226 @@ +//! The administrator area: users, invitations, services and clients, mail, message, policy settings, signing +//! keys, the audit log and health. +//! +//! Every page and every form here calls [`require_admin`] (or [`require_admin_csrf`] for a form). A member, or +//! anyone signed out, gets the styled 404 before anything else happens, so the area does not reveal itself. +//! A form also checks its CSRF token before any side effect, and answers 403 when the token is wrong. +//! +//! Writes redirect (Post/Redirect/Get) with a short code in the query string: `?notice=` for success, +//! `?error=` for a refusal. The codes map to translated text in [`notice_text`] and [`error_text`]. A +//! write that changes what an admin page shows calls [`changed`], which wakes the page's live stream +//! (`/admin/events`). A write that changes what a person sees of their own account also bumps that account's +//! topic, so their open pages refresh. + +pub mod audit; +pub mod clients; +pub mod health; +pub mod invites; +pub mod keys; +pub mod mail; +pub mod message; +pub mod settings; +pub mod users; + +#[cfg(test)] +mod tests; + +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::{SeeOther, see_other}; +use topcoat::router::response::Response; +use topcoat::router::route; +use topcoat::view::{View, component, view}; + +use crate::auth::require_admin; +use crate::i18n::Lang; +use crate::i18n::account::{Txt, text as account_text}; +use crate::i18n::admin::{A, text}; +use crate::live::{LiveHub, Topic, stream_changes}; +use crate::state::AppState; +use crate::views::{ViewerInfo, alert, notice, page_lang}; + +/// Rows per page of the long lists (users, mail, audit log). +pub const PAGE_SIZE: u32 = 50; + +/// The query of every admin list and of the redirects after a write. +#[derive(Deserialize, Default)] +pub struct FlashQuery { + /// A success code, see [`notice_text`]. + #[serde(default)] + pub notice: String, + /// A refusal code, see [`error_text`]. + #[serde(default)] + pub error: String, +} + +/// The tabs of the administrator area. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Tab { + Users, + Invites, + Services, + Mail, + Message, + Settings, + Keys, + Audit, + Health, +} + +/// The tab bar, with the current tab marked. +#[component] +pub async fn tabs(lang: Lang, current: Tab) -> Result { + Ok(view! { + + }) +} + +/// The CSS class of one tab: the current one is marked for the screen reader and the style. +fn tab_class(current: Tab, tab: Tab) -> &'static str { + if current == tab { "tab current" } else { "tab" } +} + +/// Notifies the admin pages that something they show has changed. Call it after the write commits. +pub fn changed(live: &LiveHub) { + live.bump(&Topic::Admin); +} + +/// The text of a success code, or `None` for an unknown code (which is then ignored). +pub fn notice_text(lang: Lang, code: &str) -> Option<&'static str> { + let key = match code { + "disabled" => A::NoticeDisabled, + "enabled" => A::NoticeEnabled, + "admin-granted" => A::NoticeAdminGranted, + "admin-removed" => A::NoticeAdminRemoved, + "2fa-reset" => A::NoticeTwoFactorReset, + "sessions-revoked" => A::NoticeSessionsRevoked, + "deleted" => A::NoticeDeleted, + "invite-revoked" => A::NoticeInviteRevoked, + "invite-resent" => A::NoticeInviteResent, + "invite-sent" => A::InviteQueued, + "client-saved" => A::ClientSaved, + "secret-rotated" => A::NoticeSecretRotated, + "client-disabled" => A::NoticeClientDisabled, + "mail-retried" => A::NoticeMailRetried, + "mail-abandoned" => A::NoticeMailAbandoned, + "test-queued" => A::NoticeTestQueued, + "settings-saved" => A::NoticeSettingsSaved, + "key-rotated" => A::NoticeKeyRotated, + "key-retired" => A::NoticeKeyRetired, + "file-value" => A::NoticeFileValue, + "message-sent" => A::NoticeMessageSent, + _ => return None, + }; + Some(text(lang, key)) +} + +/// The text of a refusal code, or `None` for an unknown code. +pub fn error_text(lang: Lang, code: &str) -> Option<&'static str> { + let key = match code { + "last-admin" => A::ErrLastAdmin, + "self-disable" => A::ErrSelfDisable, + "self-admin" => A::ErrSelfAdmin, + "self-delete" => A::ErrSelfDelete, + "self" => A::NoOwnAccountHere, + "confirm-email" => A::ErrConfirmEmail, + "mail-retry" => A::ErrMailNotRetryable, + "mail-abandon" => A::ErrMailNotAbandonable, + "message-empty" => A::ErrMessageEmpty, + "message-subject" => A::ErrMessageSubjectLong, + "message-body" => A::ErrMessageBodyLong, + "message-email" => A::ErrMessageEmailInvalid, + "rate-limited" => A::ErrMessageRateLimited, + "key-current" => A::ErrKeyNotRetirable, + "invite-gone" => A::ErrInviteGone, + "no-client" => A::ErrNoSuchClient, + "settings" => A::ErrSettingsInvalid, + "invite-taken" => A::ErrInviteTaken, + "email" => A::ErrInviteAddress, + "client-name" => A::ErrClientName, + "client-uri" => A::ErrUri, + "family-key" => A::ErrFamilyKey, + "family-taken" => A::ErrFamilyKeyTaken, + "public-url" => A::ErrPublicUrl, + "scopes" => A::ErrScopes, + _ => return None, + }; + Some(text(lang, key)) +} + +/// `path?error=`, the redirect of a refused write. +pub fn refused(path: &str, code: &str) -> SeeOther { + see_other(format!("{path}?error={code}")) +} + +/// `path?notice=`, the redirect of a successful write. +pub fn done(path: &str, code: &str) -> SeeOther { + see_other(format!("{path}?notice={code}")) +} + +/// The viewer's info and language for an admin page, after the admin check. +pub fn frame_info(cx: &Cx, viewer: &crate::auth::Viewer) -> (Lang, ViewerInfo) { + (page_lang(cx, Some(viewer)), ViewerInfo::of(viewer)) +} + +/// `GET /admin`: the first tab. Non-administrators get 404. +#[route(GET "/admin")] +async fn admin_root(cx: &Cx) -> Result { + require_admin(cx).await?; + Ok(see_other("/admin/users")) +} + +/// `GET /admin/events`: the live stream of the admin pages. It sends one `changed` event for each admin +/// write, and the page fetches itself again. Non-administrators get 404. +#[route(GET "/admin/events")] +async fn admin_events(cx: &Cx) -> Result { + require_admin(cx).await?; + let state = app_context::(cx); + let live = state.live.clone(); + stream_changes(cx, &state.live, &[Topic::Admin], move || { + let live = live.clone(); + async move { Ok(live.generation(&Topic::Admin).to_string()) } + }) + .await +} + +/// A form with one button, and the CSRF token. `on` is sent as a hidden field; it is empty for most actions. +#[component] +pub async fn action_button( + action: String, + csrf: String, + label: &'static str, + class: &'static str, + on: &'static str, +) -> Result { + Ok(view! { +
    + + + +
    + }) +} + +/// The success notice and the alert of an admin page, drawn above its content. +#[component] +pub async fn flash_messages(success: Option, problem: Option) -> Result { + Ok(view! { + if let Some(message) = success { + notice(message: message) + } + if let Some(message) = problem { + alert(message: message) + } + }) +} diff --git a/crates/im-web/src/pages/admin/settings.rs b/crates/im-web/src/pages/admin/settings.rs new file mode 100644 index 0000000..73b420b --- /dev/null +++ b/crates/im-web/src/pages/admin/settings.rs @@ -0,0 +1,348 @@ +//! `/admin/settings`: the policy values that an administrator can change without a restart. +//! +//! Each value comes from one of three places, and the page shows which: a value saved here (`UI`), the +//! configuration file (`file`), or the built-in default. A saved value is a `policy.` setting; it wins +//! over the file. Reset removes the saved value, so the file value applies again. Every value is checked +//! with the same rules as the file before anything is written, so a bad form changes nothing. +//! +//! The file-only settings (base address, listen address, database, data directory, trusted proxies) are shown +//! read-only: they are used when the server starts, so changing them here would do nothing until a restart. + +use im_core::config::{POLICY_KEYS, PolicyConfig}; +use im_core::model::AuditAction; +use serde::Deserialize; +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::{page, route}; +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::i18n::Lang; +use crate::i18n::admin::{A, text}; +use crate::pages::admin::{ + FlashQuery, Tab, changed, done, error_text, flash_messages, frame_info, notice_text, refused, + tabs, +}; +use crate::state::AppState; +use crate::views::{ViewerInfo, shell}; + +/// The form of the settings: one text field per policy key, and the CSRF token. +#[derive(Deserialize, Default)] +struct SettingsForm { + #[serde(default)] + csrf: String, + #[serde(default)] + require_2fa_for_admins: String, + #[serde(default)] + max_sessions: String, + #[serde(default)] + session_max_days: String, + #[serde(default)] + invite_days: String, + #[serde(default)] + reset_minutes: String, + #[serde(default)] + email_change_hours: String, +} + +impl SettingsForm { + /// Each key with the value typed for it, in the order of `POLICY_KEYS`. + fn values(&self) -> [(&'static str, &str); 6] { + [ + ("require_2fa_for_admins", &self.require_2fa_for_admins), + ("max_sessions", &self.max_sessions), + ("session_max_days", &self.session_max_days), + ("invite_days", &self.invite_days), + ("reset_minutes", &self.reset_minutes), + ("email_change_hours", &self.email_change_hours), + ] + } +} + +/// The form of a reset: the key to reset, and the CSRF token. +#[derive(Deserialize, Default)] +struct ResetForm { + #[serde(default)] + csrf: String, + #[serde(default)] + key: String, +} + +/// The value of one policy key as text, the way the form shows and accepts it. +fn value_of(policy: &PolicyConfig, key: &str) -> String { + match key { + "require_2fa_for_admins" => policy.require_2fa_for_admins.to_string(), + "max_sessions" => policy.max_sessions.to_string(), + "session_max_days" => policy.session_max_days.to_string(), + "invite_days" => policy.invite_days.to_string(), + "reset_minutes" => policy.reset_minutes.to_string(), + "email_change_hours" => policy.email_change_hours.to_string(), + _ => String::new(), + } +} + +/// The labels and hints of a policy key. +fn labels(key: &str) -> (A, A) { + match key { + "require_2fa_for_admins" => (A::SettingLabelRequire2fa, A::SettingHintRequire2fa), + "max_sessions" => (A::SettingLabelMaxSessions, A::SettingHintMaxSessions), + "session_max_days" => (A::SettingLabelSessionDays, A::SettingHintSessionDays), + "invite_days" => (A::SettingLabelInviteDays, A::SettingHintInviteDays), + "reset_minutes" => (A::SettingLabelResetMinutes, A::SettingHintResetMinutes), + _ => (A::SettingLabelEmailHours, A::SettingHintEmailHours), + } +} + +/// One row of the settings table: the key, its value now, and where the value comes from. +struct SettingRow { + key: &'static str, + value: String, + source: Source, +} + +/// Where a policy value comes from. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Source { + Ui, + File, + Default, +} + +/// `GET /admin/settings`. +#[page("/admin/settings")] +async fn settings_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let policy = state.policy(); + let saved: Vec = state + .store + .settings_with_prefix("policy.") + .await? + .into_iter() + .map(|(key, _)| key.trim_start_matches("policy.").to_owned()) + .collect(); + let rows: Vec = POLICY_KEYS + .iter() + .map(|key| SettingRow { + key, + value: value_of(&policy, key), + source: if saved.iter().any(|name| name == key) { + Source::Ui + } else if state.config.explicit_policy.iter().any(|name| name == key) { + Source::File + } else { + Source::Default + }, + }) + .collect(); + let file = FileValues { + base_url: state.config.base_url.clone(), + listen: state.config.listen.to_string(), + database: state.config.database.display().to_string(), + data_dir: state.config.data_dir.display().to_string(), + trusted_proxies: state + .config + .trusted_proxies + .iter() + .map(ToString::to_string) + .collect::>() + .join(", "), + }; + Ok(settings_view( + cx, + lang, + info, + viewer.session.csrf_token.clone(), + rows, + file, + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), + )) +} + +/// `POST /admin/settings`: saves the values that changed. Every value is checked first; if one is wrong, +/// nothing is saved. +#[route(POST "/admin/settings")] +async fn save_settings(cx: &Cx, Form(form): Form) -> 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; + } + 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() { + 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), + AuditAction::SettingsChanged, + None, + json!({ "keys": names }), + ) + .await; + changed(&state.live); + Ok(done("/admin/settings", "settings-saved")) +} + +/// `POST /admin/settings/reset`: removes the saved value of one key, so the file value (or the default) +/// applies again. +#[route(POST "/admin/settings/reset")] +async fn reset_setting(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_admin_csrf(cx, &form.csrf).await?; + let Some(key) = POLICY_KEYS.iter().find(|key| **key == form.key) else { + 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); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::SettingsChanged, + None, + json!({ "reset": key }), + ) + .await; + changed(&state.live); + Ok(done("/admin/settings", "file-value")) +} + +/// The file-only settings as text. +struct FileValues { + base_url: String, + listen: String, + database: String, + data_dir: String, + trusted_proxies: String, +} + +/// The text of a source. +fn source_text(lang: Lang, source: Source) -> &'static str { + match source { + Source::Ui => text(lang, A::SourceUi), + Source::File => text(lang, A::SourceFile), + Source::Default => text(lang, A::SourceDefault), + } +} + +/// The settings page: the editable table, the reset buttons, and the file-only values. +#[allow(clippy::too_many_arguments)] +fn settings_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + rows: Vec, + file: FileValues, + success: Option, + problem: Option, +) -> impl View { + let resets: Vec<(&'static str, &'static str)> = rows + .iter() + .filter(|row| row.source == Source::Ui) + .map(|row| (row.key, text(lang, labels(row.key).0))) + .collect(); + view! { cx => + shell(title: text(lang, A::SettingsTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Settings) +
    +

    (text(lang, A::SettingsTitle))

    +

    (text(lang, A::SettingsIntro))

    + flash_messages(success: success, problem: problem) +
    + + + + + + + + + for row in rows { + setting_row(lang: lang, row: row) + } + +
    (text(lang, A::SettingName))(text(lang, A::SettingValue))(text(lang, A::SettingSource))
    + +
    + if !resets.is_empty() { +

    (text(lang, A::UseFileValue))

    + for (key, name) in resets { + reset_form(lang: lang, csrf: csrf.clone(), key: key, name: name) + } + } +

    (text(lang, A::FileOnlyTitle))

    +

    (text(lang, A::FileOnlyIntro))

    +
    +
    (text(lang, A::FileBaseUrl))
    (file.base_url.clone())
    +
    (text(lang, A::FileListen))
    (file.listen.clone())
    +
    (text(lang, A::FileDatabase))
    (file.database.clone())
    +
    (text(lang, A::FileDataDir))
    (file.data_dir.clone())
    +
    (text(lang, A::FileTrustedProxies))
    (file.trusted_proxies.clone())
    +
    +
    + ) + } +} + +/// One policy key: its label, its input with the value now, its hint, and its source. +#[component] +async fn setting_row(lang: Lang, row: SettingRow) -> Result { + let (label, hint) = labels(row.key); + let source = source_text(lang, row.source); + Ok(view! { + + + +
    (text(lang, hint))
    + + + (source) + + }) +} + +/// A form that removes the saved value of one key. It sits outside the settings form, because forms do +/// not nest. +#[component] +async fn reset_form( + lang: Lang, + csrf: String, + key: &'static str, + name: &'static str, +) -> Result { + Ok(view! { +
    + + + (name) + +
    + }) +} diff --git a/crates/im-web/src/pages/admin/tests.rs b/crates/im-web/src/pages/admin/tests.rs new file mode 100644 index 0000000..c1962b1 --- /dev/null +++ b/crates/im-web/src/pages/admin/tests.rs @@ -0,0 +1,211 @@ +//! Router tests of the administrator area: a member gets the 404, a form without the CSRF token is refused +//! before anything changes, an administrator cannot disable themselves, and a hostile name is escaped on +//! the users page. + +use std::time::Duration; + +use http::header::{CONTENT_TYPE, COOKIE, LOCATION}; +use im_core::password::hash_password; +use im_core::store::sessions::{NewSession, SESSION_IDLE}; +use im_core::token::{generate_token, hash_token}; +use topcoat::router::{Body, to_bytes}; + +use crate::boot::{router, test_state}; +use crate::state::AppState; + +/// The cookie name the browser sends: the `__Host-` prefix is added by the jar. +const COOKIE_NAME: &str = "__Host-im_session"; + +/// A status, the `Location` header if any, and the body of a response. +struct Reply { + status: u16, + location: Option, + body: String, +} + +/// Sends a request through the router and collects the reply. +async fn send(state: AppState, request: http::request::Builder, body: Body) -> Reply { + let request = request.body(body).expect("request"); + let response = router(state).handle(request).await; + let status = response.status().as_u16(); + let location = response + .headers() + .get(LOCATION) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let bytes = to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("body"); + Reply { + status, + location, + body: String::from_utf8_lossy(&bytes).into_owned(), + } +} + +/// A GET with the session cookie. +async fn get(state: AppState, path: &str, cookie: &str) -> Reply { + let request = http::Request::get(path).header(COOKIE, format!("{COOKIE_NAME}={cookie}")); + send(state, request, Body::empty()).await +} + +/// A form POST with the session cookie. +async fn post(state: AppState, path: &str, cookie: &str, form: &str) -> Reply { + let request = http::Request::post(path) + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .header(COOKIE, format!("{COOKIE_NAME}={cookie}")); + send(state, request, Body::from(form.to_owned())).await +} + +/// Creates a session for a user with a known CSRF token. Returns the cookie value and the CSRF token. +async fn session_for(state: &AppState, user_id: &str) -> (String, String) { + let token = generate_token(); + let csrf = generate_token(); + state + .store + .create_session( + &NewSession { + user_id, + token_hash: &hash_token(&token), + csrf_token: &csrf, + amr: "pwd", + ip: None, + user_agent: None, + idle: SESSION_IDLE, + max_age: Duration::from_secs(3600), + }, + 10, + ) + .await + .expect("session"); + (token, csrf) +} + +/// A state where administrators need no two-factor sign-in, so a test session reaches the admin pages. +async fn state_without_admin_two_factor() -> (tempfile::TempDir, AppState) { + let (dir, state) = test_state().await; + let mut policy = state.policy(); + policy.require_2fa_for_admins = false; + state.set_policy(policy); + (dir, state) +} + +#[tokio::test] +async fn a_member_gets_not_found_on_the_admin_users_page() { + let (_dir, state) = state_without_admin_two_factor().await; + let hash = hash_password("the current password").expect("hash"); + let member = state + .store + .create_user("member@example.com", "Mem", &hash, false) + .await + .expect("member"); + let (cookie, _) = session_for(&state, &member.id).await; + let reply = get(state, "/admin/users", &cookie).await; + assert_eq!(reply.status, 404); +} + +#[tokio::test] +async fn an_admin_form_without_the_csrf_token_is_forbidden_and_changes_nothing() { + let (_dir, state) = state_without_admin_two_factor().await; + let hash = hash_password("the current password").expect("hash"); + let admin = state + .store + .create_user("admin@example.com", "Ada", &hash, true) + .await + .expect("admin"); + let other = state + .store + .create_user("other@example.com", "Oto", &hash, false) + .await + .expect("other"); + let (cookie, _) = session_for(&state, &admin.id).await; + let reply = post( + state.clone(), + &format!("/admin/users/{}/disable", other.id), + &cookie, + "csrf=not-the-token&on=", + ) + .await; + assert_eq!(reply.status, 403); + let still = state + .store + .user_by_id(&other.id) + .await + .expect("query") + .expect("user"); + assert!(still.disabled_at.is_none()); +} + +#[tokio::test] +async fn an_administrator_cannot_disable_themselves() { + let (_dir, state) = state_without_admin_two_factor().await; + let hash = hash_password("the current password").expect("hash"); + let admin = state + .store + .create_user("admin@example.com", "Ada", &hash, true) + .await + .expect("admin"); + let other = state + .store + .create_user("other@example.com", "Oto", &hash, true) + .await + .expect("other"); + let (cookie, csrf) = session_for(&state, &admin.id).await; + let reply = post( + state.clone(), + &format!("/admin/users/{}/disable", admin.id), + &cookie, + &format!("csrf={csrf}&on="), + ) + .await; + assert_eq!(reply.status, 303); + assert!( + reply + .location + .as_deref() + .is_some_and(|location| location.contains("error=self-disable")), + "refused with the self-disable code, got {:?}", + reply.location + ); + let still = state + .store + .user_by_id(&admin.id) + .await + .expect("query") + .expect("user"); + assert!(still.disabled_at.is_none()); + assert!( + state + .store + .user_by_id(&other.id) + .await + .expect("query") + .is_some() + ); +} + +#[tokio::test] +async fn a_hostile_user_name_is_escaped_on_the_admin_users_page() { + let (_dir, state) = state_without_admin_two_factor().await; + let hash = hash_password("the current password").expect("hash"); + let admin = state + .store + .create_user("admin@example.com", "Ada", &hash, true) + .await + .expect("admin"); + state + .store + .create_user( + "mallory@example.com", + "", + &hash, + false, + ) + .await + .expect("hostile user"); + let (cookie, _) = session_for(&state, &admin.id).await; + let reply = get(state, "/admin/users", &cookie).await; + assert_eq!(reply.status, 200); + assert!(!reply.body.contains(") -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let search: String = query.q.trim().chars().take(100).collect(); + let cursor = query + .after + .split_once('|') + .filter(|(at, id)| !at.is_empty() && !id.is_empty()); + let mut users = state + .store + .list_users( + (!search.is_empty()).then_some(search.as_str()), + cursor, + PAGE_SIZE + 1, + ) + .await?; + let more = users.len() > PAGE_SIZE as usize; + users.truncate(PAGE_SIZE as usize); + let next = more + .then(|| users.last().map(|u| format!("{}|{}", u.created_at, u.id))) + .flatten() + .map(|cursor| { + format!( + "/admin/users?q={}&after={}", + percent_encode(&search), + percent_encode(&cursor) + ) + }); + let rows: Vec = users.iter().map(|user| row_of(lang, user)).collect(); + Ok(users_view( + cx, + lang, + info, + search, + rows, + next, + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), + )) +} + +/// The list row of an account. +fn row_of(lang: Lang, user: &User) -> UserRow { + UserRow { + name: user.name.clone(), + email: user.email.clone(), + status: if user.is_disabled() { + text(lang, A::Disabled) + } else { + text(lang, A::Active) + }, + admin: user.is_admin, + created: user.created_at.clone(), + href: format!("/admin/users/{}", user.id), + } +} + +/// The account list page. +#[allow(clippy::too_many_arguments)] +fn users_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + search: String, + rows: Vec, + next: Option, + success: Option, + problem: Option, +) -> impl View { + view! { cx => + shell(title: text(lang, A::UsersTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Users) +
    +

    (text(lang, A::UsersTitle))

    +

    (text(lang, A::UsersIntro))

    + flash_messages(success: success, problem: problem) +
    + + +
    + if rows.is_empty() { +

    (text(lang, A::NoUsers))

    + } else { + + + + + + + + + + for row in rows { + user_row(lang: lang, row: row) + } + +
    (text(lang, A::Name))(text(lang, A::Email))(text(lang, A::Status))(text(lang, A::Created))(text(lang, A::Open))
    + } + if let Some(href) = next { +

    (text(lang, A::NextPage))

    + } +
    + ) + } +} + +/// One account in the list. +#[component] +async fn user_row(lang: Lang, row: UserRow) -> Result { + Ok(view! { + + (row.name.clone()) + (row.email.clone()) + + (row.status) + if row.admin { + (text(lang, A::Administrator)) + } + + (row.created.clone()) + (text(lang, A::Open)) + + }) +} + +/// One account's page: its facts and the actions on it. +#[page("/admin/users/{id}")] +async fn user_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_admin(cx).await?; + let state = app_context::(cx); + let (lang, info) = frame_info(cx, &viewer); + let Some(id) = path_param(cx, "id") else { + return Err(not_found().into()); + }; + let Some(user) = state.store.user_by_id(&id).await? else { + return Err(not_found().into()); + }; + let sessions = state.store.list_sessions(&user.id).await?.len(); + let is_self = user.id == viewer.user.id; + Ok(user_view( + cx, + lang, + info, + viewer.session.csrf_token.clone(), + user, + sessions, + is_self, + notice_text(lang, &query.notice).map(str::to_owned), + error_text(lang, &query.error).map(str::to_owned), + )) +} + +/// The markup of one account's page. The actions are shown only for other accounts. +#[allow(clippy::too_many_arguments)] +fn user_view( + cx: &Cx, + lang: Lang, + info: ViewerInfo, + csrf: String, + user: User, + sessions: usize, + is_self: bool, + success: Option, + problem: Option, +) -> impl View { + let base = format!("/admin/users/{}", user.id); + let status = if user.is_disabled() { + text(lang, A::Disabled) + } else { + text(lang, A::Active) + }; + let two_factor = if user.totp_enabled() { + text(lang, A::TwoFactorOn) + } else { + text(lang, A::TwoFactorOff) + }; + let admin_flag = if user.is_admin { + text(lang, A::RemoveAdmin) + } else { + text(lang, A::MakeAdmin) + }; + let admin_on = if user.is_admin { "0" } else { "1" }; + let admin_text = if user.is_admin { + text(lang, A::Yes) + } else { + text(lang, A::No) + }; + view! { cx => + shell(title: text(lang, A::UserTitle), lang: lang, viewer: Some(info), + tabs(lang: lang, current: Tab::Users) +
    +

    (text(lang, A::NavUsers))

    +

    (user.name.clone())

    + flash_messages(success: success, problem: problem) +
    +
    (text(lang, A::Email))
    (user.email.clone())
    +
    (text(lang, A::Status))
    (status)
    +
    (text(lang, A::Administrator))
    (admin_text)
    +
    (text(lang, A::Created))
    (user.created_at.clone())
    +
    (text(lang, A::SessionsLabel))
    (sessions.to_string())
    +
    (text(lang, A::TwoFactor))
    (two_factor)
    +
    + if is_self { +

    (text(lang, A::YouLabel))". "(text(lang, A::NoOwnAccountHere))

    + } else { +
    + if user.is_disabled() { + action_button(action: format!("{base}/enable"), csrf: csrf.clone(), label: text(lang, A::EnableAccount), class: "button primary", on: "") + } else { + action_button(action: format!("{base}/disable"), csrf: csrf.clone(), label: text(lang, A::DisableAccount), class: "button danger", on: "") + } + action_button(action: format!("{base}/admin"), csrf: csrf.clone(), label: admin_flag, class: "button ghost", on: admin_on) + action_button(action: format!("{base}/reset-2fa"), csrf: csrf.clone(), label: text(lang, A::ResetTwoFactor), class: "button ghost", on: "") + action_button(action: format!("{base}/revoke-sessions"), csrf: csrf.clone(), label: text(lang, A::RevokeSessions), class: "button ghost", on: "") +
    + +

    (text(lang, A::DeleteWarning))

    + + +
    +
    + } +
    + ) + } +} + +/// Checks the CSRF token and loads the account named by the path. A member gets 404 before the token is +/// read; a wrong token gets 403; a missing account gets 404. +async fn target(cx: &Cx, csrf: &str) -> Result<(Viewer, User)> { + let viewer = require_admin_csrf(cx, csrf).await?; + let state = app_context::(cx); + let Some(id) = path_param(cx, "id") else { + return Err(not_found().into()); + }; + let Some(user) = state.store.user_by_id(&id).await? else { + return Err(not_found().into()); + }; + Ok((viewer, user)) +} + +/// `POST /admin/users/{id}/disable`. Ends the account's sessions and queues the back-channel logouts. +#[route(POST "/admin/users/{id}/disable")] +async fn disable(cx: &Cx, Form(form): Form) -> Result { + let (viewer, user) = target(cx, &form.csrf).await?; + let base = format!("/admin/users/{}", user.id); + if user.id == viewer.user.id { + return Ok(refused(&base, "self-disable")); + } + if user.is_disabled() { + return Ok(done(&base, "disabled")); + } + let state = app_context::(cx); + if state.store.disable_user(&user.id).await? { + state.live.bump(&Topic::Account(user.id.clone())); + changed(&state.live); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::UserDisabled, + Some(("user", &user.id)), + json!({}), + ) + .await; + return Ok(done(&base, "disabled")); + } + // The store refused: the account is the last enabled administrator. + Ok(refused(&base, "last-admin")) +} + +/// `POST /admin/users/{id}/enable`. +#[route(POST "/admin/users/{id}/enable")] +async fn enable(cx: &Cx, Form(form): Form) -> Result { + let (viewer, user) = target(cx, &form.csrf).await?; + let base = format!("/admin/users/{}", user.id); + let state = app_context::(cx); + if state.store.enable_user(&user.id).await? { + changed(&state.live); + state.live.bump(&Topic::Account(user.id.clone())); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::UserEnabled, + Some(("user", &user.id)), + json!({}), + ) + .await; + } + Ok(done(&base, "enabled")) +} + +/// `POST /admin/users/{id}/admin`. `on=1` makes the account an administrator, `on=0` removes the flag. +#[route(POST "/admin/users/{id}/admin")] +async fn set_admin_flag(cx: &Cx, Form(form): Form) -> Result { + let (viewer, user) = target(cx, &form.csrf).await?; + let base = format!("/admin/users/{}", user.id); + if user.id == viewer.user.id { + return Ok(refused(&base, "self-admin")); + } + let make = form.on == "1"; + let state = app_context::(cx); + let outcome = state.store.set_admin(&user.id, make).await?; + let code = if make { + "admin-granted" + } else { + "admin-removed" + }; + match outcome { + AdminChange::LastAdmin => Ok(refused(&base, "last-admin")), + AdminChange::Unchanged => Ok(done(&base, code)), + AdminChange::Changed => { + state.live.bump(&Topic::Account(user.id.clone())); + changed(&state.live); + let action = if make { + AuditAction::AdminGranted + } else { + AuditAction::AdminRemoved + }; + record( + cx, + Actor::User(&viewer.user.id), + action, + Some(("user", &user.id)), + json!({}), + ) + .await; + Ok(done(&base, code)) + } + } +} + +/// `POST /admin/users/{id}/reset-2fa`. Clears the second factor and the recovery codes, and mails the +/// account's own address so the person knows. +#[route(POST "/admin/users/{id}/reset-2fa")] +async fn reset_two_factor(cx: &Cx, Form(form): Form) -> Result { + let (viewer, user) = target(cx, &form.csrf).await?; + let base = format!("/admin/users/{}", user.id); + if user.id == viewer.user.id { + return Ok(refused(&base, "self")); + } + let state = app_context::(cx); + state.store.disable_totp(&user.id).await?; + state.live.bump(&Topic::Account(user.id.clone())); + changed(&state.live); + let request_lang = page_lang(cx, Some(&viewer)); + mail::notify( + &state.store, + &state.key, + &user, + request_lang, + Notice::TwoFactorOff, + ) + .await; + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::AdminTwoFactorReset, + Some(("user", &user.id)), + json!({}), + ) + .await; + Ok(done(&base, "2fa-reset")) +} + +/// `POST /admin/users/{id}/revoke-sessions`. Ends every session of the account, with their logouts. +#[route(POST "/admin/users/{id}/revoke-sessions")] +async fn revoke_sessions(cx: &Cx, Form(form): Form) -> Result { + let (viewer, user) = target(cx, &form.csrf).await?; + let base = format!("/admin/users/{}", user.id); + if user.id == viewer.user.id { + return Ok(refused(&base, "self")); + } + let state = app_context::(cx); + let ended = state + .store + .end_all_sessions(&user.id, EndReason::Revoked) + .await?; + if !ended.is_empty() { + state.live.bump(&Topic::Account(user.id.clone())); + changed(&state.live); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::AdminSessionsRevoked, + Some(("user", &user.id)), + json!({ "count": ended.len() }), + ) + .await; + } + Ok(done(&base, "sessions-revoked")) +} + +/// `POST /admin/users/{id}/delete`. The address must be typed again. Deletes the account, its sessions, +/// links and recovery codes, and then its photo file. The last enabled administrator cannot be deleted. +#[route(POST "/admin/users/{id}/delete")] +async fn delete_account(cx: &Cx, Form(form): Form) -> Result { + let (viewer, user) = target(cx, &form.csrf).await?; + let base = format!("/admin/users/{}", user.id); + if user.id == viewer.user.id { + return Ok(refused(&base, "self-delete")); + } + if normalize_email(&form.confirm) != user.email { + return Ok(refused(&base, "confirm-email")); + } + let state = app_context::(cx); + match state.store.delete_user(&user.id).await { + Ok(true) => { + if let Err(error) = im_core::photo::remove_photo(&state.config.data_dir, &user.id) { + tracing::error!(error = %error, "photo of a deleted account not removed"); + } + state.live.bump(&Topic::Account(user.id.clone())); + changed(&state.live); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::UserDeleted, + Some(("user", &user.id)), + json!({}), + ) + .await; + Ok(done("/admin/users", "deleted")) + } + Ok(false) => Ok(done("/admin/users", "deleted")), + Err(CoreError::Conflict(_)) => Ok(refused(&base, "last-admin")), + Err(error) => Err(error.into()), + } +} diff --git a/crates/im-web/src/pages/email.rs b/crates/im-web/src/pages/email.rs index ba818fc..e0e76e0 100644 --- a/crates/im-web/src/pages/email.rs +++ b/crates/im-web/src/pages/email.rs @@ -137,7 +137,7 @@ async fn email_request_submit(cx: &Cx, Form(form): Form) -> Re )); } - let hours = state.config.policy.email_change_hours; + let hours = state.policy().email_change_hours; let old_token = generate_token(); let new_token = generate_token(); let expires = stamp_after(Duration::from_secs(u64::from(hours) * 60 * 60)); diff --git a/crates/im-web/src/pages/invite.rs b/crates/im-web/src/pages/invite.rs index afb712f..7a8ad86 100644 --- a/crates/im-web/src/pages/invite.rs +++ b/crates/im-web/src/pages/invite.rs @@ -4,14 +4,13 @@ //! gets the styled not-found page, and so does an acceptance that the store refuses (the link was spent //! meanwhile, or the address got an account). The acceptance itself is one conditional update in the //! store, so parallel submissions create one account. `/admin/invites` is the minimal admin form that -//! creates invitations; it answers 404 to anyone who is not an administrator. +//! is in `pages/admin/invites.rs`. use im_core::model::{AuditAction, amr}; -use im_core::names::{parse_display_name, parse_email}; +use im_core::names::parse_display_name; use im_core::password::{check_policy, hash_password_async}; -use im_core::store::invites::{AcceptOutcome, invite_lifetime}; -use im_core::time::stamp_after; -use im_core::token::{generate_token, hash_token}; +use im_core::store::invites::AcceptOutcome; +use im_core::token::hash_token; use serde::Deserialize; use serde_json::json; use topcoat::Result; @@ -22,17 +21,13 @@ use topcoat::router::page; use topcoat::view::{View, view}; use crate::audit::{Actor, record}; -use crate::auth::{ - after_sign_in, check_csrf, check_pre_csrf, clear_pre_csrf, pre_csrf_token, require_admin, - start_session, -}; +use crate::auth::{after_sign_in, check_pre_csrf, clear_pre_csrf, pre_csrf_token, start_session}; use crate::i18n::Lang; use crate::i18n::account::{Txt, policy_problem, text}; use crate::i18n::flows::{Flow, text as flow_text}; -use crate::mail::{self, Mail, Recipient}; use crate::pages::path_param; use crate::state::AppState; -use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; +use crate::views::{alert, field, page_lang, shell}; /// The invitation form. #[derive(Deserialize, Default)] @@ -47,24 +42,6 @@ struct InviteForm { password_again: String, } -/// The administrator's invitation form. The checkbox sends `on` when ticked. -#[derive(Deserialize, Default)] -struct AdminInviteForm { - #[serde(default)] - csrf: String, - #[serde(default)] - email: String, - #[serde(default)] - admin: String, -} - -/// The query of `GET /admin/invites`. -#[derive(Deserialize, Default)] -struct NoticeQuery { - #[serde(default)] - notice: String, -} - /// `GET /invite/{token}`. #[page("/invite/{token}")] async fn invite_form(cx: &Cx) -> Result { @@ -140,98 +117,6 @@ async fn invite_submit(cx: &Cx, Form(form): Form) -> Result) -> Result { - let viewer = require_admin(cx).await?; - let lang = page_lang(cx, Some(&viewer)); - Ok(admin_invites_view( - cx, - lang, - ViewerInfo::of(&viewer), - viewer.session.csrf_token.clone(), - query.notice == "sent", - None, - )) -} - -/// `POST /admin/invites`: creates the invitation and queues its mail. -#[page(POST "/admin/invites")] -async fn admin_invites_submit(cx: &Cx, Form(form): Form) -> Result { - let viewer = require_admin(cx).await?; - if !check_csrf(&viewer.session, &form.csrf) { - return Err(forbidden().into()); - } - let state = app_context::(cx); - let lang = page_lang(cx, Some(&viewer)); - let csrf = viewer.session.csrf_token.clone(); - let info = ViewerInfo::of(&viewer); - - let email = match parse_email(&form.email) { - Ok(email) => email, - Err(_) => { - let problem = text(lang, Txt::ErrEmailInvalid).to_owned(); - return Ok(admin_invites_view( - cx, - lang, - info, - csrf, - false, - Some(problem), - )); - } - }; - let is_admin = form.admin == "on"; - let days = state.config.policy.invite_days; - let token = generate_token(); - let expires = stamp_after(invite_lifetime(days)); - match state - .store - .create_invite( - &hash_token(&token), - &email, - is_admin, - &viewer.user.id, - &expires, - ) - .await - { - Ok(()) => {} - Err(im_core::Error::Conflict(_)) => { - let problem = flow_text(lang, Flow::InviteAddressTaken).to_owned(); - return Ok(admin_invites_view( - cx, - lang, - info, - csrf, - false, - Some(problem), - )); - } - Err(error) => return Err(error.into()), - } - - let link = format!("{}/invite/{token}", state.config.base_url); - match Recipient::new(None, &email) { - Ok(to) => { - let mail = Mail::Invite { link: &link, days }; - if let Err(error) = mail::queue(&state.store, &state.key, &to, lang, &mail).await { - tracing::error!(error = %error, "invitation mail not queued"); - } - } - Err(error) => tracing::error!(error, "invitation mail not queued"), - } - record( - cx, - Actor::User(&viewer.user.id), - AuditAction::InviteCreated, - None, - json!({ "admin": is_admin }), - ) - .await; - Err(see_other("/admin/invites?notice=sent").into()) -} - /// The invitation page: the address (read only), the name and the new password. fn invite_view( cx: &Cx, @@ -266,37 +151,3 @@ fn invite_view( ) } } - -/// The administrator's invitation form, with the result of the last submission above it. -fn admin_invites_view( - cx: &Cx, - lang: Lang, - info: ViewerInfo, - csrf: String, - sent: bool, - problem: Option, -) -> impl View { - view! { cx => - shell(title: flow_text(lang, Flow::AdminInvitesTitle), lang: lang, viewer: Some(info), -
    -

    (flow_text(lang, Flow::AdminInvitesTitle))

    -

    (flow_text(lang, Flow::AdminInvitesIntro))

    - if sent { - notice(message: flow_text(lang, Flow::InviteQueued).to_owned()) - } - if let Some(problem) = problem { - alert(message: problem) - } -
    - - field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "off", value: String::new()) - - -
    -
    - ) - } -} diff --git a/crates/im-web/src/pages/mod.rs b/crates/im-web/src/pages/mod.rs index 38a2655..0de504b 100644 --- a/crates/im-web/src/pages/mod.rs +++ b/crates/im-web/src/pages/mod.rs @@ -1,5 +1,6 @@ //! The pages and the page-level layers. One file per page. +pub mod admin; pub mod email; pub mod home; pub mod invite; diff --git a/crates/im-web/src/pages/reset.rs b/crates/im-web/src/pages/reset.rs index 15480ae..d7b7be1 100644 --- a/crates/im-web/src/pages/reset.rs +++ b/crates/im-web/src/pages/reset.rs @@ -110,7 +110,7 @@ async fn forgot_submit(cx: &Cx, Form(form): Form) -> Result, + /// The sign-in policy in effect: the file values, with the settings saved in the admin UI layered on + /// top. Read it through [`AppState::policy`]; the admin settings page replaces it while the server + /// runs. + pub policy_live: Arc>, /// The database. Reads go to a pooled reader and writes to the single writer. pub store: Store, /// The instance key (`im.key`). Seals secrets at rest. @@ -28,3 +32,21 @@ pub struct AppState { /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain. pub stop: watch::Receiver, } + +impl AppState { + /// A copy of the policy in effect now. Cheap: the policy is a handful of numbers. + pub fn policy(&self) -> PolicyConfig { + self.policy_live + .read() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + /// Replaces the policy in effect. Used when an administrator saves the settings page. + pub fn set_policy(&self, policy: PolicyConfig) { + *self + .policy_live + .write() + .unwrap_or_else(PoisonError::into_inner) = policy; + } +} diff --git a/deploy/ferron.kdl b/deploy/ferron.kdl new file mode 100644 index 0000000..11044d9 --- /dev/null +++ b/deploy/ferron.kdl @@ -0,0 +1,6 @@ +// Example Ferron site for `im`. Ferron terminates TLS and forwards to the loopback listener of `im`. +// Check the directive names against the Ferron version you run; this file shows the shape, it has not been +// run against a live Ferron here. `base_url` in im.toml must be this same origin. +im.example.com { + proxy http://127.0.0.1:7650 +} diff --git a/deploy/im.service b/deploy/im.service new file mode 100644 index 0000000..b1e314a --- /dev/null +++ b/deploy/im.service @@ -0,0 +1,47 @@ +[Unit] +Description=im: the family's sign-in provider (OpenID Connect) +After=network-online.target +Wants=network-online.target +StartLimitIntervalSec=60 +StartLimitBurst=5 + +[Service] +Type=simple +User=im +Group=im +Environment=IM_CONFIG=/etc/im/im.toml +ExecStart=/usr/local/bin/im serve +WorkingDirectory=/var/lib/im +Restart=on-failure +RestartSec=2 +LimitNOFILE=65536 + +# Hardening. The service writes only to its state directory: database, data_dir (instance key, photos) and +# the backup dir. If [backup] dir is set outside /var/lib/im, add that path to ReadWritePaths. +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +ReadWritePaths=/var/lib/im +PrivateTmp=yes +PrivateDevices=yes +PrivateUsers=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +RestrictSUIDSGID=yes +RestrictRealtime=yes +RestrictNamespaces=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +LockPersonality=yes +MemoryDenyWriteExecute=yes +SystemCallArchitectures=native +SystemCallFilter=@system-service +CapabilityBoundingSet= +AmbientCapabilities= +UMask=0077 + +[Install] +WantedBy=multi-user.target