From cc5a8a02f31f3768e4105e2f5e2f3ac6ac45d762 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 10:50:58 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20admin=20pages=20(tags,=20co?= =?UTF-8?q?lumns,=20members,=20limits,=20server),=20people=20cards,=20audi?= =?UTF-8?q?t,=20family=20switcher,=20backups,=20sweeper,=20export/restore/?= =?UTF-8?q?fsck=20CLI,=20systemd=20unit,=20Ferron=20example,=20README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 14 + Cargo.toml | 1 + README.md | 176 +++++++++++ crates/iz-core/src/config.rs | 12 +- crates/iz-core/src/lib.rs | 1 + crates/iz-core/src/manifest.rs | 255 +++++++++++++++ crates/iz-core/src/store/audit.rs | 107 +++++++ crates/iz-core/src/store/board.rs | 68 +++- crates/iz-core/src/store/export.rs | 365 +++++++++++++++++++++ crates/iz-core/src/store/mod.rs | 17 + crates/iz-core/src/store/outbox.rs | 5 +- crates/iz-core/src/store/people.rs | 91 ++++++ crates/iz-core/src/store/sweep.rs | 120 +++++++ crates/iz-web/Cargo.toml | 1 + crates/iz-web/src/auth.rs | 26 +- crates/iz-web/src/backup.rs | 270 ++++++++++++++++ crates/iz-web/src/boot.rs | 9 + crates/iz-web/src/cli/export.rs | 291 +++++++++++++++++ crates/iz-web/src/cli/fsck.rs | 314 ++++++++++++++++++ crates/iz-web/src/cli/mod.rs | 175 ++++++++++ crates/iz-web/src/cli/restore.rs | 457 +++++++++++++++++++++++++++ crates/iz-web/src/family.rs | 257 +++++++++++++++ crates/iz-web/src/i18n/mod.rs | 1 + crates/iz-web/src/i18n/structure.rs | 364 +++++++++++++++++++++ crates/iz-web/src/live.rs | 4 + crates/iz-web/src/main.rs | 80 ++--- crates/iz-web/src/pages/admin.rs | 102 ++++++ crates/iz-web/src/pages/columns.rs | 278 ++++++++++++++++ crates/iz-web/src/pages/logs.rs | 14 +- crates/iz-web/src/pages/mod.rs | 3 + crates/iz-web/src/pages/people.rs | 119 +++++++ crates/iz-web/src/pages/rules.rs | 54 +++- crates/iz-web/src/pages/settings.rs | 246 +++++++++++++- crates/iz-web/src/pages/tags.rs | 323 +++++++++++++++++++ crates/iz-web/src/pages/task.rs | 9 +- crates/iz-web/src/state.rs | 3 + crates/iz-web/src/sweeper.rs | 166 ++++++++++ crates/iz-web/src/views/admin.rs | 25 ++ crates/iz-web/src/views/mod.rs | 30 +- crates/iz-web/src/views/structure.rs | 413 ++++++++++++++++++++++++ deploy/ferron.conf | 17 + deploy/iz.service | 52 +++ docs/architecture.md | 10 +- style/_components.scss | 35 ++ style/_layout.scss | 2 +- 45 files changed, 5282 insertions(+), 100 deletions(-) create mode 100644 README.md create mode 100644 crates/iz-core/src/manifest.rs create mode 100644 crates/iz-core/src/store/audit.rs create mode 100644 crates/iz-core/src/store/export.rs create mode 100644 crates/iz-core/src/store/people.rs create mode 100644 crates/iz-core/src/store/sweep.rs create mode 100644 crates/iz-web/src/backup.rs create mode 100644 crates/iz-web/src/cli/export.rs create mode 100644 crates/iz-web/src/cli/fsck.rs create mode 100644 crates/iz-web/src/cli/mod.rs create mode 100644 crates/iz-web/src/cli/restore.rs create mode 100644 crates/iz-web/src/family.rs create mode 100644 crates/iz-web/src/i18n/structure.rs create mode 100644 crates/iz-web/src/pages/columns.rs create mode 100644 crates/iz-web/src/pages/people.rs create mode 100644 crates/iz-web/src/pages/tags.rs create mode 100644 crates/iz-web/src/sweeper.rs create mode 100644 crates/iz-web/src/views/structure.rs create mode 100644 deploy/ferron.conf create mode 100644 deploy/iz.service diff --git a/Cargo.lock b/Cargo.lock index 1f1e9c4..00c3b9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -576,6 +576,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", + "clap_derive", ] [[package]] @@ -590,6 +591,18 @@ dependencies = [ "strsim", ] +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "clap_lex" version = "1.1.1" @@ -1896,6 +1909,7 @@ dependencies = [ "aws-lc-rs", "base64 0.23.1", "bytes", + "clap", "futures-util", "grass", "hex", diff --git a/Cargo.toml b/Cargo.toml index 772cdf4..61162b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ http = "1.5.0" http-body = "1.1.0" http-body-util = "0.1.5" chacha20poly1305 = "0.11.0" +clap = "4.6.7" hex = "0.4.3" ipnet = "2.12.2" lettre = { version = "0.11.23", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] } diff --git a/README.md b/README.md new file mode 100644 index 0000000..109f210 --- /dev/null +++ b/README.md @@ -0,0 +1,176 @@ +# iz + +iz is the family task board. It has columns, cards (with one level of subtasks, dependencies and +assignees), projects (tags), deadlines with meeting times and reminders, comments, attachments with +in-page viewers (images, media, PDF, spreadsheets, slides), an activity trail, and admin-defined mail +rules with a durable outbox. Sign-in goes through the family's `im` identity provider. + +Design notes are in `docs/architecture.md`. The HTTP contracts with `im` and `in` are in +`docs/contracts.md`, and the code conventions are in `docs/conventions.md`. + +## Build + +```sh +cargo build --release -p iz-web +``` + +The binary is `target/release/iz`. Nothing in the build or the runtime uses Node. Use `bun` for any +JavaScript tooling. + +## Configuration + +Copy the example and edit it: + +```sh +cp config/iz.example.toml config/iz.toml +``` + +Or pass any path with `--config `. The config path is chosen in this order: the `--config` +flag, then the `IZ_CONFIG` environment variable, then `config/iz.toml`. If the file does not exist, +iz writes the example there on first run. + +Keys: + +| Key | Meaning | +|---|---| +| `database` | SQLite database file. Its `-wal` and `-shm` files sit next to it. | +| `data_dir` | Directory for `iz.key`, the lock file, attachments and other local files. | +| `listen` | HTTP listen address. Keep it on `127.0.0.1` behind the reverse proxy. | +| `base_url` | Public URL used in links and mail. `https://` or `http://`, no trailing slash. | +| `trusted_proxies` | Peers whose `X-Forwarded-For` is trusted for client IPs. IPs or CIDR networks. | +| `[oidc]` | `issuer` (the `im` origin, `https://`, no trailing slash), `client_id`, `client_secret_file`. Remove the section to run without sign-in. | +| `[in_store]` | `enabled`. Stores attachments in the `in` Files service instead of local disk. Off by default. | +| `[backup]` | `dir` (backup sets go here), `interval_hours` (1 to 720, default 24), `keep` (1 to 365, default 14), `healthcheck_url` (optional, pinged after each good backup). Remove the section to turn scheduled backups off. | + +Unknown keys are an error at boot, so a typo stops the start instead of being ignored. + +Secrets are never in the TOML: + +- The OIDC client secret goes in the file named by `client_secret_file`. The file must be mode + `0600` or `0400`, owned by the service user. iz reads it at boot. +- The SMTP password is entered in the `/settings` page. iz seals it in the database. + +## Production layout + +The example unit and reverse proxy config assume this layout: + +- `/usr/local/bin/iz`: the binary. +- `/etc/iz/iz.toml`: the config. `data_dir = "/var/lib/iz/data"` and `database = "/var/lib/iz/data/iz.db"`. +- `/etc/iz/oidc_client_secret`: the client secret, mode `0600`, owned by `iz`. +- `/var/lib/iz`: the working directory. The data lives in `/var/lib/iz/data`. Backups can go in + `/var/lib/iz/backups`. The unit makes all of `/var/lib/iz` writable and nothing else. + +The reverse proxy example is `deploy/ferron.conf`. The unit is `deploy/iz.service`. + +## First run + +1. Create the service user and directories: + + ```sh + sudo useradd --system --home-dir /var/lib/iz --shell /usr/sbin/nologin iz + sudo install -d -m 0750 -o iz -g iz /var/lib/iz /var/lib/iz/data + sudo install -d -m 0750 -o root -g iz /etc/iz + ``` + +2. Install the binary and the config: + + ```sh + sudo install -m 0755 target/release/iz /usr/local/bin/iz + sudo install -m 0640 -o root -g iz config/iz.toml /etc/iz/iz.toml + ``` + + Edit `/etc/iz/iz.toml` so `data_dir`, `database` and `base_url` match the layout above. + +3. Register the client at `im` and write its secret file (see the next section). + +4. Install the unit by hand. Nothing enables it for you: + + ```sh + sudo install -m 0644 deploy/iz.service /etc/systemd/system/iz.service + sudo systemctl daemon-reload + sudo systemctl enable --now iz + ``` + +5. Check it answers: `curl -fsS http://127.0.0.1:7654/healthz` should print `ok `. + +On the first run iz creates `iz.key` in `data_dir` (32 random bytes, mode `0600`). Sealed secrets in the +database, including the SMTP password, cannot be read without this key. Back up `iz.key` together with +the database, and store the copy somewhere other than the server. Losing `iz.key` means re-entering the +SMTP password and the sealed values, and any backup that lacks the key cannot restore those secrets. + +## Registering the client at im + +iz is a client of `im`. Register it on the machine where `im` runs, with the `im` tools: + +```sh +im client add --name iz --family-key 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 \ + --scopes "openid profile email directory.read" +``` + +Replace `https://iz.example.com` with your `base_url`. If the flags differ, run `im client add --help`. + +- `im` prints `client_id` and `client_secret`. The secret is shown once. Save it into the file named + by `client_secret_file`, mode `0600`, owned by `iz`. +- `im` generates the `client_id` itself. Copy the printed value into `client_id` in `iz.toml`. +- The scopes must include `openid profile email` for sign-in and `directory.read` for the people + directory. +- The redirect, post-logout and back-channel URLs are the paths iz serves: `{base_url}/auth/callback`, + `{base_url}/` and `{base_url}/auth/backchannel-logout`. + +Then set the `[oidc]` section in `iz.toml`: + +```toml +[oidc] +issuer = "https://im.example.com" +client_id = "" +client_secret_file = "/etc/iz/oidc_client_secret" +``` + +Restart iz after changing the config. `im client list` shows the registered clients, and +`im client disable ` turns one off. + +## Backups + +With a `[backup]` section, iz writes a backup set into `dir` every `interval_hours` and keeps the newest +`keep` sets. A set is a directory with: + +- `iz.db`: a consistent copy of the database, +- `attachments/`: the local attachment files, +- `manifest.json`: a SHA-256 for each file. + +Backups do not copy `iz.key`. Keep that copy separately, as described in First run. + +Restore with the server stopped: + +```sh +sudo systemctl stop iz +iz restore --from /var/lib/iz/backups/ +sudo systemctl start iz +``` + +`iz restore` checks the set against `manifest.json` before it writes anything. A set that fails the +check is not restored. Do not copy the live database file by hand: it is written while iz runs. + +## Command line + +Run these as the `iz` user, or with `sudo -u iz`, using the same config as the server. + +- `iz serve`: run the server. This is the default when no command is given. +- `iz export --out DIR`: write an export into `DIR`. It never writes outside `DIR`. +- `iz restore --from `: restore a backup set. The server must be stopped. +- `iz fsck`: check the database and files. It is read-only. + +`export`, `restore` and `fsck` refuse to run while the server holds the lock file `data_dir/iz.lock`. +Stop the service first. Exit status is 0 for success, 1 for a failure, and 2 for a usage error. + +Logs go to stderr at `info` level. Set `RUST_LOG` to change the level. Under systemd, read them with +`journalctl -u iz`. + +## Where to read more + +- `docs/architecture.md`: modules, data model, routes, workers and rules. +- `docs/contracts.md`: the HTTP contracts shared with `im` (sign-in, logout, directory) and `in` (object store). +- `docs/conventions.md`: boot order, config rules, store and deploy rules. diff --git a/crates/iz-core/src/config.rs b/crates/iz-core/src/config.rs index 4aac41b..f1db72b 100644 --- a/crates/iz-core/src/config.rs +++ b/crates/iz-core/src/config.rs @@ -71,10 +71,10 @@ pub struct InStoreConfig { pub struct BackupConfig { /// Directory that receives the backup sets. pub dir: PathBuf, - /// Hours between backups. Between 1 and 720. + /// Hours between backups. Between 1 and 168 (one week). #[serde(default = "default_backup_interval_hours")] pub interval_hours: u32, - /// Backup sets to keep. Between 1 and 365. + /// Finished backup sets to keep; older sets are deleted after each backup. At least 1. #[serde(default = "default_backup_keep")] pub keep: u32, /// Optional URL pinged after each successful backup (for example a dead-man's switch). @@ -186,13 +186,13 @@ impl Config { if backup.dir.as_os_str().is_empty() { return Err(Error::Config("backup.dir must not be empty".into())); } - if !(1..=720).contains(&backup.interval_hours) { + if !(1..=168).contains(&backup.interval_hours) { return Err(Error::Config( - "backup.interval_hours must be 1 to 720".into(), + "backup.interval_hours must be 1 to 168".into(), )); } - if !(1..=365).contains(&backup.keep) { - return Err(Error::Config("backup.keep must be 1 to 365".into())); + if backup.keep == 0 { + return Err(Error::Config("backup.keep must be at least 1".into())); } if let Some(url) = &backup.healthcheck_url && !(url.starts_with("https://") || url.starts_with("http://")) diff --git a/crates/iz-core/src/lib.rs b/crates/iz-core/src/lib.rs index 412eb33..d466c9b 100644 --- a/crates/iz-core/src/lib.rs +++ b/crates/iz-core/src/lib.rs @@ -11,6 +11,7 @@ pub mod config; pub mod error; pub mod limits; pub mod mail_text; +pub mod manifest; pub mod preview; pub mod rules; pub mod secret; diff --git a/crates/iz-core/src/manifest.rs b/crates/iz-core/src/manifest.rs new file mode 100644 index 0000000..47b236d --- /dev/null +++ b/crates/iz-core/src/manifest.rs @@ -0,0 +1,255 @@ +//! The manifest of a backup set: the list of files in the set with their sizes and SHA-256 digests, and +//! the check that a set on disk still matches it. +//! +//! A set is one directory: `manifest.json` plus the files it lists, with `/`-separated relative paths. +//! The writer (`iz-web` backup worker) writes every listed file first and the manifest last, so a set +//! without a manifest is an unfinished set. The verifier (`iz restore`, `iz fsck`) refuses a set when a +//! listed file is missing, has another size or digest, a path is unsafe (absolute, `..`, a link), or a +//! file is in the directory that the manifest does not list. A manifest that is not valid JSON, or +//! names another version, is refused too. +//! +//! The manifest only detects changes to the set: someone who rewrites files and the manifest together +//! is not caught. Keeping the backup directory readable only by the service user is the protection +//! against that. + +use std::collections::BTreeSet; +use std::fs::File; +use std::io::Read; +use std::path::{Component, Path, PathBuf}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::error::{Error, Result}; + +/// The file name of the manifest inside a set. +pub const MANIFEST_NAME: &str = "manifest.json"; +/// The only manifest version this build reads and writes. +pub const MANIFEST_VERSION: u32 = 1; +/// Largest manifest read, in bytes. Reason: a manifest lists files; a huge one is not ours. +pub const MANIFEST_MAX_BYTES: u64 = 16 * 1024 * 1024; + +/// One file of a set. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ManifestFile { + /// Path inside the set, `/`-separated, relative, without `..` or a leading `/`. + pub path: String, + /// Size in bytes. + pub size: u64, + /// SHA-256 of the contents, lowercase hex. + pub sha256: String, +} + +/// The manifest as stored in `manifest.json`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Manifest { + /// Always [`MANIFEST_VERSION`] for this build. + pub version: u32, + /// UTC stamp of when the set was written. + pub created_at: String, + /// The build that wrote the set. + pub build: String, + /// Every file of the set except the manifest itself. + pub files: Vec, +} + +/// The SHA-256 and size of one file, read in chunks. +pub fn digest_file(path: &Path) -> Result<(u64, String)> { + let mut file = File::open(path)?; + let mut hasher = Sha256::new(); + let mut size: u64 = 0; + let mut buffer = vec![0u8; 64 * 1024]; + loop { + let read = file.read(&mut buffer)?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + size += read as u64; + } + Ok((size, hex::encode(hasher.finalize()))) +} + +/// Whether `path` is a safe relative set path: non-empty, no leading `/`, no `..`, no `.`, no empty +/// component, no NUL or backslash. +pub fn is_safe_relative(path: &str) -> bool { + if path.is_empty() || path.contains('\0') || path.contains('\\') { + return false; + } + !path.split('/').any(str::is_empty) + && Path::new(path) + .components() + .all(|component| matches!(component, Component::Normal(_))) +} + +/// Writes `manifest.json` into `dir` with the given files. Each listed file must already exist in +/// `dir` and is hashed here, so the manifest describes what is on disk. The manifest is written to a +/// temporary name and renamed into place, so a crash leaves either no manifest or a whole one. +pub fn write_manifest( + dir: &Path, + created_at: &str, + build: &str, + paths: &[String], +) -> Result { + let mut files = Vec::with_capacity(paths.len()); + for path in paths { + if !is_safe_relative(path) { + return Err(Error::Invalid(format!( + "unsafe path in a backup set: {path}" + ))); + } + let (size, sha256) = digest_file(&dir.join(path))?; + files.push(ManifestFile { + path: path.clone(), + size, + sha256, + }); + } + let manifest = Manifest { + version: MANIFEST_VERSION, + created_at: created_at.to_owned(), + build: build.to_owned(), + files, + }; + let json = serde_json::to_vec_pretty(&manifest) + .map_err(|e| Error::Invalid(format!("encoding the manifest: {e}")))?; + let tmp = dir.join(format!("{MANIFEST_NAME}.tmp")); + std::fs::write(&tmp, json)?; + File::open(&tmp)?.sync_all()?; + std::fs::rename(&tmp, dir.join(MANIFEST_NAME))?; + Ok(manifest) +} + +/// Reads and checks a set. Returns the manifest when every listed file matches its size and digest and +/// no other file sits in the set. Errors name the first problem found. +pub fn verify_set(dir: &Path) -> Result { + let manifest = read_manifest(&dir.join(MANIFEST_NAME))?; + let mut listed = BTreeSet::new(); + for file in &manifest.files { + if !is_safe_relative(&file.path) { + return Err(refused(format!( + "unsafe path in the manifest: {}", + file.path + ))); + } + if !listed.insert(file.path.clone()) { + return Err(refused(format!("the manifest lists {} twice", file.path))); + } + let path = dir.join(&file.path); + let meta = std::fs::symlink_metadata(&path) + .map_err(|_| refused(format!("missing from the set: {}", file.path)))?; + if !meta.file_type().is_file() { + return Err(refused(format!("not a regular file: {}", file.path))); + } + let (size, sha256) = digest_file(&path)?; + if size != file.size || sha256 != file.sha256 { + return Err(refused(format!( + "changed since the set was written: {}", + file.path + ))); + } + } + let mut on_disk = BTreeSet::new(); + collect_files(dir, dir, &mut on_disk)?; + on_disk.remove(MANIFEST_NAME); + if let Some(extra) = on_disk.difference(&listed).next() { + return Err(refused(format!("not listed in the manifest: {extra}"))); + } + Ok(manifest) +} + +/// Reads the manifest with its size limit and checks its version. +pub fn read_manifest(path: &Path) -> Result { + let meta = std::fs::symlink_metadata(path) + .map_err(|_| refused("the set has no manifest".to_owned()))?; + if !meta.file_type().is_file() || meta.len() > MANIFEST_MAX_BYTES { + return Err(refused( + "the manifest is not a regular file of a sane size".to_owned(), + )); + } + let bytes = std::fs::read(path)?; + let manifest: Manifest = serde_json::from_slice(&bytes) + .map_err(|e| refused(format!("the manifest is not valid: {e}")))?; + if manifest.version != MANIFEST_VERSION { + return Err(refused(format!( + "the manifest has version {}, this build reads {MANIFEST_VERSION}", + manifest.version + ))); + } + Ok(manifest) +} + +/// Every regular file below `root` as a `/`-separated path relative to `base`. Links and other +/// non-regular entries are refused, so a set cannot hide a file behind a link. +fn collect_files(base: &Path, dir: &Path, out: &mut BTreeSet) -> Result<()> { + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let path: PathBuf = entry.path(); + let meta = std::fs::symlink_metadata(&path)?; + if meta.file_type().is_dir() { + collect_files(base, &path, out)?; + } else if meta.file_type().is_file() { + let relative = path + .strip_prefix(base) + .map_err(|_| refused("a file escaped the set".to_owned()))?; + let text = relative + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join("/"); + out.insert(text); + } else { + return Err(refused(format!("not a regular file: {}", path.display()))); + } + } + Ok(()) +} + +/// A refused set: the manifest's problem as the user reads it. +fn refused(text: String) -> Error { + Error::Invalid(format!("the backup set is refused: {text}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_relative_path_must_stay_inside_the_set() { + assert!(is_safe_relative("iz.db")); + assert!(is_safe_relative("attachments/0a/01J")); + for bad in [ + "", + "/etc/passwd", + "../x", + "a/../b", + "a//b", + "a/", + "./a", + "a\\b", + "a\0b", + ] { + assert!(!is_safe_relative(bad), "accepted {bad:?}"); + } + } + + #[test] + fn a_tampered_file_or_an_extra_file_is_refused() { + let dir = tempfile::tempdir().expect("temp dir"); + std::fs::write(dir.path().join("iz.db"), b"one").expect("write"); + write_manifest( + dir.path(), + "2026-10-28T00:00:00.000000000Z", + "t", + &["iz.db".into()], + ) + .expect("manifest"); + verify_set(dir.path()).expect("a fresh set verifies"); + + std::fs::write(dir.path().join("iz.db"), b"two").expect("tamper"); + assert!(verify_set(dir.path()).is_err()); + std::fs::write(dir.path().join("iz.db"), b"one").expect("restore"); + std::fs::write(dir.path().join("extra"), b"x").expect("extra"); + assert!(verify_set(dir.path()).is_err()); + } +} diff --git a/crates/iz-core/src/store/audit.rs b/crates/iz-core/src/store/audit.rs new file mode 100644 index 0000000..deeb0b0 --- /dev/null +++ b/crates/iz-core/src/store/audit.rs @@ -0,0 +1,107 @@ +//! The audit trail of administrator and account actions: one append-only row per action, written after +//! the change it records has committed. +//! +//! A failed audit write never fails the request. The write is logged at error level and the caller gets +//! nothing back, because a request that already changed data must still answer as a success. The `data` +//! column holds what an operator needs to read the action (names, roles, counts), never a password, a +//! token, a cookie or a secret: the caller is responsible for that. + +use serde_json::Value; + +use super::{db_err, new_id}; +use crate::error::Result; +use crate::store::Store; +use crate::time::now_stamp; + +/// The kinds of actor an audit row can name. Matches the CHECK constraint of `audit_log.actor_kind`. +pub const ACTOR_KINDS: [&str; 4] = ["member", "admin", "system", "anonymous"]; + +/// One row to append. `actor_id` is the member id (the OIDC `sub`) when there is one. +#[derive(Debug, Clone)] +pub struct AuditEntry<'a> { + /// The member who acted, if any. + pub actor: Option<&'a str>, + /// `member`, `admin`, `system` or `anonymous`. + pub actor_kind: &'static str, + /// Dotted action name, for example `role.set` or `tag.delete`. + pub action: &'static str, + /// What kind of thing was changed, for example `member`, `tag`, `column`, `settings`. + pub target_kind: &'static str, + /// The id of the changed thing, if it has one. + pub target_id: Option<&'a str>, + /// The client address as iz saw it, when the request has one. + pub ip: Option<&'a str>, + /// Details for the operator. Never a secret. + pub data: Value, +} + +impl Store { + /// Appends one audit row. Never fails: an error is logged and dropped, so the caller's answer does + /// not depend on the audit trail. Call it after the change commits. + pub async fn audit(&self, entry: AuditEntry<'_>) { + if let Err(error) = self.append_audit(&entry).await { + tracing::error!( + error = %error, + action = entry.action, + "audit: could not record an action" + ); + } + } + + /// The write behind [`Store::audit`]. Returns the error instead of logging it, so tests can check it. + pub async fn append_audit(&self, entry: &AuditEntry<'_>) -> Result<()> { + let data = serde_json::to_string(&entry.data).unwrap_or_else(|_| "{}".to_owned()); + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO audit_log (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + ( + new_id(), + now_stamp(), + entry.actor.map(str::to_owned), + entry.actor_kind.to_owned(), + entry.action.to_owned(), + entry.target_kind.to_owned(), + entry.target_id.map(str::to_owned), + entry.ip.map(str::to_owned), + data, + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn an_audit_row_is_appended_with_its_action() { + let dir = tempfile::tempdir().expect("temp dir"); + let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); + store + .append_audit(&AuditEntry { + actor: Some("sub-1"), + actor_kind: "admin", + action: "role.set", + target_kind: "member", + target_id: Some("sub-2"), + ip: None, + data: serde_json::json!({"role": "viewer"}), + }) + .await + .expect("append"); + let conn = store.read_conn().await; + let count = super::super::fetch_opt( + &conn, + "SELECT COUNT(*) FROM audit_log WHERE action = 'role.set' AND actor_kind = 'admin'", + (), + |row| super::super::col_int(row, 0), + ) + .await + .expect("count"); + assert_eq!(count, Some(1)); + } +} diff --git a/crates/iz-core/src/store/board.rs b/crates/iz-core/src/store/board.rs index 96c0b06..226594b 100644 --- a/crates/iz-core/src/store/board.rs +++ b/crates/iz-core/src/store/board.rs @@ -26,8 +26,6 @@ const DEFAULT_COLUMNS: [(&str, bool); 4] = [ ]; /// Name of the tag every task wears when no other is chosen. pub const DEFAULT_TAG_NAME: &str = "General"; -/// Longest tag colour name, in characters. Reason: colours come from a short fixed palette. -const COLOR_MAX: usize = 20; /// The board row. #[derive(Debug, Clone, PartialEq, Eq)] @@ -124,6 +122,17 @@ fn map_tag(row: &turso::Row) -> Result { } /// A board key prefix: two to six uppercase ASCII letters. +/// The number of colours in the fixed project palette. The names are `c0` to `c{TAG_COLOURS - 1}`; the +/// board view maps each name to one tone of the stylesheet. +pub const TAG_COLOURS: usize = 8; + +/// Whether `name` is one colour of the fixed palette (`c0` to `c7`). +pub fn valid_colour(name: &str) -> bool { + name.strip_prefix('c') + .and_then(|n| n.parse::().ok()) + .is_some_and(|n| n < TAG_COLOURS && name == format!("c{n}")) +} + pub fn valid_prefix(prefix: &str) -> bool { (2..=6).contains(&prefix.len()) && prefix.bytes().all(|b| b.is_ascii_uppercase()) } @@ -463,8 +472,8 @@ impl Store { pub async fn add_tag(&self, board_id: &str, name: &str, color: Option<&str>) -> Result { let name = clean_tag_name(name)?; let color = match color.map(str::trim).filter(|c| !c.is_empty()) { - Some(c) if c.chars().count() <= COLOR_MAX => Some(c.to_owned()), - Some(_) => return Err(Error::Invalid("colour name is too long".into())), + Some(c) if valid_colour(c) => Some(c.to_owned()), + Some(_) => return Err(Error::Invalid("that colour is not in the palette".into())), None => None, }; let conn = self.inner.conn.lock().await; @@ -502,6 +511,57 @@ impl Store { finish(tx, outcome).await } + /// Sets the colour of a project from the fixed palette, or clears it (`None`). `NotFound` for a tag + /// that is not on this board. + pub async fn set_tag_colour( + &self, + board_id: &str, + tag_id: &str, + colour: Option<&str>, + ) -> Result<()> { + let colour = match colour.map(str::trim).filter(|c| !c.is_empty()) { + Some(c) if valid_colour(c) => Some(c.to_owned()), + Some(_) => return Err(Error::Invalid("that colour is not in the palette".into())), + None => None, + }; + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE tags SET color = ?3 WHERE id = ?1 AND board_id = ?2", + (tag_id.to_owned(), board_id.to_owned(), colour), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + + /// Live task counts per project of `board_id`, as `(tag id, count)`. Projects with no task are absent. + pub async fn tag_usage(&self, board_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT tag_id, COUNT(*) FROM tasks WHERE board_id = ?1 AND deleted_at IS NULL GROUP BY tag_id", + (board_id.to_owned(),), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + ) + .await + } + + /// Live task counts per live column of `board_id`, as `(column id, count)`. + pub async fn column_usage(&self, board_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT column_id, COUNT(*) FROM tasks WHERE board_id = ?1 AND deleted_at IS NULL GROUP BY column_id", + (board_id.to_owned(),), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + ) + .await + } + /// Renames a tag. The new name must be unique per board, ignoring case. pub async fn rename_tag(&self, board_id: &str, tag_id: &str, name: &str) -> Result<()> { let name = clean_tag_name(name)?; diff --git a/crates/iz-core/src/store/export.rs b/crates/iz-core/src/store/export.rs new file mode 100644 index 0000000..09702ef --- /dev/null +++ b/crates/iz-core/src/store/export.rs @@ -0,0 +1,365 @@ +//! Read-only access to a database file, for the operator commands (`iz export`, `iz restore`, `iz fsck`). +//! +//! What it is: a connection that never migrates, never writes and reads a board as JSON rows with the +//! column names the export file uses. What it is not: the server's store. Opening through [`Store::open`] +//! would apply migrations, so a check of a damaged or foreign file would change it. The invariant: nothing +//! in this module writes to the database, and the migration history is checked by [`migrations_problem`] +//! against the versions this build knows. + +use std::path::Path; + +use turso::{Builder, Connection, Database, IntoParams, Value}; + +use super::migrate::MIGRATIONS; +use super::{col_text, db_err, fetch_all}; +use crate::error::{Error, Result}; + +/// A database file opened read-only. Keep it alive while its rows are used. +pub struct ReadOnly { + /// Keeps the database handle alive as long as the connection exists. + _db: Database, + conn: Connection, +} + +/// One attachment row as stored. `location` is `local` (bytes on this disk), `in` (bytes in another +/// service) or `moving`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AttachmentRow { + /// Attachment id (ULID). + pub id: String, + /// The task it belongs to. + pub task_id: String, + /// File name as uploaded. + pub name: String, + /// Sniffed MIME type. + pub mime: String, + /// Length in bytes as recorded. + pub size: u64, + /// Lowercase hex SHA-256 as recorded. + pub sha256: String, + /// Uploader's member id. + pub uploaded_by: String, + /// UTC stamp of the upload. + pub created_at: String, + /// Where the bytes are: `local`, `in` or `moving`. + pub location: String, +} + +/// A board as JSON rows, one list per table. Each row is an object keyed by the column names. +#[derive(Debug, Clone, PartialEq)] +pub struct BoardDump { + /// The board row (a single object). + pub board: serde_json::Value, + /// Columns, retired ones included, in position order. + pub columns: Vec, + /// Tags (projects), in position order. + pub tags: Vec, + /// Tasks, deleted ones included (with `deleted_at`), oldest first. + pub tasks: Vec, + /// Assignments of tasks. + pub assignees: Vec, + /// Dependency links, cleared ones included (with `cleared_at`). + pub dependencies: Vec, + /// Comments, deleted ones included (with `deleted_at`). + pub comments: Vec, + /// Activity of the board's tasks, oldest first. + pub activity: Vec, + /// Members named by any row above: `sub`, `name` and `email` only. + pub members: Vec, +} + +/// The first problem with a migration history, as the user reads it, or `None` when the versions are +/// exactly `1..=N` and `N` is no newer than this build. An empty history is a problem too. +pub fn migrations_problem(versions: &[i64]) -> Option { + if versions.is_empty() { + return Some("the database has no migration history".into()); + } + for (index, version) in versions.iter().enumerate() { + let expected = i64::try_from(index + 1).unwrap_or(i64::MAX); + if *version != expected { + return Some(format!( + "migration history is not contiguous: expected version {expected}, found {version}" + )); + } + } + let known = MIGRATIONS + .last() + .map_or(0, |(version, _)| i64::from(*version)); + let newest = versions.last().copied().unwrap_or(0); + if newest > known { + return Some(format!( + "the database is at migration {newest}, this build knows up to {known}" + )); + } + None +} + +/// Column names of an attachment row, in the order `attachment_rows` selects them. +const ATTACHMENT_SQL: &str = "SELECT a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, \ + a.created_at, a.location FROM attachments a"; + +fn map_attachment(row: &turso::Row) -> Result { + let size = match row.get_value(4).map_err(db_err)? { + Value::Integer(n) => { + u64::try_from(n).map_err(|_| Error::Database("attachment size is negative".into()))? + } + _ => return Err(Error::Database("attachment size is not an integer".into())), + }; + Ok(AttachmentRow { + id: col_text(row, 0)?, + task_id: col_text(row, 1)?, + name: col_text(row, 2)?, + mime: col_text(row, 3)?, + size, + sha256: col_text(row, 5)?, + uploaded_by: col_text(row, 6)?, + created_at: col_text(row, 7)?, + location: col_text(row, 8)?, + }) +} + +/// Converts one SQL value to JSON. Blobs are refused: no column of this schema holds one. +fn to_json(value: Value) -> Result { + Ok(match value { + Value::Null => serde_json::Value::Null, + Value::Integer(n) => serde_json::Value::from(n), + Value::Real(f) => serde_json::Number::from_f64(f) + .map(serde_json::Value::Number) + .ok_or_else(|| Error::Database("a real column holds NaN or infinity".into()))?, + Value::Text(s) => serde_json::Value::String(s), + Value::Blob(_) => return Err(Error::Database("unexpected blob in a row".into())), + }) +} + +/// Runs a query and returns each row as an object keyed by `cols`, which name the selected columns in +/// order. +async fn json_rows( + conn: &Connection, + sql: &str, + params: impl IntoParams, + cols: &[&str], +) -> Result> { + fetch_all(conn, sql, params, |row| { + let mut object = serde_json::Map::new(); + for (i, name) in cols.iter().enumerate() { + let value = row.get_value(i).map_err(db_err)?; + object.insert((*name).to_owned(), to_json(value)?); + } + Ok(serde_json::Value::Object(object)) + }) + .await +} + +impl ReadOnly { + /// Opens the database file read-only. A missing file is an error: nothing is created. + pub async fn open(path: &Path) -> Result { + let text = path.to_str().ok_or_else(|| { + Error::Config(format!("database path is not UTF-8: {}", path.display())) + })?; + let db = Builder::new_local(text) + .read_only(true) + .build() + .await + .map_err(db_err)?; + let conn = db.connect().map_err(db_err)?; + Ok(ReadOnly { _db: db, conn }) + } + + /// The rows `PRAGMA integrity_check` returns. A healthy database returns exactly `ok`. + pub async fn integrity_check(&self) -> Result> { + fetch_all(&self.conn, "PRAGMA integrity_check", (), |row| { + col_text(row, 0) + }) + .await + } + + /// The migration versions recorded, ascending. + pub async fn migration_versions(&self) -> Result> { + fetch_all( + &self.conn, + "SELECT version FROM schema_migrations ORDER BY version", + (), + |row| match row.get_value(0).map_err(db_err)? { + Value::Integer(n) => Ok(n), + _ => Err(Error::Database( + "schema_migrations.version is not an integer".into(), + )), + }, + ) + .await + } + + /// Every attachment row of the database, oldest first. + pub async fn attachment_rows(&self) -> Result> { + fetch_all( + &self.conn, + &format!("{ATTACHMENT_SQL} ORDER BY a.id"), + (), + map_attachment, + ) + .await + } + + /// The attachment rows of the tasks of `board_id`, oldest first. + pub async fn board_attachment_rows(&self, board_id: &str) -> Result> { + fetch_all( + &self.conn, + &format!( + "{ATTACHMENT_SQL} JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 \ + ORDER BY a.created_at, a.id" + ), + (board_id.to_owned(),), + map_attachment, + ) + .await + } + + /// The ids of the boards in the database. One board per instance is the rule, but the export names + /// the board it reads, so it checks. + pub async fn board_ids(&self) -> Result> { + fetch_all(&self.conn, "SELECT id FROM boards ORDER BY id", (), |row| { + col_text(row, 0) + }) + .await + } + + /// Reads a board, its tasks and everything hanging off them, as JSON rows. Every query names its + /// columns, so the export file does not depend on the column order of the schema. + pub async fn export_board(&self, board_id: &str) -> Result { + let conn = &self.conn; + let board_param = || (board_id.to_owned(),); + let board = json_rows( + conn, + "SELECT id, name, key_prefix, next_task_number, created_at FROM boards WHERE id = ?1", + board_param(), + &["id", "name", "key_prefix", "next_task_number", "created_at"], + ) + .await? + .into_iter() + .next() + .ok_or(Error::NotFound)?; + let columns = json_rows( + conn, + "SELECT id, name, position, is_done, created_at, deleted_at FROM columns \ + WHERE board_id = ?1 ORDER BY position, id", + board_param(), + &[ + "id", + "name", + "position", + "is_done", + "created_at", + "deleted_at", + ], + ) + .await?; + let tags = json_rows( + conn, + "SELECT id, name, position, is_default, color, created_at FROM tags \ + WHERE board_id = ?1 ORDER BY position, id", + board_param(), + &[ + "id", + "name", + "position", + "is_default", + "color", + "created_at", + ], + ) + .await?; + let tasks = json_rows( + conn, + "SELECT id, key, parent_id, title, description, column_id, tag_id, deadline, meeting_at, \ + position, created_by, created_at, updated_at, done_at, deleted_at FROM tasks \ + WHERE board_id = ?1 ORDER BY created_at, id", + board_param(), + &[ + "id", + "key", + "parent_id", + "title", + "description", + "column_id", + "tag_id", + "deadline", + "meeting_at", + "position", + "created_by", + "created_at", + "updated_at", + "done_at", + "deleted_at", + ], + ) + .await?; + let assignees = json_rows( + conn, + "SELECT a.task_id, a.sub, a.assigned_at FROM task_assignees a \ + JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 ORDER BY a.task_id, a.sub", + board_param(), + &["task_id", "sub", "assigned_at"], + ) + .await?; + let dependencies = json_rows( + conn, + "SELECT d.blocked_id, d.blocking_id, d.created_at, d.cleared_at FROM dependencies d \ + JOIN tasks t ON t.id = d.blocked_id WHERE t.board_id = ?1 ORDER BY d.created_at", + board_param(), + &["blocked_id", "blocking_id", "created_at", "cleared_at"], + ) + .await?; + let comments = json_rows( + conn, + "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at \ + FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1 \ + ORDER BY c.created_at, c.id", + board_param(), + &[ + "id", + "task_id", + "author", + "body", + "created_at", + "edited_at", + "deleted_at", + ], + ) + .await?; + let activity = json_rows( + conn, + "SELECT x.id, x.task_id, x.actor, x.subject, x.kind, x.detail, x.at FROM activity x \ + JOIN tasks t ON t.id = x.task_id WHERE t.board_id = ?1 ORDER BY x.at, x.id", + board_param(), + &["id", "task_id", "actor", "subject", "kind", "detail", "at"], + ) + .await?; + let members = json_rows( + conn, + "SELECT sub, name, email FROM members WHERE sub IN (\ + SELECT created_by FROM tasks WHERE board_id = ?1 \ + UNION SELECT a.sub FROM task_assignees a JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 \ + UNION SELECT c.author FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1 \ + UNION SELECT x.actor FROM activity x JOIN tasks t ON t.id = x.task_id \ + WHERE t.board_id = ?1 AND x.actor IS NOT NULL \ + UNION SELECT x.subject FROM activity x JOIN tasks t ON t.id = x.task_id \ + WHERE t.board_id = ?1 AND x.subject IS NOT NULL \ + UNION SELECT at.uploaded_by FROM attachments at JOIN tasks t ON t.id = at.task_id \ + WHERE t.board_id = ?1) ORDER BY sub", + board_param(), + &["sub", "name", "email"], + ) + .await?; + Ok(BoardDump { + board, + columns, + tags, + tasks, + assignees, + dependencies, + comments, + activity, + members, + }) + } +} diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 31bd8d3..5da4c14 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -9,18 +9,22 @@ pub mod activity; pub mod attachments; +pub mod audit; pub mod board; pub mod comments; pub mod events; +pub mod export; pub mod members; pub mod migrate; pub mod outbox; +pub mod people; pub mod reminders; pub mod rules; pub mod rules_engine; pub mod sender; pub mod sessions; pub mod snapshot; +pub mod sweep; pub mod tasks; use std::path::Path; @@ -128,6 +132,19 @@ impl Store { Ok(()) } + /// The highest applied migration version, for the server page. + pub async fn schema_version(&self) -> Result { + let conn = self.read_conn().await; + let value = fetch_opt( + &conn, + "SELECT MAX(version) FROM schema_migrations", + (), + |row| col_int(row, 0), + ) + .await?; + Ok(value.unwrap_or(0)) + } + /// Runs `SELECT 1` on a pooled reader and fails when the database does not answer. The health /// route calls it with a deadline, so a stuck lock shows up as a failed probe. pub async fn ping(&self) -> Result<()> { diff --git a/crates/iz-core/src/store/outbox.rs b/crates/iz-core/src/store/outbox.rs index 1e1943a..acd0857 100644 --- a/crates/iz-core/src/store/outbox.rs +++ b/crates/iz-core/src/store/outbox.rs @@ -1,7 +1,7 @@ //! The outbox: every mail iz sends is a row here first, written in the transaction that decided it. The //! worker in `iz-web` claims due rows under a lease, sends them and records the result. Nothing else sends. //! -//! Retries: a failed attempt waits `BACKOFF_MINUTES` (1, 5, 15, then 60) before the next one; the fifth +//! Retries: a failed attempt waits `BACKOFF_MINUTES` (5, 10, 20, then 40) before the next one; the fifth //! failure, or a permanent refusal by the server, abandons the row. A row that cannot be sent for lack of a //! sender is held for `HOLD_MINUTES` and spends no attempt. A claim is a lease of `LEASE_MINUTES`: a worker //! that dies lets the row go again after that. Rows of a member who is no longer eligible are abandoned at @@ -22,7 +22,8 @@ use crate::time::now_stamp; /// Failed attempts before a row is abandoned. pub const MAX_ATTEMPTS: i64 = 5; /// The wait after the first, second, third and fourth failure, in minutes. The fifth failure abandons. -pub const BACKOFF_MINUTES: [i64; 4] = [1, 5, 15, 60]; +/// Reason: architecture section 5 fixes these values. +pub const BACKOFF_MINUTES: [i64; 4] = [5, 10, 20, 40]; /// The wait before trying again when no sender is configured. It spends no attempt. pub const HOLD_MINUTES: i64 = 1; /// How long a claim holds a row before another worker may take it, in minutes. diff --git a/crates/iz-core/src/store/people.rs b/crates/iz-core/src/store/people.rs new file mode 100644 index 0000000..b5414bb --- /dev/null +++ b/crates/iz-core/src/store/people.rs @@ -0,0 +1,91 @@ +//! The person card of `/people/{sub}`: how many open and finished tasks a member of this board is +//! assigned to, how many tasks they created, how many comments and files they posted. Every count is +//! limited to live tasks of one board, so a member of another board or a deleted card adds nothing. + +use turso::Connection; + +use super::{col_int, fetch_opt}; +use crate::error::Result; +use crate::store::Store; + +/// The counts shown on a person card. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PersonCounts { + /// Assigned live tasks that are not done. + pub open: i64, + /// Assigned live tasks that are done. + pub done: i64, + /// Live tasks the member created. + pub created: i64, + /// Live comments the member wrote. + pub comments: i64, + /// Files the member attached to live tasks. + pub files: i64, +} + +/// Counts for one member on one board. One statement per figure, all reads. +pub async fn counts(conn: &Connection, board_id: &str, sub: &str) -> Result { + let open = count( + conn, + "SELECT COUNT(*) FROM task_assignees a JOIN tasks t ON t.id = a.task_id \ + WHERE a.sub = ?2 AND t.board_id = ?1 AND t.deleted_at IS NULL AND t.done_at IS NULL", + board_id, + sub, + ) + .await?; + let done = count( + conn, + "SELECT COUNT(*) FROM task_assignees a JOIN tasks t ON t.id = a.task_id \ + WHERE a.sub = ?2 AND t.board_id = ?1 AND t.deleted_at IS NULL AND t.done_at IS NOT NULL", + board_id, + sub, + ) + .await?; + let created = count( + conn, + "SELECT COUNT(*) FROM tasks WHERE board_id = ?1 AND created_by = ?2 AND deleted_at IS NULL", + board_id, + sub, + ) + .await?; + let comments = count( + conn, + "SELECT COUNT(*) FROM comments c JOIN tasks t ON t.id = c.task_id \ + WHERE t.board_id = ?1 AND c.author = ?2 AND c.deleted_at IS NULL AND t.deleted_at IS NULL", + board_id, + sub, + ) + .await?; + let files = count( + conn, + "SELECT COUNT(*) FROM attachments f JOIN tasks t ON t.id = f.task_id \ + WHERE t.board_id = ?1 AND f.uploaded_by = ?2 AND t.deleted_at IS NULL", + board_id, + sub, + ) + .await?; + Ok(PersonCounts { + open, + done, + created, + comments, + files, + }) +} + +/// One `COUNT(*)` with the board and the member as its two parameters. +async fn count(conn: &Connection, sql: &str, board_id: &str, sub: &str) -> Result { + let value = fetch_opt(conn, sql, (board_id.to_owned(), sub.to_owned()), |row| { + col_int(row, 0) + }) + .await?; + Ok(value.unwrap_or(0)) +} + +impl Store { + /// The counts of one member on `board_id`, read on a pooled reader. + pub async fn person_counts(&self, board_id: &str, sub: &str) -> Result { + let conn = self.read_conn().await; + counts(&conn, board_id, sub).await + } +} diff --git a/crates/iz-core/src/store/sweep.rs b/crates/iz-core/src/store/sweep.rs new file mode 100644 index 0000000..3630a68 --- /dev/null +++ b/crates/iz-core/src/store/sweep.rs @@ -0,0 +1,120 @@ +//! Retention and housekeeping deletes that the sweeper worker runs on a timer: old activity, old rows of +//! the mail ledger, and finished mail outbox rows. Every delete is batched, so one call never holds the +//! writer for long, and the caller loops until a batch comes back short. +//! +//! This module only deletes rows that nothing needs any more. Pending mail, pending attachment deletions +//! and live sessions are never touched here; their own modules own those rules. + +use jiff::Timestamp; + +use super::db_err; +use crate::clock::stamp_of; +use crate::error::Result; +use crate::store::Store; + +/// Days kept for activity, mail decisions and finished mail. Reason: a year covers a full review cycle of +/// the family board; older rows are noise for the admin pages. +pub const RETENTION_DAYS: i64 = 365; + +impl Store { + /// Deletes up to `batch` activity rows recorded before `cutoff`. Returns how many were deleted. + /// Activity is ordered by its stored stamp, which is fixed width, so text comparison is time order. + pub async fn prune_activity(&self, cutoff: Timestamp, batch: i64) -> Result { + let cutoff = stamp_of(cutoff)?; + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM activity WHERE id IN (SELECT id FROM activity WHERE at < ?1 LIMIT ?2)", + (cutoff, batch), + ) + .await + .map_err(db_err) + } + + /// Deletes up to `batch` mail decisions created before `cutoff`. Returns how many were deleted. + pub async fn prune_mail_decisions(&self, cutoff: Timestamp, batch: i64) -> Result { + let cutoff = stamp_of(cutoff)?; + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM mail_decisions WHERE id IN \ + (SELECT id FROM mail_decisions WHERE created_at < ?1 LIMIT ?2)", + (cutoff, batch), + ) + .await + .map_err(db_err) + } + + /// Deletes up to `batch` mail outbox rows that are finished (`sent` or `abandoned`) and were created + /// before `cutoff`. Pending and failed rows are never deleted: they still owe a send. + pub async fn prune_mail_outbox(&self, cutoff: Timestamp, batch: i64) -> Result { + let cutoff = stamp_of(cutoff)?; + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM mail_outbox WHERE id IN (SELECT id FROM mail_outbox \ + WHERE state IN ('sent', 'abandoned') AND created_at < ?1 LIMIT ?2)", + (cutoff, batch), + ) + .await + .map_err(db_err) + } + + /// The attachments whose bytes are on this machine (`location = 'local'`), as ids. The backup worker + /// copies exactly these files. + pub async fn local_attachment_ids(&self) -> Result> { + let conn = self.read_conn().await; + super::fetch_all( + &conn, + "SELECT id FROM attachments WHERE location = 'local' ORDER BY id", + (), + |row| super::col_text(row, 0), + ) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::fetch_opt; + + async fn count(store: &Store, sql: &str) -> i64 { + let conn = store.read_conn().await; + fetch_opt(&conn, sql, (), |row| super::super::col_int(row, 0)) + .await + .unwrap() + .unwrap() + } + + #[tokio::test] + async fn pruning_deletes_only_old_finished_rows() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("iz.db")).await.unwrap(); + { + let conn = store.inner.conn.lock().await; + conn.execute_batch( + "INSERT INTO members (sub, email, name, first_seen_at) VALUES ('u1', 'a@example.com', 'Ada', 'then'); + INSERT INTO activity (id, kind, detail, at) VALUES ('old', 'account_changed', '{}', '2020-01-01T00:00:00.000000000Z'); + INSERT INTO activity (id, kind, detail, at) VALUES ('new', 'account_changed', '{}', '2030-01-01T00:00:00.000000000Z'); + INSERT INTO mail_outbox (id, event_id, recipient, kind, subject, body, state, next_attempt_at, created_at, sent_at) + VALUES ('sent', 'e1', 'u1', 'test', 's', 'b', 'sent', 'then', '2020-01-01T00:00:00.000000000Z', '2020-01-01T00:00:00.000000000Z'); + INSERT INTO mail_outbox (id, event_id, recipient, kind, subject, body, state, next_attempt_at, created_at) + VALUES ('pending', 'e2', 'u1', 'test', 's', 'b', 'pending', 'then', '2020-01-01T00:00:00.000000000Z');", + ) + .await + .unwrap(); + } + let cutoff = Timestamp::now(); + assert_eq!(store.prune_activity(cutoff, 10).await.unwrap(), 1); + assert_eq!(store.prune_mail_outbox(cutoff, 10).await.unwrap(), 1); + assert_eq!(store.prune_mail_decisions(cutoff, 10).await.unwrap(), 0); + assert_eq!(count(&store, "SELECT COUNT(*) FROM activity").await, 1); + assert_eq!( + count( + &store, + "SELECT COUNT(*) FROM mail_outbox WHERE state = 'pending'" + ) + .await, + 1, + "a pending row must survive pruning" + ); + } +} diff --git a/crates/iz-web/Cargo.toml b/crates/iz-web/Cargo.toml index 6f89784..d3370ab 100644 --- a/crates/iz-web/Cargo.toml +++ b/crates/iz-web/Cargo.toml @@ -12,6 +12,7 @@ path = "src/main.rs" [dependencies] base64.workspace = true +clap = { workspace = true, features = ["derive"] } bytes.workspace = true futures-util.workspace = true hex.workspace = true diff --git a/crates/iz-web/src/auth.rs b/crates/iz-web/src/auth.rs index cf2d0d4..234f04d 100644 --- a/crates/iz-web/src/auth.rs +++ b/crates/iz-web/src/auth.rs @@ -124,24 +124,28 @@ pub async fn require_member(cx: &Cx) -> Result { } } -/// The signed-in member with the level `need`. A viewer who tries a write gets `403`; a member -/// with no access, or a disabled one, gets `404`, so the page does not reveal that it exists. +/// The signed-in member with the level `need`. A viewer or member who tries a write gets `403`; a +/// member with no access, or a disabled one, gets `404`, so the page does not reveal that it exists. +/// Administrator pages answer `404` to everyone who is not an administrator, anonymous visitors +/// included: an admin page does not reveal that it exists, so it never redirects to sign-in. pub async fn require_role(cx: &Cx, need: Need) -> Result { + if need == Need::Admin { + let Some(me) = current_member(cx).await? else { + return Err(not_found().into()); + }; + return match authorize(&me.actor(), &Action::Administer) { + Ok(()) => Ok(me), + Err(_) => Err(not_found().into()), + }; + } let me = require_member(cx).await?; let action = match need { Need::Viewer => Action::ReadBoard, - Need::Member => Action::WriteTask, - Need::Admin => Action::Administer, + _ => Action::WriteTask, }; match authorize(&me.actor(), &action) { Ok(()) => Ok(me), - // An active member who is refused an admin page is told so (403). A disabled member is not, - // so a disabled administrator sees the same 404 as anyone without access. - Err(Denied::Forbidden) - if need == Need::Member || (need == Need::Admin && !me.member.disabled) => - { - Err(forbidden().into()) - } + Err(Denied::Forbidden) => Err(forbidden().into()), Err(_) => Err(not_found().into()), } } diff --git a/crates/iz-web/src/backup.rs b/crates/iz-web/src/backup.rs new file mode 100644 index 0000000..b214e40 --- /dev/null +++ b/crates/iz-web/src/backup.rs @@ -0,0 +1,270 @@ +//! The scheduled backup worker. Every `interval_hours` it writes one backup set under `[backup] dir`, then +//! keeps the newest `keep` finished sets and deletes the rest. It runs only when the config has a `[backup]` +//! section, and stops with the stop flag. +//! +//! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a +//! `VACUUM INTO` snapshot), `attachments/` for every attachment whose bytes are local, and +//! `manifest.json` written last (`iz_core::manifest`). A set is built in `.tmp-` and renamed to its +//! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed. +//! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever +//! deleted. Nothing is written in place. + +use std::os::unix::fs::DirBuilderExt; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use iz_core::clock::stamp_of; +use iz_core::config::BackupConfig; +use iz_core::manifest::{self, MANIFEST_NAME}; +use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; +use iz_core::store::{Store, new_id}; +use iz_core::{Error, Result}; +use tokio::sync::watch; + +use crate::state::AppState; + +/// Prefix of a set that is still being written. Reason: a crash leaves a visibly unfinished directory. +const TMP_PREFIX: &str = ".tmp-"; +/// The database copy inside a set. +const DB_FILE: &str = "iz.db"; +/// How long a healthcheck ping may take, in seconds. Reason: a slow ping must not hold the worker. +const PING_TIMEOUT: Duration = Duration::from_secs(10); +/// The stamp format of a set's directory name. Reason: no colons, so the name is portable. +const SET_STAMP_FORMAT: &str = "%Y%m%dT%H%M%SZ"; +/// Length of a set's directory name, which is the stamp format above. +const SET_NAME_LEN: usize = 16; + +/// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing. +/// The first backup runs at once, then one every `interval_hours`. +pub fn spawn(state: AppState, mut stop: watch::Receiver) { + let Some(policy) = state.config.backup.clone() else { + return; + }; + tokio::spawn(async move { + let client = match reqwest::Client::builder() + .timeout(PING_TIMEOUT) + .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) + .build() + { + Ok(client) => Some(client), + Err(error) => { + tracing::warn!(error = %error, "healthcheck client not built; pings are off"); + None + } + }; + let interval = Duration::from_secs(u64::from(policy.interval_hours) * 3600); + loop { + run_once(&state, &policy, client.as_ref(), &mut stop).await; + tokio::select! { + () = tokio::time::sleep(interval) => {} + _ = stop.wait_for(|stopped| *stopped) => break, + } + } + tracing::info!("backup worker stopped"); + }); +} + +/// One backup: write a set, publish it, prune the old sets, ping the healthcheck. A failure is logged and +/// leaves no partial set. A stop request cancels a set in progress and removes it. +async fn run_once( + state: &AppState, + policy: &BackupConfig, + client: Option<&reqwest::Client>, + stop: &mut watch::Receiver, +) { + if let Err(error) = ensure_dir(&policy.dir) { + tracing::warn!(error = %error, "backup directory cannot be created"); + return; + } + let now = jiff::Timestamp::now(); + let name = now.strftime(SET_STAMP_FORMAT).to_string(); + let created_at = match stamp_of(now) { + Ok(stamp) => stamp, + Err(error) => { + tracing::warn!(error = %error, "backup time cannot be stamped"); + return; + } + }; + let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id())); + let outcome = tokio::select! { + result = write_set(&state.store, &state.config.data_dir, &tmp, &created_at) => result, + _ = stop.wait_for(|stopped| *stopped) => { + Err(Error::Io(std::io::Error::other("stopped before the set was finished"))) + } + }; + let outcome = outcome.and_then(|files| publish(&tmp, &policy.dir, &name).map(|()| files)); + match outcome { + Ok(files) => { + tracing::info!(set = %name, files, "backup set written"); + let keep = usize::try_from(policy.keep).unwrap_or(usize::MAX); + match prune(&policy.dir, keep) { + Ok(0) => {} + Ok(removed) => tracing::info!(removed, "old backup sets deleted"), + Err(error) => tracing::warn!(error = %error, "pruning old backup sets failed"), + } + if let (Some(url), Some(client)) = (policy.healthcheck_url.as_deref(), client) { + ping(client, url).await; + } + } + Err(error) => { + // Only the directory this run created is removed, by its exact path. + let _ = std::fs::remove_dir_all(&tmp); + tracing::warn!(error = %error, "backup failed; the partial set was removed"); + } + } +} + +/// Writes the files of one set into `tmp` and the manifest last. Returns the number of files listed, not +/// counting the manifest. The caller removes `tmp` on error. +async fn write_set(store: &Store, data_dir: &Path, tmp: &Path, created_at: &str) -> Result { + create_dir(tmp, false)?; + store.snapshot_to(&tmp.join(DB_FILE)).await?; + let mut paths = vec![DB_FILE.to_owned()]; + let attachments = tmp.join(ATTACHMENTS_DIR); + create_dir(&attachments, false)?; + for id in store.local_attachment_ids().await? { + let source = blob_path(data_dir, &id)?; + let relative = format!("{ATTACHMENTS_DIR}/{id}"); + let target = tmp.join(&relative); + tokio::fs::copy(&source, &target).await?; + tokio::fs::File::open(&target).await?.sync_all().await?; + paths.push(relative); + } + let files = paths.len(); + // Hashing reads every file, which can take a while; it runs off the async threads. + let dir = tmp.to_owned(); + let created = created_at.to_owned(); + let build = env!("IZ_BUILD_SHA").to_owned(); + tokio::task::spawn_blocking(move || manifest::write_manifest(&dir, &created, &build, &paths)) + .await + .map_err(|error| Error::Io(std::io::Error::other(error)))??; + Ok(files) +} + +/// Creates the backup directory and any missing parents, unless it already exists. +fn ensure_dir(dir: &Path) -> std::io::Result<()> { + if dir.is_dir() { + return Ok(()); + } + create_dir(dir, true) +} + +/// Renames a complete set to its stamp and makes the rename durable. Refuses to replace an existing name. +fn publish(tmp: &Path, dir: &Path, name: &str) -> Result<()> { + let target = dir.join(name); + if std::fs::symlink_metadata(&target).is_ok() { + return Err(Error::Conflict(format!("backup set {name} already exists"))); + } + std::fs::rename(tmp, &target)?; + std::fs::File::open(dir)?.sync_all()?; + Ok(()) +} + +/// Deletes all finished sets except the newest `keep`. Only directories named like a set and holding a +/// manifest are candidates, so an unrelated directory in the backup dir is never touched. Returns the count. +fn prune(dir: &Path, keep: usize) -> Result { + let mut sets: Vec = std::fs::read_dir(dir)? + .filter_map(std::result::Result::ok) + .filter(|entry| is_set_name(&entry.file_name().to_string_lossy())) + .map(|entry| entry.path()) + .filter(|path| is_finished_set(path)) + .collect(); + // The stamp is fixed width and sorts in time order, so the name order is the age order. + sets.sort(); + let excess = sets.len().saturating_sub(keep); + for old in &sets[..excess] { + std::fs::remove_dir_all(old)?; + } + Ok(excess) +} + +/// Whether `name` has the shape of a set's directory name: `YYYYMMDDTHHMMSSZ`. +fn is_set_name(name: &str) -> bool { + let bytes = name.as_bytes(); + bytes.len() == SET_NAME_LEN + && bytes.iter().enumerate().all(|(i, byte)| match i { + 8 => *byte == b'T', + 15 => *byte == b'Z', + _ => byte.is_ascii_digit(), + }) +} + +/// Whether `path` is a real directory (not a link) that holds a manifest. +fn is_finished_set(path: &Path) -> bool { + let is_dir = std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir()); + let has_manifest = std::fs::symlink_metadata(path.join(MANIFEST_NAME)) + .is_ok_and(|meta| meta.file_type().is_file()); + is_dir && has_manifest +} + +/// Creates a directory with mode 0700. `recursive` also creates missing parents. +fn create_dir(path: &Path, recursive: bool) -> std::io::Result<()> { + std::fs::DirBuilder::new() + .recursive(recursive) + .mode(0o700) + .create(path) +} + +/// Pings the healthcheck once. A failure is logged without the URL, because the URL can carry a secret key. +async fn ping(client: &reqwest::Client, url: &str) { + match client.get(url).send().await { + Ok(response) if response.status().is_success() => {} + Ok(response) => { + tracing::warn!(status = %response.status(), "healthcheck ping was refused"); + } + Err(error) => { + tracing::warn!(error = %error.without_url(), "healthcheck ping failed"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A finished set on disk: a directory with a manifest, named by its stamp. + fn fake_set(dir: &Path, name: &str) { + let set = dir.join(name); + std::fs::create_dir(&set).expect("set dir"); + std::fs::write(set.join(MANIFEST_NAME), b"{}").expect("manifest"); + } + + #[tokio::test] + async fn a_written_set_verifies_and_is_published_by_its_stamp() { + let dir = tempfile::tempdir().expect("temp dir"); + let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); + let tmp = dir.path().join(format!("{TMP_PREFIX}{}", new_id())); + let created = "2026-10-28T09:30:00.000000000Z"; + write_set(&store, dir.path(), &tmp, created) + .await + .expect("set written"); + publish(&tmp, dir.path(), "20261028T093000Z").expect("published"); + let published = dir.path().join("20261028T093000Z"); + let verified = manifest::verify_set(&published).expect("the set verifies"); + assert_eq!(verified.created_at, created); + assert!(verified.files.iter().any(|file| file.path == DB_FILE)); + assert!(!tmp.exists(), "the temporary name is gone after the rename"); + } + + #[test] + fn prune_keeps_the_newest_sets_and_leaves_other_directories() { + let dir = tempfile::tempdir().expect("temp dir"); + for name in [ + "20260101T000000Z", + "20260102T000000Z", + "20260103T000000Z", + "20260104T000000Z", + ] { + fake_set(dir.path(), name); + } + std::fs::create_dir(dir.path().join("notes")).expect("unrelated dir"); + std::fs::create_dir(dir.path().join(format!("{TMP_PREFIX}abc"))).expect("tmp dir"); + assert_eq!(prune(dir.path(), 2).expect("prune"), 2); + assert!(!dir.path().join("20260101T000000Z").exists()); + assert!(!dir.path().join("20260102T000000Z").exists()); + assert!(dir.path().join("20260103T000000Z").exists()); + assert!(dir.path().join("20260104T000000Z").exists()); + assert!(dir.path().join("notes").exists()); + assert!(dir.path().join(format!("{TMP_PREFIX}abc")).exists()); + } +} diff --git a/crates/iz-web/src/boot.rs b/crates/iz-web/src/boot.rs index 63e6825..63a6ff3 100644 --- a/crates/iz-web/src/boot.rs +++ b/crates/iz-web/src/boot.rs @@ -35,6 +35,10 @@ const DEFAULT_KEY_PREFIX: &str = "IZ"; pub async fn serve(config_path: &Path) -> iz_core::Result<()> { let config = Config::load(config_path)?; let listen = config.listen; + // One server per data directory: the lock is held until this function returns, so a second `iz` + // (or an operator command) refuses to touch the same files while this one runs. + std::fs::create_dir_all(&config.data_dir)?; + let _lock = crate::cli::lock_data_dir(&config.data_dir).map_err(iz_core::Error::Config)?; let state = open_state(config).await?; let listener = TcpListener::bind(listen).await.map_err(|error| { @@ -52,6 +56,9 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> { directory::spawn(state.clone(), stop_rx.clone()); attachments::spawn(state.clone(), stop_rx.clone()); crate::mail::spawn(state.clone(), stop_rx.clone()); + crate::family::spawn(state.clone(), stop_rx.clone()); + crate::backup::spawn(state.clone(), stop_rx.clone()); + crate::sweeper::spawn(state.clone(), stop_rx.clone()); tokio::spawn(async move { shutdown_signal().await; tracing::info!("shutdown signal received"); @@ -103,6 +110,7 @@ async fn open_state(config: Config) -> iz_core::Result { key: Arc::new(key), live: Arc::new(LiveHub::default()), oidc, + family: Arc::default(), }) } @@ -179,6 +187,7 @@ mod tests { key: Arc::new(key), live: Arc::new(LiveHub::default()), oidc: None, + family: Arc::default(), }; (dir, state) } diff --git a/crates/iz-web/src/cli/export.rs b/crates/iz-web/src/cli/export.rs new file mode 100644 index 0000000..90c2b26 --- /dev/null +++ b/crates/iz-web/src/cli/export.rs @@ -0,0 +1,291 @@ +//! `iz export --out `: writes the board to a new directory so it can be read or kept without the +//! database. +//! +//! The directory holds `board.json` (the board, its tasks, assignees, dependencies, comments, activity, +//! attachment metadata and the members named by those rows), `attachments/` for every attachment whose +//! bytes are on this disk, and `manifest.json` for all of them. An attachment whose bytes are elsewhere +//! (location `in`) or that is moving is listed with `"bytes": false`; the export then exits 1 after writing +//! everything else, so an incomplete export is never silent. The output is refused unless `--out` is missing +//! or an empty directory, and no path in it is built from anything but fixed names and validated ULIDs. No +//! symlink is created, and nothing is written outside `--out`. + +use std::fs::{DirBuilder, OpenOptions}; +use std::io::{Read, Write}; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; +use std::path::Path; +use std::process::ExitCode; + +use iz_core::config::Config; +use iz_core::manifest::write_manifest; +use iz_core::staging::blob_path; +use iz_core::store::export::{AttachmentRow, ReadOnly}; +use iz_core::time::now_stamp; +use sha2::{Digest, Sha256}; + +use super::{database_file, describe, existing_data_dir, fail, take_lock}; + +/// The file that holds the board. +const BOARD_FILE: &str = "board.json"; +/// The directory inside `--out` that holds the attachment bytes. +const ATTACHMENTS_DIR: &str = "attachments"; +/// Read chunk for copying bytes. Reason: keeps memory flat for large attachments. +const CHUNK: usize = 64 * 1024; + +/// Runs the export and maps its outcome to an exit status. +pub async fn run(config_path: &Path, out: &Path) -> ExitCode { + let config = match Config::load(config_path) { + Ok(config) => config, + Err(error) => return fail(describe(&error)), + }; + let data_dir = match existing_data_dir(&config) { + Ok(dir) => dir, + Err(message) => return fail(message), + }; + let _lock = match take_lock(&data_dir) { + Ok(lock) => lock, + Err(code) => return code, + }; + if let Err(message) = prepare_out(out) { + return fail(message); + } + match write_export(&config, &data_dir, out).await { + Ok(report) => { + println!( + "exported {} attachments with bytes and {} without to {}", + report.with_bytes, + report.without_bytes.len(), + out.display() + ); + if report.without_bytes.is_empty() { + return ExitCode::SUCCESS; + } + for (id, reason) in &report.without_bytes { + eprintln!("iz: attachment {id} has no bytes in the export: {reason}"); + } + eprintln!( + "iz: the export is incomplete; {} attachments have no bytes", + report.without_bytes.len() + ); + ExitCode::FAILURE + } + Err(message) => fail(message), + } +} + +/// What an export wrote, for the summary. +struct Report { + /// Attachments whose bytes are in the export. + with_bytes: usize, + /// Attachments whose bytes are not, with the reason. + without_bytes: Vec<(String, String)>, +} + +/// Makes `out` a new directory with mode 0700, or accepts an existing empty one. A link or a file is +/// refused, and so is a directory with anything in it. +fn prepare_out(out: &Path) -> Result<(), String> { + match std::fs::symlink_metadata(out) { + Ok(meta) => { + if !meta.file_type().is_dir() { + return Err(format!("{} exists and is not a directory", out.display())); + } + let mut entries = std::fs::read_dir(out) + .map_err(|error| format!("cannot read {}: {error}", out.display()))?; + if entries.next().is_some() { + return Err(format!("{} is not empty", out.display())); + } + Ok(()) + } + Err(_) => DirBuilder::new() + .mode(0o700) + .create(out) + .map_err(|error| format!("cannot create {}: {error}", out.display())), + } +} + +/// Reads the database and writes the export. Every failure before the manifest leaves the directory +/// partly written; the caller reports it and the operator removes it. +async fn write_export(config: &Config, data_dir: &Path, out: &Path) -> Result { + let database = database_file(config)?; + let db = ReadOnly::open(&database) + .await + .map_err(|error| describe(&error))?; + let board_ids = db.board_ids().await.map_err(|error| describe(&error))?; + let [board_id] = board_ids.as_slice() else { + return Err(format!( + "expected one board in the database, found {}", + board_ids.len() + )); + }; + let dump = db + .export_board(board_id) + .await + .map_err(|error| describe(&error))?; + let rows = db + .board_attachment_rows(board_id) + .await + .map_err(|error| describe(&error))?; + + DirBuilder::new() + .mode(0o700) + .recursive(true) + .create(out.join(ATTACHMENTS_DIR)) + .map_err(|error| format!("cannot create the attachments directory: {error}"))?; + let mut written = vec![BOARD_FILE.to_owned()]; + let mut attachments = Vec::with_capacity(rows.len()); + let mut report = Report { + with_bytes: 0, + without_bytes: Vec::new(), + }; + for row in &rows { + // The id is used in two file names, so it must be the canonical ULID text, or it is refused. + let source = blob_path(data_dir, &row.id).map_err(|error| describe(&error))?; + let mut entry = attachment_json(row); + if row.location == "local" { + match copy_blob(&source, &out.join(ATTACHMENTS_DIR).join(&row.id), row)? { + Ok(()) => { + let relative = format!("{ATTACHMENTS_DIR}/{}", row.id); + entry["bytes"] = serde_json::Value::Bool(true); + entry["file"] = serde_json::Value::String(relative.clone()); + written.push(relative); + report.with_bytes += 1; + } + Err(reason) => { + entry["bytes"] = serde_json::Value::Bool(false); + report.without_bytes.push((row.id.clone(), reason)); + } + } + } else { + entry["bytes"] = serde_json::Value::Bool(false); + report.without_bytes.push(( + row.id.clone(), + format!( + "location is {}, the bytes are not on this disk", + row.location + ), + )); + } + attachments.push(entry); + } + + let members = dump.members; + let board = serde_json::json!({ + "format": "iz-export", + "version": 1, + "exported_at": now_stamp(), + "board": dump.board, + "columns": dump.columns, + "tags": dump.tags, + "tasks": dump.tasks, + "assignees": dump.assignees, + "dependencies": dump.dependencies, + "comments": dump.comments, + "activity": dump.activity, + "attachments": attachments, + "members": members, + }); + let bytes = serde_json::to_vec_pretty(&board) + .map_err(|error| format!("encoding {BOARD_FILE}: {error}"))?; + write_new(&out.join(BOARD_FILE), &bytes)?; + + write_manifest(out, &now_stamp(), env!("IZ_BUILD_SHA"), &written) + .map_err(|error| describe(&error))?; + Ok(report) +} + +/// The metadata of an attachment row as the export file states it. +fn attachment_json(row: &AttachmentRow) -> serde_json::Value { + serde_json::json!({ + "id": row.id, + "task_id": row.task_id, + "name": row.name, + "mime": row.mime, + "size": row.size, + "sha256": row.sha256, + "uploaded_by": row.uploaded_by, + "created_at": row.created_at, + "location": row.location, + }) +} + +/// Copies the bytes of a local attachment to `dest` (created new, mode 0600) and checks that they have the +/// size and digest of the row. The source must be a regular file. On a mismatch the copy is removed and the +/// reason is returned as the inner error; the outer error is a failure to write. +fn copy_blob( + source: &Path, + dest: &Path, + row: &AttachmentRow, +) -> Result, String> { + let meta = match std::fs::symlink_metadata(source) { + Ok(meta) => meta, + Err(_) => return Ok(Err("the bytes are missing from the store".into())), + }; + if !meta.file_type().is_file() { + return Ok(Err("the stored entry is not a regular file".into())); + } + let mut input = std::fs::File::open(source) + .map_err(|error| format!("cannot read {}: {error}", source.display()))?; + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(dest) + .map_err(|error| format!("cannot create {}: {error}", dest.display()))?; + let mut hasher = Sha256::new(); + let mut size: u64 = 0; + let mut buffer = vec![0u8; CHUNK]; + loop { + let read = input + .read(&mut buffer) + .map_err(|error| format!("cannot read {}: {error}", source.display()))?; + if read == 0 { + break; + } + output + .write_all(&buffer[..read]) + .map_err(|error| format!("cannot write {}: {error}", dest.display()))?; + hasher.update(&buffer[..read]); + size += read as u64; + } + output + .sync_all() + .map_err(|error| format!("cannot sync {}: {error}", dest.display()))?; + let digest = hex::encode(hasher.finalize()); + if size != row.size || digest != row.sha256 { + drop(output); + std::fs::remove_file(dest) + .map_err(|error| format!("cannot remove {}: {error}", dest.display()))?; + return Ok(Err( + "the bytes do not match the recorded size or digest".into() + )); + } + Ok(Ok(())) +} + +/// Writes a new file with mode 0600 and syncs it. Used for `board.json`. +fn write_new(path: &Path, bytes: &[u8]) -> Result<(), String> { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .map_err(|error| format!("cannot create {}: {error}", path.display()))?; + file.write_all(bytes) + .and_then(|()| file.sync_all()) + .map_err(|error| format!("cannot write {}: {error}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn export_refuses_a_non_empty_out_directory() { + let dir = tempfile::tempdir().expect("temp dir"); + std::fs::write(dir.path().join("keep.txt"), b"x").expect("seed file"); + let error = prepare_out(dir.path()).expect_err("non-empty must be refused"); + assert!(error.contains("is not empty"), "got: {error}"); + let empty = dir.path().join("fresh"); + prepare_out(&empty).expect("a missing directory is created"); + assert!(empty.is_dir()); + } +} diff --git a/crates/iz-web/src/cli/fsck.rs b/crates/iz-web/src/cli/fsck.rs new file mode 100644 index 0000000..bb9b54a --- /dev/null +++ b/crates/iz-web/src/cli/fsck.rs @@ -0,0 +1,314 @@ +//! `iz fsck`: a read-only check of the database and the attachments. +//! +//! It checks: `integrity_check` returns `ok`; the migration history is contiguous and known to this build; +//! every attachment row with location `local` has its file at the expected path, a regular file whose size +//! and SHA-256 match the row; no row is stuck in `moving`; and every file in `attachments/` is named by a +//! row (unnamed files are reported, not deleted). Rows with location `in` are counted, not checked: their +//! bytes are in another service. The database is opened read-only and never migrated. The lock file is the +//! only thing it may create. Exit status 0 when nothing is wrong, 1 when anything is. + +use std::collections::HashSet; +use std::path::Path; +use std::process::ExitCode; + +use iz_core::config::Config; +use iz_core::manifest::digest_file; +use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; +use iz_core::store::export::{ReadOnly, migrations_problem}; + +use super::{database_file, describe, existing_data_dir, fail, take_lock}; + +/// Runs the check, prints the report, and maps the outcome to an exit status. +pub async fn run(config_path: &Path) -> ExitCode { + let config = match Config::load(config_path) { + Ok(config) => config, + Err(error) => return fail(describe(&error)), + }; + let data_dir = match existing_data_dir(&config) { + Ok(dir) => dir, + Err(message) => return fail(message), + }; + let _lock = match take_lock(&data_dir) { + Ok(lock) => lock, + Err(code) => return code, + }; + let mut report = Report::default(); + check(&config, &data_dir, &mut report).await; + for line in &report.lines { + println!("{line}"); + } + if report.problems == 0 { + println!("fsck: clean"); + ExitCode::SUCCESS + } else { + println!("fsck: {} problems found", report.problems); + ExitCode::FAILURE + } +} + +/// The lines of the report and how many of them are problems. +#[derive(Default)] +struct Report { + /// Every line printed, in order. + lines: Vec, + /// How many lines are problems (the exit status depends on it). + problems: usize, +} + +impl Report { + /// Records a line that is fine. + fn ok(&mut self, text: impl Into) { + self.lines.push(format!("ok: {}", text.into())); + } + + /// Records a line that is a problem. + fn problem(&mut self, text: impl Into) { + self.problems += 1; + self.lines.push(format!("problem: {}", text.into())); + } +} + +/// Runs every check. Nothing here writes to the data directory. +async fn check(config: &Config, data_dir: &Path, report: &mut Report) { + let attachments_dir = data_dir.join(ATTACHMENTS_DIR); + let database = match database_file(config) { + Ok(path) => path, + Err(message) => { + report.problem(message); + return; + } + }; + let db = match ReadOnly::open(&database).await { + Ok(db) => db, + Err(error) => { + report.problem(format!("cannot open the database: {}", describe(&error))); + return; + } + }; + match db.integrity_check().await { + Ok(rows) if rows == ["ok"] => report.ok("database integrity_check"), + Ok(rows) => report.problem(format!("integrity_check: {}", rows.join("; "))), + Err(error) => report.problem(format!("integrity_check failed: {}", describe(&error))), + } + match db.migration_versions().await { + Ok(versions) => match migrations_problem(&versions) { + None => report.ok(format!("migrations 1 to {} are contiguous", versions.len())), + Some(problem) => report.problem(problem), + }, + Err(error) => report.problem(format!("cannot read migrations: {}", describe(&error))), + } + let rows = match db.attachment_rows().await { + Ok(rows) => rows, + Err(error) => { + report.problem(format!("cannot read attachments: {}", describe(&error))); + return; + } + }; + + let known: HashSet<&str> = rows.iter().map(|row| row.id.as_str()).collect(); + let mut local_ok = 0usize; + let mut elsewhere = 0usize; + for row in &rows { + match row.location.as_str() { + "local" => {} + "in" => { + elsewhere += 1; + continue; + } + other => { + report.problem(format!( + "attachment {} is in location {other}; a move did not finish", + row.id + )); + continue; + } + } + let path = match blob_path(data_dir, &row.id) { + Ok(path) => path, + Err(_) => { + report.problem(format!("attachment id {} is not a canonical ULID", row.id)); + continue; + } + }; + match std::fs::symlink_metadata(&path) { + Err(_) => { + report.problem(format!( + "attachment {} has no file at {}", + row.id, + path.display() + )); + continue; + } + Ok(meta) if !meta.file_type().is_file() => { + report.problem(format!("attachment {} is not a regular file", row.id)); + continue; + } + Ok(_) => {} + } + match digest_file(&path) { + Ok((size, _)) if size != row.size => report.problem(format!( + "attachment {} is {size} bytes, the row says {}", + row.id, row.size + )), + Ok((_, digest)) if digest != row.sha256 => { + report.problem(format!("attachment {} fails its sha256", row.id)); + } + Ok(_) => local_ok += 1, + Err(error) => report.problem(format!( + "attachment {} cannot be read: {}", + row.id, + describe(&error) + )), + } + } + report.ok(format!( + "{local_ok} local attachments match their rows; {elsewhere} are held elsewhere and not checked" + )); + + // Files in the attachments directory that no row names. They are reported; nothing is deleted. + match std::fs::read_dir(&attachments_dir) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if local_ok > 0 { + report.problem("the attachments directory does not exist".to_owned()); + } + } + Err(error) => report.problem(format!("cannot list the attachments directory: {error}")), + Ok(entries) => { + let mut unnamed = 0usize; + for entry in entries { + let Ok(entry) = entry else { + report.problem("cannot read an entry of the attachments directory".to_owned()); + continue; + }; + let name = entry.file_name().to_string_lossy().into_owned(); + if !known.contains(name.as_str()) { + unnamed += 1; + report.problem(format!("file {name} in attachments is named by no row")); + } + } + if unnamed == 0 { + report.ok("every file in attachments is named by a row"); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use iz_core::authz::Role; + use iz_core::store::members::DirectoryMember; + + /// An attachment whose bytes were edited after the row was written must be reported. The check runs + /// on a real database file built by the store, in a temp directory. + #[tokio::test] + async fn fsck_reports_an_edited_attachment() { + let root = tempfile::tempdir().expect("temp dir"); + let data = root.path().join("data"); + std::fs::create_dir_all(&data).expect("data dir"); + let db_path = data.join("iz.db"); + let store = iz_core::store::Store::open(&db_path).await.expect("store"); + let (board_id, task_id, member) = seed_task(&store).await; + let id = iz_core::store::new_id(); + let bytes = b"original attachment bytes"; + let sha256 = hex::encode(::digest(bytes)); + store + .add_attachment( + &board_id, + &task_id, + iz_core::store::attachments::NewAttachment { + id: id.clone(), + name: "note.txt".into(), + mime: "text/plain".into(), + size: bytes.len() as u64, + sha256, + uploaded_by: member, + }, + ) + .await + .expect("row"); + let blob = blob_path(&data, &id).expect("path"); + std::fs::create_dir_all(blob.parent().expect("parent")).expect("attachments dir"); + std::fs::write(&blob, bytes).expect("bytes"); + drop(store); + + let config = Config::parse(&format!( + "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", + db_path.display(), + data.display(), + )) + .expect("config"); + let mut clean = Report::default(); + check( + &config, + &data.canonicalize().expect("canonical"), + &mut clean, + ) + .await; + assert_eq!( + clean.problems, 0, + "untouched data is clean: {:?}", + clean.lines + ); + + std::fs::write(&blob, b"edited attachment bytes!").expect("edit"); + let mut dirty = Report::default(); + check( + &config, + &data.canonicalize().expect("canonical"), + &mut dirty, + ) + .await; + assert!( + dirty.problems > 0, + "the edit is reported: {:?}", + dirty.lines + ); + assert!( + dirty.lines.iter().any(|line| line.contains(&id)), + "the report names the attachment: {:?}", + dirty.lines + ); + } + + /// One board, one task and the member who makes it. Returns (board id, task id, member sub). + async fn seed_task(store: &iz_core::store::Store) -> (String, String, String) { + let board = store.ensure_board("IZ").await.expect("board"); + let member = DirectoryMember { + sub: "ada".into(), + email: "ada@example.com".into(), + name: "Ada".into(), + im_admin: false, + disabled: false, + locale: None, + zoneinfo: "UTC".into(), + picture_version: 0, + }; + store + .apply_directory_member(&member, Role::Admin) + .await + .expect("member"); + let member = member.sub; + let columns = store.columns(&board.id).await.expect("columns"); + let tags = store.tags(&board.id).await.expect("tags"); + let task = store + .create_task( + &board.id, + iz_core::store::tasks::NewTask { + title: "Task".into(), + description: String::new(), + column_id: columns[0].id.clone(), + tag_id: tags[0].id.clone(), + deadline: None, + meeting_at: None, + assignees: Vec::new(), + parent_id: None, + link: None, + }, + &member, + ) + .await + .expect("task"); + (board.id, task.id, member) + } +} diff --git a/crates/iz-web/src/cli/mod.rs b/crates/iz-web/src/cli/mod.rs new file mode 100644 index 0000000..c6f47b9 --- /dev/null +++ b/crates/iz-web/src/cli/mod.rs @@ -0,0 +1,175 @@ +//! The operator command line: the words `iz` takes after its options, the lock that keeps two processes off +//! one data directory, and the helpers the commands share. +//! +//! Commands: `iz [--config ] [serve]` runs the server (a bare `iz` does the same), `export --out ` +//! writes the board to a new directory, `restore --from ` replaces the database and attachments +//! with a verified backup set, and `fsck` checks the database and attachments without changing them. The +//! configuration file is the `--config` path, then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is +//! success, 1 a failure, 2 a usage error. +//! +//! The lock: every command that touches the data directory takes an exclusive lock on `iz.lock` inside it, +//! held for the life of the process. A second process that finds the lock taken stops at once. What it is +//! not: the lock does not protect the files from other users; the data directory is mode 0700 for that. + +pub mod export; +pub mod fsck; +pub mod restore; + +use std::fs::{File, OpenOptions, TryLockError}; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use clap::{Parser, Subcommand}; +use iz_core::config::Config; + +/// The file inside the data directory that carries the process lock. +pub const LOCK_FILE: &str = "iz.lock"; + +/// The line printed when another process holds the lock. Operators search for it, so it is fixed. +pub const BUSY_MESSAGE: &str = "iz is already running on this data directory; stop it (systemctl stop iz) before running this command"; + +/// The configuration file when neither `--config` nor `IZ_CONFIG` names one. +pub const DEFAULT_CONFIG: &str = "config/iz.toml"; + +/// The environment variable that names the configuration file. +pub const CONFIG_ENV: &str = "IZ_CONFIG"; + +/// The parsed command line. `--config` is global, so it works before or after the command word. +#[derive(Debug, Parser)] +#[command( + name = "iz", + about = "The iz task board: the server and its operator commands" +)] +pub struct Cli { + /// The configuration file. Without it, `IZ_CONFIG`, then `config/iz.toml`. + #[arg(long, global = true, value_name = "PATH")] + pub config: Option, + /// What to do. Without a command the server runs. + #[command(subcommand)] + pub command: Option, +} + +/// The commands. `Serve` is the default. +#[derive(Debug, Subcommand)] +pub enum Command { + /// Runs the server until SIGTERM or Ctrl-C. + Serve, + /// Writes the board, its attachments and a manifest into a new directory. + Export { + /// The directory to create. It must not exist or must be empty. + #[arg(long, value_name = "DIR")] + out: PathBuf, + }, + /// Replaces the database and attachments with a verified backup set. The previous files are kept. + Restore { + /// The backup set directory: `manifest.json` and the files it lists. + #[arg(long, value_name = "DIR")] + from: PathBuf, + }, + /// Checks the database and the attachments without changing anything. + Fsck, +} + +/// The configuration path: the flag, else `IZ_CONFIG`, else the default. +pub fn config_path(flag: Option) -> PathBuf { + flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from)) + .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG)) +} + +/// Takes the exclusive lock on `data_dir/iz.lock`. The returned file holds the lock until it is dropped, +/// so bind it to a variable that lives as long as the work does. A busy lock gives [`BUSY_MESSAGE`]; any +/// other failure names the lock file. +pub fn lock_data_dir(data_dir: &Path) -> Result { + let path = data_dir.join(LOCK_FILE); + // Mode 0600: only this user reads the lock file. `truncate(false)` keeps whatever the file holds. + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(&path) + .map_err(|error| format!("iz: cannot open the lock file {}: {error}", path.display()))?; + match file.try_lock() { + Ok(()) => Ok(file), + Err(TryLockError::WouldBlock) => Err(BUSY_MESSAGE.to_owned()), + Err(TryLockError::Error(error)) => { + Err(format!("iz: cannot lock {}: {error}", path.display())) + } + } +} + +/// Prints the failure of [`lock_data_dir`] and gives the exit status 1. +pub fn take_lock(data_dir: &Path) -> Result { + lock_data_dir(data_dir).map_err(|message| { + eprintln!("{message}"); + ExitCode::FAILURE + }) +} + +/// Prints `iz: ` to stderr and gives the exit status 1. +pub fn fail(message: impl std::fmt::Display) -> ExitCode { + eprintln!("iz: {message}"); + ExitCode::FAILURE +} + +/// The text of an iz-core error for the user. A refused set or an invalid value is shown as its text +/// alone; everything else keeps its prefix. +pub fn describe(error: &iz_core::Error) -> String { + match error { + iz_core::Error::Invalid(text) | iz_core::Error::Conflict(text) => text.clone(), + other => other.to_string(), + } +} + +/// The data directory as an absolute path. It must exist: the commands that call this never create it. +pub fn existing_data_dir(config: &Config) -> Result { + config.data_dir.canonicalize().map_err(|error| { + format!( + "the data directory {} cannot be used: {error}", + config.data_dir.display() + ) + }) +} + +/// The database path, checked to be a regular file that is not a link. Nothing is created. +pub fn database_file(config: &Config) -> Result { + let meta = std::fs::symlink_metadata(&config.database).map_err(|error| { + format!( + "the database {} cannot be read: {error}", + config.database.display() + ) + })?; + if !meta.file_type().is_file() { + return Err(format!( + "the database {} is not a regular file", + config.database.display() + )); + } + Ok(config.database.clone()) +} + +/// A UTC stamp that is safe in a file name: `20261028T093015Z`. +pub fn file_stamp() -> String { + jiff::Timestamp::now() + .strftime("%Y%m%dT%H%M%SZ") + .to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_held_lock_is_refused_and_released_on_drop() { + let dir = tempfile::tempdir().expect("temp dir"); + let first = lock_data_dir(dir.path()).expect("first lock"); + assert_eq!( + lock_data_dir(dir.path()).err().as_deref(), + Some(BUSY_MESSAGE) + ); + drop(first); + lock_data_dir(dir.path()).expect("lock after release"); + } +} diff --git a/crates/iz-web/src/cli/restore.rs b/crates/iz-web/src/cli/restore.rs new file mode 100644 index 0000000..6b6ece3 --- /dev/null +++ b/crates/iz-web/src/cli/restore.rs @@ -0,0 +1,457 @@ +//! `iz restore --from `: replaces the database and the attachments with a verified backup set. +//! +//! Order: verify the set with `manifest::verify_set`; check that the configured database is a regular file +//! inside the data directory; copy the set's `iz.db` and attachments into a staging directory inside the data +//! directory and check each copy against the manifest; run `integrity_check` and the migration check on the +//! staged database. Nothing outside the staging directory changes until then. Only after that are the current +//! `iz.db`, `iz.db-wal`, `iz.db-shm` and `attachments` moved aside under a UTC stamp (kept, never deleted) and +//! the staged files moved into place. If a move fails, the moves made so far are undone. +//! +//! Every path is joined from the data directory and fixed names; the only names taken from the set are the +//! ones `verify_set` checked, and they are used only after they parse as canonical ULIDs. + +use std::fs::{DirBuilder, Permissions}; +use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use iz_core::config::Config; +use iz_core::manifest::{self, Manifest}; +use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; +use iz_core::store::export::{ReadOnly, migrations_problem}; +use iz_core::store::new_id; + +use super::{describe, existing_data_dir, fail, file_stamp, take_lock}; + +/// The database file name inside a backup set. Fixed: the set writer uses this name too. +const SET_DB: &str = "iz.db"; +/// The directory name prefix of the staging directory inside the data directory. +const STAGING_PREFIX: &str = "restore-staging-"; + +/// Runs the restore and maps its outcome to an exit status. +pub async fn run(config_path: &Path, from: &Path) -> ExitCode { + let config = match Config::load(config_path) { + Ok(config) => config, + Err(error) => return fail(describe(&error)), + }; + if let Err(error) = std::fs::create_dir_all(&config.data_dir) + .and_then(|()| std::fs::set_permissions(&config.data_dir, Permissions::from_mode(0o700))) + { + return fail(format!( + "the data directory {} cannot be created: {error}", + config.data_dir.display() + )); + } + let data_dir = match existing_data_dir(&config) { + Ok(dir) => dir, + Err(message) => return fail(message), + }; + let _lock = match take_lock(&data_dir) { + Ok(lock) => lock, + Err(code) => return code, + }; + match restore(&config, &data_dir, from).await { + Ok(summary) => { + println!("{summary}"); + ExitCode::SUCCESS + } + Err(message) => fail(message), + } +} + +/// A canonical ULID name from a set. `None` for anything else, so a name is used only when it is the +/// exact text the store would have written. +fn canonical_id(name: &str) -> Option { + // `blob_path` accepts exactly the canonical ULID text, so it is the one check for ids. + blob_path(Path::new("."), name) + .ok() + .map(|_| name.to_owned()) +} + +/// The files a restore takes from a set: `iz.db`, and `attachments/` for each canonical id. Any other +/// listed file is refused, so a set cannot smuggle a file into the data directory. +fn plan_set(manifest: &Manifest) -> Result, String> { + let mut attachments = Vec::new(); + let mut has_db = false; + for file in &manifest.files { + if file.path == SET_DB { + has_db = true; + } else if let Some(id) = file + .path + .strip_prefix("attachments/") + .and_then(canonical_id) + { + attachments.push(id); + } else { + return Err(format!("the set lists an unexpected file: {}", file.path)); + } + } + if !has_db { + return Err(format!("the set has no {SET_DB}")); + } + Ok(attachments) +} + +/// The database path, joined from the canonical parent directory and the file name. Refused unless it is +/// inside the data directory and is not a link, so the restore cannot replace a file outside it. +fn database_target(config: &Config, data_dir: &Path) -> Result { + let name = config.database.file_name().ok_or_else(|| { + format!( + "the database path has no file name: {}", + config.database.display() + ) + })?; + let parent = config + .database + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + let parent = parent.canonicalize().map_err(|error| { + format!( + "the database directory {} cannot be used: {error}", + parent.display() + ) + })?; + if !parent.starts_with(data_dir) { + return Err(format!( + "the database {} is outside the data directory; restore refuses to replace it", + config.database.display() + )); + } + let target = parent.join(name); + if let Ok(meta) = std::fs::symlink_metadata(&target) + && !meta.file_type().is_file() + { + return Err(format!( + "the database {} is not a regular file", + target.display() + )); + } + Ok(target) +} + +/// Copies `source` to `dest` (created new, mode 0600), then checks the copy against the manifest entry +/// for `relative` so a set changed during the copy is refused. +fn copy_checked( + manifest: &Manifest, + relative: &str, + source: &Path, + dest: &Path, +) -> Result<(), String> { + let expected = manifest + .files + .iter() + .find(|file| file.path == relative) + .ok_or_else(|| format!("the set does not list {relative}"))?; + std::fs::copy(source, dest).map_err(|error| format!("cannot copy {relative}: {error}"))?; + std::fs::set_permissions(dest, Permissions::from_mode(0o600)) + .map_err(|error| format!("cannot set the mode of {}: {error}", dest.display()))?; + let (size, digest) = manifest::digest_file(dest) + .map_err(|error| format!("cannot read the copy of {relative}: {}", describe(&error)))?; + if size != expected.size || digest != expected.sha256 { + return Err(format!("the set changed while it was copied: {relative}")); + } + Ok(()) +} + +/// The staging directory and what it holds, so a failure can remove exactly what was made. +struct Staging { + dir: PathBuf, +} + +impl Staging { + /// Makes a new staging directory with a fresh name inside the data directory, mode 0700. + fn create(data_dir: &Path) -> Result { + let dir = data_dir.join(format!("{STAGING_PREFIX}{}", new_id())); + DirBuilder::new() + .mode(0o700) + .create(&dir) + .map_err(|error| format!("cannot create {}: {error}", dir.display()))?; + Ok(Staging { dir }) + } + + /// Removes the files a restore puts in the staging directory, then the directory. It removes only + /// regular files directly inside it and inside its `attachments` directory, and leaves anything else + /// in place. + fn discard(&self) { + let _ = remove_regular_files(&self.dir); + let attachments = self.dir.join(ATTACHMENTS_DIR); + let _ = remove_regular_files(&attachments); + let _ = std::fs::remove_dir(&attachments); + let _ = std::fs::remove_dir(&self.dir); + } +} + +/// Removes every regular file directly inside `dir`. Links and directories are not touched. +fn remove_regular_files(dir: &Path) -> std::io::Result<()> { + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + if entry.file_type()?.is_file() { + std::fs::remove_file(entry.path())?; + } + } + Ok(()) +} + +/// Checks the staged database: `integrity_check` says `ok` and the migrations are contiguous. Its sidecars +/// are removed when empty; a sidecar with bytes is refused. +async fn check_staged(staged_db: &Path) -> Result<(), String> { + { + let db = ReadOnly::open(staged_db) + .await + .map_err(|error| describe(&error))?; + let rows = db + .integrity_check() + .await + .map_err(|error| describe(&error))?; + if rows != ["ok"] { + return Err(format!( + "the set's database fails integrity_check: {}", + rows.join("; ") + )); + } + let versions = db + .migration_versions() + .await + .map_err(|error| describe(&error))?; + if let Some(problem) = migrations_problem(&versions) { + return Err(format!("the set's database is refused: {problem}")); + } + } + for suffix in ["-wal", "-shm"] { + let mut sidecar = staged_db.as_os_str().to_owned(); + sidecar.push(suffix); + let sidecar = PathBuf::from(sidecar); + match std::fs::symlink_metadata(&sidecar) { + Err(_) => {} + Ok(meta) if meta.len() == 0 => { + std::fs::remove_file(&sidecar) + .map_err(|error| format!("cannot remove {}: {error}", sidecar.display()))?; + } + Ok(meta) => { + return Err(format!( + "the staged database has {} bytes in {}", + meta.len(), + sidecar.display() + )); + } + } + } + Ok(()) +} + +/// The whole restore. Returns the summary line on success. +async fn restore(config: &Config, data_dir: &Path, from: &Path) -> Result { + let manifest = manifest::verify_set(from).map_err(|error| describe(&error))?; + let attachment_ids = plan_set(&manifest)?; + let db_target = database_target(config, data_dir)?; + let attachments_dir = data_dir.join(ATTACHMENTS_DIR); + if let Ok(meta) = std::fs::symlink_metadata(&attachments_dir) + && !meta.file_type().is_dir() + { + return Err(format!("{} is not a directory", attachments_dir.display())); + } + + // Stage and check everything first. A failure here removes the staging directory and changes nothing else. + let staging = Staging::create(data_dir)?; + let staged = stage(&staging, from, &manifest, &attachment_ids).await; + if let Err(message) = staged { + staging.discard(); + return Err(message); + } + + let stamp = file_stamp(); + let result = swap_into_place(&staging.dir, &db_target, data_dir, &stamp); + match result { + Ok(moved) => { + if let Err(error) = std::fs::remove_dir(&staging.dir) { + eprintln!( + "iz: the staging directory {} could not be removed: {error}", + staging.dir.display() + ); + } + Ok(format!( + "restored from {}: {} attachments; previous files kept as {}", + from.display(), + attachment_ids.len(), + moved.join(", ") + )) + } + Err(message) => { + staging.discard(); + Err(message) + } + } +} + +/// Copies the set's files into the staging directory and checks them. The staging directory always gets +/// an `attachments` directory, even when the set has none, so the swap is the same in both cases. +async fn stage( + staging: &Staging, + from: &Path, + manifest: &Manifest, + attachment_ids: &[String], +) -> Result<(), String> { + let staged_db = staging.dir.join(SET_DB); + copy_checked(manifest, SET_DB, &from.join(SET_DB), &staged_db)?; + let staged_attachments = staging.dir.join(ATTACHMENTS_DIR); + DirBuilder::new() + .mode(0o700) + .create(&staged_attachments) + .map_err(|error| format!("cannot create {}: {error}", staged_attachments.display()))?; + for id in attachment_ids { + let relative = format!("{ATTACHMENTS_DIR}/{id}"); + copy_checked( + manifest, + &relative, + &from.join(ATTACHMENTS_DIR).join(id), + &staged_attachments.join(id), + )?; + } + check_staged(&staged_db).await +} + +/// One move made by the swap, so it can be undone. +enum Move { + /// An existing file or directory moved aside, from, to. + Aside(PathBuf, PathBuf), + /// A staged file moved into place, from, to. + Placed(PathBuf, PathBuf), +} + +/// Moves the current database files and attachments aside, then the staged ones into place. Returns the +/// names the old files were kept under. If any move fails, the moves made so far are reversed. +fn swap_into_place( + staging: &Path, + db_target: &Path, + data_dir: &Path, + stamp: &str, +) -> Result, String> { + let attachments = data_dir.join(ATTACHMENTS_DIR); + let mut old: Vec<(PathBuf, PathBuf)> = Vec::new(); + for current in [ + db_target.to_path_buf(), + with_suffix(db_target, "-wal"), + with_suffix(db_target, "-shm"), + attachments.clone(), + ] { + if std::fs::symlink_metadata(¤t).is_ok() { + let aside = with_suffix(¤t, &format!(".{stamp}")); + if std::fs::symlink_metadata(&aside).is_ok() { + return Err(format!( + "{} already exists; nothing was changed", + aside.display() + )); + } + old.push((current, aside)); + } + } + let staged_db = staging.join(SET_DB); + let staged_attachments = staging.join(ATTACHMENTS_DIR); + + let mut done: Vec = Vec::new(); + let outcome = (|| -> std::io::Result<()> { + for (current, aside) in &old { + std::fs::rename(current, aside)?; + done.push(Move::Aside(current.clone(), aside.clone())); + } + std::fs::rename(&staged_db, db_target)?; + done.push(Move::Placed(staged_db.clone(), db_target.to_path_buf())); + std::fs::rename(&staged_attachments, &attachments)?; + done.push(Move::Placed( + staged_attachments.clone(), + attachments.clone(), + )); + std::fs::File::open(data_dir)?.sync_all() + })(); + + match outcome { + Ok(()) => Ok(old + .iter() + .map(|(_, aside)| aside.display().to_string()) + .collect()), + Err(error) => { + // Undo in reverse. A failure to undo is reported with the paths, so the operator can finish by hand. + let mut stuck = Vec::new(); + for step in done.into_iter().rev() { + // An aside file goes back to its original name; a placed file goes back to staging. + let undone = match &step { + Move::Aside(original, aside) => std::fs::rename(aside, original), + Move::Placed(staged, target) => std::fs::rename(target, staged), + }; + if let Err(undo_error) = undone { + stuck.push(undo_error.to_string()); + } + } + if stuck.is_empty() { + Err(format!("restore failed and was undone: {error}")) + } else { + Err(format!( + "restore failed: {error}; some moves could not be undone: {}", + stuck.join("; ") + )) + } + } + } +} + +/// `path` with `suffix` appended to its file name. +fn with_suffix(path: &Path, suffix: &str) -> PathBuf { + let mut text = path.as_os_str().to_owned(); + text.push(suffix); + PathBuf::from(text) +} + +#[cfg(test)] +mod tests { + use super::*; + use iz_core::manifest::write_manifest; + + /// A set with a file that a manifest does not list, or whose bytes changed after the manifest was + /// written, must not be restored: nothing in the data directory may change. + #[tokio::test] + async fn restore_refuses_a_tampered_set_and_changes_nothing() { + let root = tempfile::tempdir().expect("temp dir"); + let set = root.path().join("set"); + let data = root.path().join("data"); + std::fs::create_dir_all(&set).expect("set dir"); + std::fs::create_dir_all(&data).expect("data dir"); + let db = data.join("iz.db"); + std::fs::write(&db, b"current database").expect("current db"); + std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db"); + write_manifest( + &set, + "2026-10-28T00:00:00.000000000Z", + "test", + &[SET_DB.to_owned()], + ) + .expect("manifest"); + // Tamper after the manifest is written. + let mut bytes = std::fs::read(set.join(SET_DB)).expect("read"); + bytes[0] ^= 0x01; + std::fs::write(set.join(SET_DB), bytes).expect("tamper"); + + let config = Config::parse(&format!( + "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", + db.display(), + data.display(), + )) + .expect("config"); + let error = restore(&config, &data.canonicalize().expect("canonical"), &set) + .await + .expect_err("tampered set must be refused"); + assert!( + error.contains("changed since the set was written"), + "got: {error}" + ); + assert_eq!( + std::fs::read(&db).expect("db still there"), + b"current database" + ); + let entries: Vec<_> = std::fs::read_dir(&data) + .expect("list") + .map(|e| e.expect("entry").file_name()) + .collect(); + assert_eq!(entries.len(), 1, "only the database remains: {entries:?}"); + } +} diff --git a/crates/iz-web/src/family.rs b/crates/iz-web/src/family.rs new file mode 100644 index 0000000..5be58c3 --- /dev/null +++ b/crates/iz-web/src/family.rs @@ -0,0 +1,257 @@ +//! The family switcher list (contracts.md 4): `im`'s service registry, fetched with the service +//! token every five minutes and kept in memory. Pages read the copy through [`FamilyCache`]; they +//! never call `im` themselves. +//! +//! Every entry is checked before it is kept: a key of `[a-z0-9-]`, a name, and a URL that is `http` +//! or `https` only. Entries that fail are dropped one by one, so one bad row never hides the others. +//! A failed refresh keeps the last good list; a stale copy is fine (contracts.md 4). When OIDC is not +//! configured, the worker is not started and the list stays empty. + +use std::sync::RwLock; +use std::time::Duration; + +use reqwest::Url; +use serde_json::Value; +use tokio::sync::watch; + +use crate::oidc::{ImError, ImResult, OidcClient, read_limited}; +use crate::state::AppState; + +/// How often the list is fetched. Reason: contracts.md 4 says apps fetch every five minutes. +const REFRESH: Duration = Duration::from_secs(5 * 60); +/// Largest listing read from `im`, in bytes. Reason: a family has a few dozen services, so a real +/// listing is a few kilobytes; this bounds memory. +const LISTING_MAX_BYTES: usize = 64 * 1024; +/// Most services kept for the switcher. Reason: a bar with more links than this is not usable. +pub const MAX_SERVICES: usize = 20; +/// Longest service key, in characters. Reason: keys are short words such as `im` or `in`. +const KEY_MAX_CHARS: usize = 32; +/// Longest service name, in characters. Reason: the name is a link label in a narrow bar. +const NAME_MAX_CHARS: usize = 60; + +/// One service of the family, as the switcher shows it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Service { + /// The family key, such as `im`. Matched against the key of this app to mark the current one. + pub key: String, + /// The label shown in the switcher. + pub name: String, + /// The absolute `http` or `https` URL of the service. + pub url: String, + /// Whether the last health probe of `im` passed. + pub healthy: bool, +} + +/// The last good service list. Shared between the worker, which replaces it, and the pages, which +/// copy it out. +#[derive(Debug, Default)] +pub struct FamilyCache { + services: RwLock>, +} + +impl FamilyCache { + /// A copy of the list as it stands. Empty until the first successful fetch. + pub fn snapshot(&self) -> Vec { + self.services + .read() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + } + + /// Replaces the list. Only the worker calls this. + fn replace(&self, services: Vec) { + *self + .services + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = services; + } +} + +/// The listing of `im` (contracts.md 4). Entries stay raw values so that one bad entry does not +/// stop the rest. +#[derive(serde::Deserialize)] +struct Listing { + services: Vec, +} + +/// One entry as `im` sends it. Unknown fields are ignored. +#[derive(serde::Deserialize)] +struct WireService { + key: String, + name: String, + url: String, + #[serde(default)] + healthy: bool, +} + +/// Starts the worker. It fetches at once and then every [`REFRESH`], until the stop flag is set. +/// Does nothing when OIDC is not configured. +pub fn spawn(state: AppState, stop: watch::Receiver) { + let Some(oidc) = state.oidc.clone() else { + return; + }; + tokio::spawn(run(state, oidc, stop)); +} + +async fn run(state: AppState, oidc: std::sync::Arc, mut stop: watch::Receiver) { + loop { + match fetch(&oidc).await { + Ok(services) => { + tracing::debug!( + count = services.len(), + "family: the service list was refreshed" + ); + state.family.replace(services); + } + Err(error) => { + tracing::warn!(error = %error, "family: the service list could not be refreshed; keeping the last one"); + } + } + if wait_or_stop(REFRESH, &mut stop).await { + return; + } + } +} + +/// One fetch of the listing with the service token. +async fn fetch(oidc: &OidcClient) -> ImResult> { + let token = oidc.service_token().await?; + let url = format!("{}/api/v1/family", oidc.issuer()); + let response = oidc + .http() + .get(url) + .bearer_auth(token) + .send() + .await + .map_err(|e| ImError::Unavailable(e.to_string()))?; + if !response.status().is_success() { + return Err(ImError::BadResponse(format!( + "the family list answered {}", + response.status().as_u16() + ))); + } + let body = read_limited(response, LISTING_MAX_BYTES).await?; + parse_listing(&body).map_err(ImError::BadResponse) +} + +/// Reads a listing and keeps the entries that pass [`check_entry`], at most [`MAX_SERVICES`] of them. +/// Entries past the limit are dropped. +pub fn parse_listing(body: &[u8]) -> Result, String> { + let listing: Listing = + serde_json::from_slice(body).map_err(|e| format!("the family list: {e}"))?; + Ok(listing + .services + .into_iter() + .filter_map(check_entry) + .take(MAX_SERVICES) + .collect()) +} + +/// Turns one raw entry into a [`Service`], or `None` when it does not parse or fails a check. +fn check_entry(raw: Value) -> Option { + let wire: WireService = serde_json::from_value(raw).ok()?; + if !valid_key(&wire.key) || !valid_name(&wire.name) { + return None; + } + let url = Url::parse(&wire.url).ok()?; + if !matches!(url.scheme(), "http" | "https") { + return None; + } + Some(Service { + key: wire.key, + name: wire.name, + url: url.into(), + healthy: wire.healthy, + }) +} + +/// A key is 1 to 32 characters of lowercase letters, digits and hyphens. +fn valid_key(key: &str) -> bool { + let length = key.chars().count(); + (1..=KEY_MAX_CHARS).contains(&length) + && key + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') +} + +/// A name is 1 to 60 characters. +fn valid_name(name: &str) -> bool { + (1..=NAME_MAX_CHARS).contains(&name.chars().count()) +} + +/// Waits for `wait`, or returns `true` early when the stop flag is set. +async fn wait_or_stop(wait: Duration, stop: &mut watch::Receiver) -> bool { + tokio::select! { + _ = stop.wait_for(|stopped| *stopped) => true, + () = tokio::time::sleep(wait) => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_parser_drops_bad_entries_and_keeps_the_rest() { + let long_key = "k".repeat(KEY_MAX_CHARS + 1); + let long_name = "n".repeat(NAME_MAX_CHARS + 1); + let body = format!( + r#"{{"services":[ + {{"key":"im","name":"Account","url":"https://im.example.com","healthy":true,"checked_at":"x"}}, + {{"key":"ftp","name":"Files","url":"ftp://files.example.com"}}, + {{"key":"javascript","name":"Bad","url":"javascript:alert(1)"}}, + {{"key":"{long_key}","name":"Long key","url":"https://a.example.com"}}, + {{"key":"Upper","name":"Case","url":"https://b.example.com"}}, + {{"key":"in","name":"{long_name}","url":"https://c.example.com"}}, + {{"key":"iz","name":"Board","url":"http://iz.example.com/","healthy":false}} + ]}}"# + ); + let services = parse_listing(body.as_bytes()).expect("listing parses"); + let keys: Vec<&str> = services.iter().map(|s| s.key.as_str()).collect(); + assert_eq!(keys, ["im", "iz"]); + assert!(services[0].healthy); + assert!(!services[1].healthy); + assert_eq!(services[1].url, "http://iz.example.com/"); + } + + /// The switcher is left out of a page when the list is empty. The styled 404 page goes through + /// the shell, so it shows the topbar; the list is empty here because nothing has been fetched. + #[tokio::test] + async fn an_empty_list_renders_no_switcher() { + let dir = tempfile::tempdir().expect("temp dir"); + let text = format!( + "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", + dir.path().join("iz.db").display(), + dir.path().display(), + ); + let config = iz_core::config::Config::parse(&text).expect("test config"); + let store = iz_core::store::Store::open(&config.database) + .await + .expect("store"); + let state = AppState { + config: std::sync::Arc::new(config), + store, + key: std::sync::Arc::new([0u8; 32]), + live: std::sync::Arc::default(), + oidc: None, + family: std::sync::Arc::default(), + }; + let request = http::Request::get("/no/such/page") + .header(http::header::ACCEPT, "text/html") + .body(topcoat::router::Body::empty()) + .expect("request"); + let response = crate::boot::router(state).handle(request).await; + let body = topcoat::router::to_bytes(response.into_body(), 256 * 1024) + .await + .expect("body"); + let html = String::from_utf8_lossy(&body); + assert!( + html.contains("Page not found"), + "the styled 404, got: {html}" + ); + assert!( + !html.contains("class=\"switcher\""), + "no switcher, got: {html}" + ); + } +} diff --git a/crates/iz-web/src/i18n/mod.rs b/crates/iz-web/src/i18n/mod.rs index 6dd121d..6f93bc2 100644 --- a/crates/iz-web/src/i18n/mod.rs +++ b/crates/iz-web/src/i18n/mod.rs @@ -10,6 +10,7 @@ pub mod admin; pub mod board; pub mod shell; +pub mod structure; pub mod task; use topcoat::context::Cx; diff --git a/crates/iz-web/src/i18n/structure.rs b/crates/iz-web/src/i18n/structure.rs new file mode 100644 index 0000000..db8ab2a --- /dev/null +++ b/crates/iz-web/src/i18n/structure.rs @@ -0,0 +1,364 @@ +//! Strings of the structure and people pages: projects (`/tags`), columns (`/columns`), the members and +//! limits and server sections of `/settings`, and the person card (`/people/{sub}`). One variant per +//! phrase; `t` matches `(key, lang)` exhaustively, so a missing Turkish text does not compile. Values go +//! into sentences through `fill`, never by concatenation. + +use super::Lang; + +/// One phrase of the structure and people pages. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + /// Navigation: the projects tab. + NavTags, + /// Navigation: the columns tab. + NavColumns, + /// Projects page heading. + TagsTitle, + /// Projects page help text. + TagsHelp, + /// Heading of the add-project form. + TagsNew, + /// Label of the project name field. + TagName, + /// Label of the colour choice. + TagColour, + /// The choice of no colour. + TagNoColour, + /// Button that adds a project. + TagAdd, + /// Button that renames a project. + TagRename, + /// Button that saves a project's colour. + TagSaveColour, + /// Button that deletes a project. + TagDelete, + /// Badge of the default project. + TagDefault, + /// Button that moves a project towards the start. + TagMoveUp, + /// Button that moves a project towards the end. + TagMoveDown, + /// "{} cards" note for a project in use. + TagUsedBy, + /// Columns page heading. + ColumnsTitle, + /// Columns page help text. + ColumnsHelp, + /// Heading of the add-column form. + ColumnsNew, + /// Label of the column name field. + ColumnName, + /// Button that adds a column. + ColumnAdd, + /// Button that renames a column. + ColumnRename, + /// Button that retires a column (a soft delete). + ColumnRetire, + /// Button that moves a column towards the start. + ColumnMoveUp, + /// Button that moves a column towards the end. + ColumnMoveDown, + /// "{} cards" note for a column. + ColumnCards, + /// Badge of the done column. + ColumnDone, + /// Confirmation: a project was added. + NoticeTagAdded, + /// Confirmation: a project was renamed. + NoticeTagRenamed, + /// Confirmation: a project's colour was saved. + NoticeTagColoured, + /// Confirmation: a project was deleted. + NoticeTagDeleted, + /// Confirmation: a project was moved. + NoticeTagMoved, + /// Confirmation: a column was added. + NoticeColumnAdded, + /// Confirmation: a column was renamed. + NoticeColumnRenamed, + /// Confirmation: a column was moved. + NoticeColumnMoved, + /// Confirmation: a column was retired. + NoticeColumnRetired, + /// Confirmation: a member's role was saved. + NoticeRoleSet, + /// Confirmation: the limits were saved. + NoticeLimitsSaved, + /// Settings section: members and roles. + MembersHeading, + /// Help text of the members section. + MembersHelp, + /// Column header: name. + MemberName, + /// Column header: email address. + MemberEmail, + /// Column header: role. + MemberRole, + /// Column header: flags (directory admin, disabled). + MemberFlags, + /// Flag: the directory marks this person as an administrator. + MemberImAdmin, + /// Flag: the directory has disabled this person. + MemberDisabled, + /// Button that saves a role. + MemberSave, + /// Role word: admin. + RoleAdmin, + /// Role word: member. + RoleMember, + /// Role word: viewer. + RoleViewer, + /// Role word: none (no access). + RoleNone, + /// Settings section: limits. + LimitsHeading, + /// Help text of the limits section. + LimitsHelp, + /// Label of the attachment size limit. + LimitMib, + /// Label of the allowed attachment extensions. + LimitExtensions, + /// Button that saves the limits. + LimitsSave, + /// Settings section: server information. + ServerHeading, + /// Help text of the server section. + ServerHelp, + /// Row: public base URL. + ServerBase, + /// Row: listen address. + ServerListen, + /// Row: data directory. + ServerData, + /// Row: database file. + ServerDatabase, + /// Row: schema version. + ServerSchema, + /// Row: build. + ServerBuild, + /// Row: sign-in through im. + ServerSignIn, + /// Row: where attachments are stored. + ServerStorage, + /// Value: on. + On, + /// Value: off. + Off, + /// Value: attachments in the family's Files service. + StorageIn, + /// Value: attachments on this server's disk. + StorageLocal, + /// Person card: the role line, "{}" is the role word. + PersonRole, + /// Person card: count of open tasks. + PersonOpen, + /// Person card: count of finished tasks. + PersonDone, + /// Person card: count of created tasks. + PersonCreated, + /// Person card: count of comments. + PersonComments, + /// Person card: count of files. + PersonFiles, + /// Person card: heading of the recent activity. + PersonRecent, + /// Person card: no activity yet. + PersonNoActivity, + /// Person card: last sign-in label. + PersonLastSignIn, + /// Person card: never signed in. + PersonNeverSignedIn, + /// Person card: time zone label. + PersonZone, + /// Person card: back link to the board. + PersonBack, +} + +/// The text of `key` in `lang`. +pub fn t(lang: Lang, key: K) -> &'static str { + use Lang::{En, Tr}; + match (key, lang) { + (K::NavTags, En) => "Projects", + (K::NavTags, Tr) => "Projeler", + (K::NavColumns, En) => "Columns", + (K::NavColumns, Tr) => "Sütunlar", + (K::TagsTitle, En) => "Projects", + (K::TagsTitle, Tr) => "Projeler", + (K::TagsHelp, En) => { + "Projects group the cards. A project in use cannot be deleted; move its cards first." + } + (K::TagsHelp, Tr) => { + "Projeler kartları gruplar. Kullanımda olan bir proje silinemez; önce kartlarını taşıyın." + } + (K::TagsNew, En) => "New project", + (K::TagsNew, Tr) => "Yeni proje", + (K::TagName, En) => "Name", + (K::TagName, Tr) => "Ad", + (K::TagColour, En) => "Colour", + (K::TagColour, Tr) => "Renk", + (K::TagNoColour, En) => "No colour", + (K::TagNoColour, Tr) => "Renksiz", + (K::TagAdd, En) => "Add project", + (K::TagAdd, Tr) => "Proje ekle", + (K::TagRename, En) => "Rename", + (K::TagRename, Tr) => "Yeniden adlandır", + (K::TagSaveColour, En) => "Save colour", + (K::TagSaveColour, Tr) => "Rengi kaydet", + (K::TagDelete, En) => "Delete", + (K::TagDelete, Tr) => "Sil", + (K::TagDefault, En) => "default", + (K::TagDefault, Tr) => "varsayılan", + (K::TagMoveUp, En) => "Earlier", + (K::TagMoveUp, Tr) => "Yukarı", + (K::TagMoveDown, En) => "Later", + (K::TagMoveDown, Tr) => "AÅŸağı", + (K::TagUsedBy, En) => "{} cards", + (K::TagUsedBy, Tr) => "{} kart", + (K::ColumnsTitle, En) => "Columns", + (K::ColumnsTitle, Tr) => "Sütunlar", + (K::ColumnsHelp, En) => { + "Columns are the stages of the board. Retiring a column hides it; it is never deleted, so old activity keeps its name. The done column stays last." + } + (K::ColumnsHelp, Tr) => { + "Sütunlar panonun aÅŸamalarıdır. Bir sütunu emekli etmek onu gizler; asla silinmez, böylece eski etkinlik adını korur. Tamamlandı sütunu en sonda kalır." + } + (K::ColumnsNew, En) => "New column", + (K::ColumnsNew, Tr) => "Yeni sütun", + (K::ColumnName, En) => "Name", + (K::ColumnName, Tr) => "Ad", + (K::ColumnAdd, En) => "Add column", + (K::ColumnAdd, Tr) => "Sütun ekle", + (K::ColumnRename, En) => "Rename", + (K::ColumnRename, Tr) => "Yeniden adlandır", + (K::ColumnRetire, En) => "Retire", + (K::ColumnRetire, Tr) => "Emekliye ayır", + (K::ColumnMoveUp, En) => "Earlier", + (K::ColumnMoveUp, Tr) => "Yukarı", + (K::ColumnMoveDown, En) => "Later", + (K::ColumnMoveDown, Tr) => "AÅŸağı", + (K::ColumnCards, En) => "{} cards", + (K::ColumnCards, Tr) => "{} kart", + (K::ColumnDone, En) => "done", + (K::ColumnDone, Tr) => "tamamlandı", + (K::NoticeTagAdded, En) => "The project was added.", + (K::NoticeTagAdded, Tr) => "Proje eklendi.", + (K::NoticeTagRenamed, En) => "The project was renamed.", + (K::NoticeTagRenamed, Tr) => "Proje yeniden adlandırıldı.", + (K::NoticeTagColoured, En) => "The colour was saved.", + (K::NoticeTagColoured, Tr) => "Renk kaydedildi.", + (K::NoticeTagDeleted, En) => "The project was deleted.", + (K::NoticeTagDeleted, Tr) => "Proje silindi.", + (K::NoticeTagMoved, En) => "The project was moved.", + (K::NoticeTagMoved, Tr) => "Proje taşındı.", + (K::NoticeColumnAdded, En) => "The column was added.", + (K::NoticeColumnAdded, Tr) => "Sütun eklendi.", + (K::NoticeColumnRenamed, En) => "The column was renamed.", + (K::NoticeColumnRenamed, Tr) => "Sütun yeniden adlandırıldı.", + (K::NoticeColumnMoved, En) => "The column was moved.", + (K::NoticeColumnMoved, Tr) => "Sütun taşındı.", + (K::NoticeColumnRetired, En) => "The column was retired.", + (K::NoticeColumnRetired, Tr) => "Sütun emekliye ayrıldı.", + (K::NoticeRoleSet, En) => "The role was saved.", + (K::NoticeRoleSet, Tr) => "Rol kaydedildi.", + (K::NoticeLimitsSaved, En) => "The limits were saved.", + (K::NoticeLimitsSaved, Tr) => "Sınırlar kaydedildi.", + (K::MembersHeading, En) => "Members and roles", + (K::MembersHeading, Tr) => "Üyeler ve roller", + (K::MembersHelp, En) => { + "Admins manage the board. Members write. Viewers only read. None has no access. The last administrator cannot be demoted." + } + (K::MembersHelp, Tr) => { + "Yöneticiler panoyu yönetir. Üyeler yazar. Görüntüleyiciler yalnızca okur. Yok eriÅŸimi olmadığı anlamına gelir. Son yönetici düşürülemez." + } + (K::MemberName, En) => "Name", + (K::MemberName, Tr) => "Ad", + (K::MemberEmail, En) => "Email", + (K::MemberEmail, Tr) => "E-posta", + (K::MemberRole, En) => "Role", + (K::MemberRole, Tr) => "Rol", + (K::MemberFlags, En) => "Flags", + (K::MemberFlags, Tr) => "Durum", + (K::MemberImAdmin, En) => "admin in im", + (K::MemberImAdmin, Tr) => "im yöneticisi", + (K::MemberDisabled, En) => "disabled", + (K::MemberDisabled, Tr) => "devre dışı", + (K::MemberSave, En) => "Save role", + (K::MemberSave, Tr) => "Rolü kaydet", + (K::RoleAdmin, En) => "admin", + (K::RoleAdmin, Tr) => "yönetici", + (K::RoleMember, En) => "member", + (K::RoleMember, Tr) => "üye", + (K::RoleViewer, En) => "viewer", + (K::RoleViewer, Tr) => "görüntüleyici", + (K::RoleNone, En) => "none", + (K::RoleNone, Tr) => "yok", + (K::LimitsHeading, En) => "Limits", + (K::LimitsHeading, Tr) => "Sınırlar", + (K::LimitsHelp, En) => { + "Attachment size in MiB (1 to 500) and the extensions allowed, separated by spaces or commas. Reminder minutes are set in the mail section above." + } + (K::LimitsHelp, Tr) => { + "Ek boyutu MiB cinsinden (1 ile 500 arası) ve izin verilen uzantılar, boÅŸluk veya virgülle ayrılmış. Hatırlatma dakikaları yukarıdaki posta bölümünde." + } + (K::LimitMib, En) => "Attachment size limit (MiB)", + (K::LimitMib, Tr) => "Ek boyutu sınırı (MiB)", + (K::LimitExtensions, En) => "Allowed extensions", + (K::LimitExtensions, Tr) => "İzin verilen uzantılar", + (K::LimitsSave, En) => "Save limits", + (K::LimitsSave, Tr) => "Sınırları kaydet", + (K::ServerHeading, En) => "Server", + (K::ServerHeading, Tr) => "Sunucu", + (K::ServerHelp, En) => "Read-only. Changed in the configuration file and restarted.", + (K::ServerHelp, Tr) => { + "Salt okunur. Yapılandırma dosyasında deÄŸiÅŸtirilir ve yeniden baÅŸlatılır." + } + (K::ServerBase, En) => "Base address", + (K::ServerBase, Tr) => "Temel adres", + (K::ServerListen, En) => "Listen address", + (K::ServerListen, Tr) => "Dinleme adresi", + (K::ServerData, En) => "Data directory", + (K::ServerData, Tr) => "Veri dizini", + (K::ServerDatabase, En) => "Database file", + (K::ServerDatabase, Tr) => "Veritabanı dosyası", + (K::ServerSchema, En) => "Schema version", + (K::ServerSchema, Tr) => "Åžema sürümü", + (K::ServerBuild, En) => "Build", + (K::ServerBuild, Tr) => "Derleme", + (K::ServerSignIn, En) => "Sign-in through im", + (K::ServerSignIn, Tr) => "im ile giriÅŸ", + (K::ServerStorage, En) => "Attachment storage", + (K::ServerStorage, Tr) => "Ek depolama", + (K::On, En) => "on", + (K::On, Tr) => "açık", + (K::Off, En) => "off", + (K::Off, Tr) => "kapalı", + (K::StorageIn, En) => "Files service", + (K::StorageIn, Tr) => "Dosya hizmeti", + (K::StorageLocal, En) => "this server", + (K::StorageLocal, Tr) => "bu sunucu", + (K::PersonRole, En) => "Role: {}", + (K::PersonRole, Tr) => "Rol: {}", + (K::PersonOpen, En) => "Open tasks", + (K::PersonOpen, Tr) => "Açık kartlar", + (K::PersonDone, En) => "Finished tasks", + (K::PersonDone, Tr) => "Tamamlanan kartlar", + (K::PersonCreated, En) => "Created", + (K::PersonCreated, Tr) => "OluÅŸturulan", + (K::PersonComments, En) => "Comments", + (K::PersonComments, Tr) => "Yorumlar", + (K::PersonFiles, En) => "Files", + (K::PersonFiles, Tr) => "Dosyalar", + (K::PersonRecent, En) => "Recent activity", + (K::PersonRecent, Tr) => "Son etkinlik", + (K::PersonNoActivity, En) => "No activity yet.", + (K::PersonNoActivity, Tr) => "Henüz etkinlik yok.", + (K::PersonLastSignIn, En) => "Last sign-in", + (K::PersonLastSignIn, Tr) => "Son giriÅŸ", + (K::PersonNeverSignedIn, En) => "never", + (K::PersonNeverSignedIn, Tr) => "hiç", + (K::PersonZone, En) => "Time zone", + (K::PersonZone, Tr) => "Saat dilimi", + (K::PersonBack, En) => "Back to the board", + (K::PersonBack, Tr) => "Panoya dön", + } +} diff --git a/crates/iz-web/src/live.rs b/crates/iz-web/src/live.rs index 8973759..aeb02d2 100644 --- a/crates/iz-web/src/live.rs +++ b/crates/iz-web/src/live.rs @@ -62,6 +62,10 @@ pub enum AdminSection { Settings, /// The members and roles list. Members, + /// The projects and columns pages. + Structure, + /// The mail rules page. + Rules, } /// The change counters of all open topics. Cheap to share: every clone of the app state holds the diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index 5fc82a8..3fba85a 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -1,8 +1,8 @@ //! The `iz` binary: the command line, logging and the process lifetime. //! -//! `iz [--config ] [serve]` runs the server; a bare `iz` does the same. `iz admin ...` is the -//! operator command line, which is not built yet. The configuration file is the `--config` path, -//! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. +//! `iz [--config ] [serve]` runs the server; a bare `iz` does the same. `iz export`, `iz restore` and +//! `iz fsck` are the operator commands (see `cli`). The configuration file is the `--config` path, then +//! `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. // The page handlers nest many view and store futures; the default limit is too small for their types. #![recursion_limit = "256"] @@ -10,8 +10,11 @@ mod assets; mod attachments; mod auth; +mod backup; mod boot; +mod cli; mod directory; +mod family; mod health; mod i18n; mod live; @@ -21,50 +24,16 @@ mod pages; mod security; mod serve; mod state; +mod sweeper; mod views; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::ExitCode; +use clap::Parser; +use cli::{Cli, Command}; use tracing_subscriber::EnvFilter; -/// Printed with a usage error. -const USAGE: &str = "usage: iz [--config ] [serve]"; - -/// The configuration file when neither `--config` nor `IZ_CONFIG` names one. -const DEFAULT_CONFIG: &str = "config/iz.toml"; - -/// The environment variable that names the configuration file. -const CONFIG_ENV: &str = "IZ_CONFIG"; - -/// The parsed command line: the `--config` path and the positional words. -struct Cli { - config: Option, - words: Vec, -} - -/// Splits the arguments into the `--config ` pair and the positional words. -fn parse_args(args: impl Iterator) -> Result { - let mut config = None; - let mut words = Vec::new(); - let mut args = args; - while let Some(arg) = args.next() { - if arg == "--config" { - let path = args.next().ok_or("--config needs a path")?; - config = Some(PathBuf::from(path)); - } else { - words.push(arg); - } - } - Ok(Cli { config, words }) -} - -/// The configuration path: the flag, else `IZ_CONFIG`, else the default. -fn config_path(flag: Option) -> PathBuf { - flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from)) - .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG)) -} - /// Logs to stderr. The level comes from `RUST_LOG`, and defaults to `info`. fn init_logging() { let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); @@ -87,24 +56,21 @@ async fn serve(config: &Path) -> ExitCode { #[tokio::main] async fn main() -> ExitCode { - init_logging(); - let cli = match parse_args(std::env::args().skip(1)) { + let cli = match Cli::try_parse() { Ok(cli) => cli, - Err(message) => { - eprintln!("iz: {message}\n{USAGE}"); - return ExitCode::from(2); + Err(error) => { + // Help and version are not failures; a usage error is exit 2. + let code = if error.use_stderr() { 2 } else { 0 }; + let _ = error.print(); + return ExitCode::from(code); } }; - let words: Vec<&str> = cli.words.iter().map(String::as_str).collect(); - match words.as_slice() { - [] | ["serve"] => serve(&config_path(cli.config)).await, - ["admin", ..] => { - eprintln!("iz: admin commands are not implemented yet"); - ExitCode::from(2) - } - _ => { - eprintln!("iz: unknown command\n{USAGE}"); - ExitCode::from(2) - } + init_logging(); + let config = cli::config_path(cli.config); + match cli.command.unwrap_or(Command::Serve) { + Command::Serve => serve(&config).await, + Command::Export { out } => cli::export::run(&config, &out).await, + Command::Restore { from } => cli::restore::run(&config, &from).await, + Command::Fsck => cli::fsck::run(&config).await, } } diff --git a/crates/iz-web/src/pages/admin.rs b/crates/iz-web/src/pages/admin.rs index 6d8f9bc..12df691 100644 --- a/crates/iz-web/src/pages/admin.rs +++ b/crates/iz-web/src/pages/admin.rs @@ -13,8 +13,11 @@ use topcoat::router::response::Response; use crate::auth::CurrentMember; use crate::i18n::Lang; use crate::i18n::admin::{K, fill, t}; +use crate::i18n::structure::{K as StructureK, t as structure_t}; use crate::pages::task::core_err; +use crate::state::AppState; use crate::views::ViewerInfo; +use iz_core::store::audit::AuditEntry; /// The status of a page re-rendered with a refusal. pub const REFUSED: topcoat::router::StatusCode = topcoat::router::StatusCode::UNPROCESSABLE_ENTITY; @@ -50,6 +53,14 @@ pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option t(lang, K::NoticeRuleDeleted).to_owned(), "rule_switched" => t(lang, K::NoticeRuleSwitched).to_owned(), "retried" => t(lang, K::NoticeRetried).to_owned(), + "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(), + "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(), + "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => { + return crate::pages::tags::tag_notice(lang, code); + } + "column_added" | "column_renamed" | "column_moved" | "column_retired" => { + return crate::pages::columns::column_notice(lang, code); + } _ => return None, }; Some(text) @@ -67,3 +78,94 @@ pub struct CsrfForm { /// The session's CSRF token. pub csrf: String, } + +/// Writes one audit row for an administrator's write that has committed. The caller bumps the live +/// topic of its section; this only records who did what. Never fails the request. +pub async fn record( + state: &AppState, + me: &CurrentMember, + action: &'static str, + target_kind: &'static str, + target_id: Option<&str>, + data: serde_json::Value, +) { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action, + target_kind, + target_id, + ip: None, + data, + }) + .await; +} + +#[cfg(test)] +mod tests { + use http::header::{CONTENT_TYPE, COOKIE}; + use iz_core::authz::Role; + use topcoat::router::{Body, to_bytes}; + + use crate::boot::{router, test_state}; + use crate::pages::board::{cookie_of, sign_in_as}; + + /// Sends one request and returns the status code. + async fn status_of(state: &crate::state::AppState, request: http::Request) -> u16 { + let response = router(state.clone()).handle(request).await; + let status = response.status().as_u16(); + let _ = to_bytes(response.into_body(), 64 * 1024).await; + status + } + + /// A member, an anonymous visitor and a wrong-role user all get `404` for admin pages, never `403` or + /// a sign-in redirect that would show the page exists. + #[tokio::test] + async fn an_admin_page_is_a_404_for_members_and_anonymous_visitors() { + let (_dir, state) = test_state().await; + let (member, _) = sign_in_as(&state, "01MEMBERAAAAAAAAAAAAAAAAA", Role::Member).await; + for path in ["/settings", "/tags", "/columns", "/logs", "/rules"] { + let as_member = http::Request::get(path) + .header(COOKIE, cookie_of(&member)) + .body(Body::empty()) + .expect("request"); + assert_eq!(status_of(&state, as_member).await, 404, "member on {path}"); + let anonymous = http::Request::get(path) + .body(Body::empty()) + .expect("request"); + assert_eq!( + status_of(&state, anonymous).await, + 404, + "anonymous on {path}" + ); + } + } + + /// An administrator's write without the CSRF token is refused with `403` before any side effect. + #[tokio::test] + async fn an_admin_post_without_csrf_is_refused() { + let (_dir, state) = test_state().await; + let (token, _csrf) = sign_in_as(&state, "01ADMINAAAAAAAAAAAAAAAAAA", Role::Admin).await; + let board = state.store.ensure_board("IZ").await.expect("board"); + let request = http::Request::post("/tags") + .header(COOKIE, cookie_of(&token)) + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from("name=Sneaky")) + .expect("request"); + assert_eq!(status_of(&state, request).await, 403); + let names: Vec = state + .store + .tags(&board.id) + .await + .expect("tags") + .into_iter() + .map(|tag| tag.name) + .collect(); + assert!( + !names.iter().any(|name| name == "Sneaky"), + "the write happened" + ); + } +} diff --git a/crates/iz-web/src/pages/columns.rs b/crates/iz-web/src/pages/columns.rs new file mode 100644 index 0000000..9c78bac --- /dev/null +++ b/crates/iz-web/src/pages/columns.rs @@ -0,0 +1,278 @@ +//! The columns page (`GET /columns` and its POSTs): add, rename, move one place, and retire. Columns are +//! never deleted: retiring is a soft delete that the store records, so old activity keeps its names. The +//! done column is kept last and cannot be retired; the store enforces both. Administrators only. Every +//! write checks CSRF first, bumps the board and admin-structure topics after commit, and writes one audit +//! row. + +use iz_core::store::audit::AuditEntry; +use iz_core::store::board::Direction; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::response::Response; +use topcoat::router::{StatusCode, path_param_segment, route}; +use topcoat::view::view; + +use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; +use crate::i18n::structure::{K, t}; +use crate::i18n::{Lang, lang}; +use crate::live::{AdminSection, Topic}; +use crate::pages::admin::{REFUSED, back, user_text, viewer_of}; +use crate::pages::board::the_board; +use crate::pages::task::core_err; +use crate::state::AppState; +use crate::views::structure::{ColumnRow, ColumnsView, columns_content}; +use crate::views::{ViewerInfo, respond, shell}; + +/// The add and rename forms: the name, and the CSRF token. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct NameSubmit { + csrf: String, + name: String, +} + +/// The move form: `up` or `down`. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct MoveSubmit { + csrf: String, + direction: String, +} + +/// The notice text of a column redirect. Unknown codes give `None`. +pub fn column_notice(lang: Lang, code: &str) -> Option { + let text = match code { + "column_added" => t(lang, K::NoticeColumnAdded), + "column_renamed" => t(lang, K::NoticeColumnRenamed), + "column_moved" => t(lang, K::NoticeColumnMoved), + "column_retired" => t(lang, K::NoticeColumnRetired), + _ => return None, + }; + Some(text.to_owned()) +} + +/// The page's data: the live columns in board order with their card counts. +async fn columns_page( + state: &AppState, + lang: Lang, + notice: Option, + alert: Option, +) -> Result { + let board = the_board(&state.store).await?; + let columns = state.store.columns(&board.id).await.map_err(core_err)?; + let usage = state + .store + .column_usage(&board.id) + .await + .map_err(core_err)?; + let rows = columns + .into_iter() + .map(|column| ColumnRow { + cards: usage + .iter() + .find(|(id, _)| *id == column.id) + .map_or(0, |(_, count)| *count), + id: column.id, + name: column.name, + is_done: column.is_done, + }) + .collect(); + Ok(ColumnsView { + lang, + columns: rows, + notice, + alert, + }) +} + +/// Renders the columns page with `status` and the session's CSRF token. +async fn render( + cx: &Cx, + me: &CurrentMember, + page: ColumnsView, + status: StatusCode, +) -> Result { + let lang = page.lang; + let viewer: ViewerInfo = viewer_of(me); + let csrf = me.session.csrf_token.clone(); + let document = view! { + cx => + (status) + shell(title: t(lang, K::ColumnsTitle), lang: lang, + viewer: Some(&viewer), page_script: None, + columns_content(page: &page, csrf: csrf.as_str()) + ) + }; + respond(cx, document).await +} + +/// Bumps the board (its columns show on every card view) and the admin-structure section. +fn bump_structure(state: &AppState, board_id: &str) { + state.live.bump(&Topic::Board(board_id.to_owned())); + state.live.bump(&Topic::Admin(AdminSection::Structure)); +} + +/// `GET /columns`. Administrators only. +#[route(GET "/columns")] +async fn columns_get(cx: &Cx) -> Result { + let state = app_context::(cx); + let me = require_role(cx, Need::Admin).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let notice = query_param(cx, "notice").and_then(|code| column_notice(language, &code)); + let page = columns_page(state, language, notice, None).await?; + render(cx, &me, page, StatusCode::OK).await +} + +/// `POST /columns`: adds a column before the done column. +#[route(POST "/columns")] +async fn add_column(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + match state.store.add_column(&board.id, &form.name).await { + Ok(column) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "column.add", + target_kind: "column", + target_id: Some(&column.id), + ip: None, + data: serde_json::json!({ "name": column.name }), + }) + .await; + bump_structure(state, &board.id); + back("/columns?notice=column_added") + } + Err(error) => { + let message = user_text(error)?; + let page = columns_page(state, language, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} + +/// `POST /columns/{id}/rename`. +#[route(POST "/columns/{id}/rename")] +async fn rename_column(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let column_id = path_param_segment(cx, "id").to_owned(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + match state + .store + .rename_column(&board.id, &column_id, &form.name) + .await + { + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "column.rename", + target_kind: "column", + target_id: Some(&column_id), + ip: None, + data: serde_json::json!({ "name": form.name.trim() }), + }) + .await; + bump_structure(state, &board.id); + back("/columns?notice=column_renamed") + } + Err(error) => { + let message = user_text(error)?; + let page = columns_page(state, language, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} + +/// `POST /columns/{id}/move`: one place earlier or later. The store keeps the done column last. +#[route(POST "/columns/{id}/move")] +async fn move_column(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let column_id = path_param_segment(cx, "id").to_owned(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + let direction = match form.direction.as_str() { + "up" => Direction::Up, + "down" => Direction::Down, + _ => { + return Err(core_err(iz_core::Error::Invalid( + "unknown direction".into(), + ))); + } + }; + match state + .store + .move_column(&board.id, &column_id, direction) + .await + { + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "column.move", + target_kind: "column", + target_id: Some(&column_id), + ip: None, + data: serde_json::json!({ "direction": form.direction }), + }) + .await; + bump_structure(state, &board.id); + back("/columns?notice=column_moved") + } + Err(error) => { + let message = user_text(error)?; + let page = columns_page(state, language, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} + +/// `POST /columns/{id}/retire`: a soft delete, refused for the done column and for a column that holds cards. +#[route(POST "/columns/{id}/retire")] +async fn retire_column(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let column_id = path_param_segment(cx, "id").to_owned(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + match state.store.retire_column(&board.id, &column_id).await { + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "column.retire", + target_kind: "column", + target_id: Some(&column_id), + ip: None, + data: serde_json::json!({}), + }) + .await; + bump_structure(state, &board.id); + back("/columns?notice=column_retired") + } + Err(error) => { + let message = user_text(error)?; + let page = columns_page(state, language, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} diff --git a/crates/iz-web/src/pages/logs.rs b/crates/iz-web/src/pages/logs.rs index 377b5fc..c8499b8 100644 --- a/crates/iz-web/src/pages/logs.rs +++ b/crates/iz-web/src/pages/logs.rs @@ -19,6 +19,8 @@ use topcoat::view::view; use crate::auth::{Need, percent_encode, query_param, require_csrf, require_role}; use crate::i18n::admin::{K, t}; use crate::i18n::{Lang, lang}; +use crate::live::{AdminSection, Topic}; +use crate::pages::admin::record; use crate::pages::admin::{CsrfForm, back, notice_text, viewer_of}; use crate::pages::board::the_board; use crate::pages::task::core_err; @@ -159,11 +161,21 @@ async fn retry_row(cx: &Cx, form: Option>) -> Result { let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let row_id = path_param_segment(cx, "id").to_owned(); - require_csrf(cx, Need::Admin, &form.csrf).await?; + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; state .store .retry_row(&row_id, Timestamp::now()) .await .map_err(core_err)?; + record( + state, + &me, + "outbox.retry", + "outbox", + Some(&row_id), + serde_json::json!({}), + ) + .await; + state.live.bump(&Topic::Admin(AdminSection::Outbox)); back("/logs?section=outbox¬ice=retried") } diff --git a/crates/iz-web/src/pages/mod.rs b/crates/iz-web/src/pages/mod.rs index e76dbdc..e183dea 100644 --- a/crates/iz-web/src/pages/mod.rs +++ b/crates/iz-web/src/pages/mod.rs @@ -3,12 +3,15 @@ pub mod admin; pub mod backchannel; pub mod board; +pub mod columns; pub mod files; pub mod logs; pub mod not_found; +pub mod people; pub mod photo; pub mod rules; pub mod settings; pub mod sign_in; +pub mod tags; pub mod task; pub mod tasks; diff --git a/crates/iz-web/src/pages/people.rs b/crates/iz-web/src/pages/people.rs new file mode 100644 index 0000000..661a075 --- /dev/null +++ b/crates/iz-web/src/pages/people.rs @@ -0,0 +1,119 @@ +//! The person card (`GET /people/{sub}`): a member's name, role, counts on this board, and their recent +//! activity here. Visible to anyone who may read the board. The target must be a member of this board: a +//! member with role `none`, a disabled member, or an unknown id gets `404`, so the page reveals nothing +//! about people outside the board. Read-only: nothing on this page writes. + +use iz_core::authz::{Action, authorize}; +use iz_core::store::activity::ActivityFilter; +use iz_core::store::members::Member; +use iz_core::zones::parse_zone; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::not_found; +use topcoat::router::response::Response; +use topcoat::router::{path_param_segment, route}; +use topcoat::view::view; + +use crate::auth::{Need, require_role}; +use crate::i18n::structure::{K, t}; +use crate::i18n::task::activity_kind; +use crate::i18n::{Lang, lang}; +use crate::pages::board::the_board; +use crate::pages::task::{core_err, local_text}; +use crate::state::AppState; +use crate::views::structure::person_content; +use crate::views::{ViewerInfo, respond, shell}; + +/// How many recent activity rows the card shows. +const RECENT_ROWS: usize = 20; + +/// The role word of a stored role, in the viewer's language. +fn role_word(lang: Lang, role: &str) -> &'static str { + match role { + "admin" => t(lang, K::RoleAdmin), + "viewer" => t(lang, K::RoleViewer), + "none" => t(lang, K::RoleNone), + _ => t(lang, K::RoleMember), + } +} + +/// `GET /people/{sub}`. +#[route(GET "/people/{sub}")] +async fn person_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let me = require_role(cx, Need::Viewer).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let sub = path_param_segment(cx, "sub").to_owned(); + let board = the_board(&state.store).await?; + + // The target must be a member of this board. Anything else is a plain 404. + let target: Member = match state.store.member(&sub).await.map_err(core_err)? { + Some(member) if member.role != iz_core::authz::Role::NoAccess && !member.disabled => member, + _ => return Err(not_found().into()), + }; + if authorize(&me.actor(), &Action::ViewPerson).is_err() { + return Err(not_found().into()); + } + + let figures = state + .store + .person_counts(&board.id, &sub) + .await + .map_err(core_err)?; + let filter = ActivityFilter { + actor: Some(sub.clone()), + ..ActivityFilter::default() + }; + let feed = state + .store + .list_recent(&board.id, &filter, None, RECENT_ROWS) + .await + .map_err(core_err)?; + let zone = parse_zone(&me.member.zoneinfo).unwrap_or(jiff::tz::TimeZone::UTC); + let recent: Vec<(String, String, String)> = feed + .items + .iter() + .map(|item| { + ( + local_text(&item.at, &zone), + activity_kind(language, &item.kind).to_owned(), + item.subject.clone().unwrap_or_default(), + ) + }) + .collect(); + let counts: Vec<(&'static str, String)> = vec![ + (t(language, K::PersonOpen), figures.open.to_string()), + (t(language, K::PersonDone), figures.done.to_string()), + (t(language, K::PersonCreated), figures.created.to_string()), + (t(language, K::PersonComments), figures.comments.to_string()), + (t(language, K::PersonFiles), figures.files.to_string()), + ]; + let last_sign_in = target + .last_sign_in_at + .as_deref() + .map(|stamp| local_text(stamp, &zone)) + .filter(|text| !text.is_empty()) + .unwrap_or_else(|| t(language, K::PersonNeverSignedIn).to_owned()); + let role = role_word(language, target.role.as_str()).to_owned(); + let viewer = ViewerInfo { + name: me.member.name.clone(), + is_admin: authorize(&me.actor(), &Action::Administer).is_ok(), + csrf: me.session.csrf_token.clone(), + }; + let document = view! { + cx => + shell(title: target.name.as_str(), lang: language, + viewer: Some(&viewer), page_script: None, + person_content( + lang: language, + name: target.name.as_str(), + role: role.as_str(), + zone: target.zoneinfo.as_str(), + last_sign_in: last_sign_in.as_str(), + counts: &counts, + recent: &recent, + ) + ) + }; + respond(cx, document).await +} diff --git a/crates/iz-web/src/pages/rules.rs b/crates/iz-web/src/pages/rules.rs index 64d596b..9246af5 100644 --- a/crates/iz-web/src/pages/rules.rs +++ b/crates/iz-web/src/pages/rules.rs @@ -22,6 +22,8 @@ use topcoat::view::view; use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; use crate::i18n::admin::{K, fill, t}; use crate::i18n::{Lang, lang}; +use crate::live::{AdminSection, Topic}; +use crate::pages::admin::record; use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewer_of}; use crate::pages::board::the_board; use crate::pages::task::core_err; @@ -276,7 +278,19 @@ async fn create_rule(cx: &Cx, form: Option>) -> Result back("/rules?notice=rule"), + Ok(rule) => { + record( + state, + &me, + "rule.save", + "rule", + Some(&rule.id), + serde_json::json!({}), + ) + .await; + state.live.bump(&Topic::Admin(AdminSection::Rules)); + back("/rules?notice=rule") + } Err(error) => refused(cx, state, &me, &board.id, &form, None, error).await, } } @@ -294,7 +308,19 @@ async fn update_rule(cx: &Cx, form: Option>) -> Result back("/rules?notice=rule"), + Ok(rule) => { + record( + state, + &me, + "rule.save", + "rule", + Some(&rule.id), + serde_json::json!({}), + ) + .await; + state.live.bump(&Topic::Admin(AdminSection::Rules)); + back("/rules?notice=rule") + } Err(error) => refused(cx, state, &me, &board.id, &form, Some(rule_id), error).await, } } @@ -305,13 +331,23 @@ async fn set_enabled(cx: &Cx, form: Option>) -> Result(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let rule_id = path_param_segment(cx, "id").to_owned(); - require_csrf(cx, Need::Admin, &form.csrf).await?; + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; let board = the_board(&state.store).await?; state .store .set_rule_enabled(&board.id, &rule_id, form.enabled == "1") .await .map_err(core_err)?; + record( + state, + &me, + "rule.enabled", + "rule", + Some(&rule_id), + serde_json::json!({ "enabled": form.enabled == "1" }), + ) + .await; + state.live.bump(&Topic::Admin(AdminSection::Rules)); back("/rules?notice=rule_switched") } @@ -321,12 +357,22 @@ async fn delete_rule(cx: &Cx, form: Option>) -> Result let state = app_context::(cx); let form = form.map(|Form(form)| form).unwrap_or_default(); let rule_id = path_param_segment(cx, "id").to_owned(); - require_csrf(cx, Need::Admin, &form.csrf).await?; + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; let board = the_board(&state.store).await?; state .store .delete_rule(&board.id, &rule_id) .await .map_err(core_err)?; + record( + state, + &me, + "rule.delete", + "rule", + Some(&rule_id), + serde_json::json!({}), + ) + .await; + state.live.bump(&Topic::Admin(AdminSection::Rules)); back("/rules?notice=rule_deleted") } diff --git a/crates/iz-web/src/pages/settings.rs b/crates/iz-web/src/pages/settings.rs index ca8b116..878a367 100644 --- a/crates/iz-web/src/pages/settings.rs +++ b/crates/iz-web/src/pages/settings.rs @@ -23,11 +23,19 @@ use topcoat::view::view; use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; use crate::i18n::admin::{K, t}; use crate::i18n::{Lang, lang}; +use crate::live::{AdminSection, Topic}; use crate::mail; use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewer_of}; +use crate::pages::board::the_board; use crate::state::AppState; use crate::views::admin::{SenderForm, SettingsView, settings_content}; +use crate::views::structure::{MemberRow, ServerInfo}; use crate::views::{ViewerInfo, respond, shell}; +use iz_core::authz::Role; +use iz_core::limits::{ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN}; +use iz_core::store::attachments::{SETTING_EXTENSIONS, SETTING_LIMIT_MIB, parse_extensions}; +use iz_core::store::audit::AuditEntry; +use topcoat::router::path_param_segment; /// The sender form as posted. #[derive(Debug, Default, Deserialize)] @@ -95,6 +103,23 @@ async fn settings_view( let reminders: ReminderSettings = state.store.reminder_settings().await?; let mut sender = form.unwrap_or_else(|| sender_form(&stored)); sender.password_set = stored.password_set; + let policy = state.store.policy().await?; + let members = state + .store + .list_members() + .await? + .into_iter() + .map(|m| MemberRow { + sub: m.sub, + name: m.name, + email: m.email, + role: m.role.as_str().to_owned(), + im_admin: m.im_admin, + disabled: m.disabled, + }) + .collect(); + let limit_mib = (policy.limit_bytes / (1024 * 1024)).to_string(); + let extensions = policy.extensions.join(" "); Ok(SettingsView { lang, configured: stored.sender.is_some(), @@ -103,9 +128,44 @@ async fn settings_view( reminder_cap: reminders.hourly_cap, notice, alert, + members, + limit_mib, + extensions, + server: server_info(state).await?, + }) +} + +/// The read-only server facts of the settings page. +async fn server_info(state: &AppState) -> Result { + Ok(ServerInfo { + base_url: state.config.base_url.clone(), + listen: state.config.listen.to_string(), + data_dir: state.config.data_dir.display().to_string(), + database: state.config.database.display().to_string(), + schema: state.store.schema_version().await?, + build: env!("IZ_BUILD_SHA").to_owned(), + sign_in: state.oidc.is_some(), + storage_in: state.config.in_store.enabled, }) } +/// The members-and-roles form: the role word of one member. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct RoleSubmit { + csrf: String, + role: String, +} + +/// The limits form: the attachment size in MiB and the allowed extensions. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct LimitsSubmit { + csrf: String, + limit_mib: String, + extensions: String, +} + /// Renders the settings page with `status`. The CSRF token of the session goes in every form. async fn render( cx: &Cx, @@ -176,7 +236,22 @@ async fn save_sender(cx: &Cx, form: Option>) -> Result back("/settings?notice=sender"), + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "sender.save", + target_kind: "settings", + target_id: None, + ip: None, + data: serde_json::json!({}), + }) + .await; + state.live.bump(&Topic::Admin(AdminSection::Settings)); + back("/settings?notice=sender") + } Err(error) => { let message = user_text(error)?; let page = settings_view(state, language, Some(typed), None, Some(message)).await?; @@ -193,7 +268,22 @@ async fn check_sender(cx: &Cx, form: Option>) -> Result let me = require_csrf(cx, Need::Admin, &form.csrf).await?; let language = lang(cx, me.member.locale_override.as_deref()); match mail::check(state).await { - Ok(()) => back("/settings?notice=checked"), + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "sender.check", + target_kind: "settings", + target_id: None, + ip: None, + data: serde_json::json!({}), + }) + .await; + state.live.bump(&Topic::Admin(AdminSection::Settings)); + back("/settings?notice=checked") + } Err(error) => { let message = user_text(error)?; let page = settings_view(state, language, None, None, Some(message)).await?; @@ -214,7 +304,22 @@ async fn send_test(cx: &Cx, form: Option>) -> Result { me.member.locale.as_deref(), ); match mail::send_test(state, &me.member.name, &me.member.email, mail_lang).await { - Ok(()) => back("/settings?notice=test"), + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "sender.test", + target_kind: "settings", + target_id: None, + ip: None, + data: serde_json::json!({}), + }) + .await; + state.live.bump(&Topic::Admin(AdminSection::Settings)); + back("/settings?notice=test") + } Err(error) => { let message = user_text(error)?; let page = settings_view(state, language, None, None, Some(message)).await?; @@ -249,7 +354,22 @@ async fn save_reminders(cx: &Cx, form: Option>) -> Result< } .await; match outcome { - Ok(()) => back("/settings?notice=reminders"), + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "reminders.save", + target_kind: "settings", + target_id: None, + ip: None, + data: serde_json::json!({}), + }) + .await; + state.live.bump(&Topic::Admin(AdminSection::Settings)); + back("/settings?notice=reminders") + } Err(error) => { let message = user_text(error)?; let page = settings_view(state, language, None, None, Some(message)).await?; @@ -271,7 +391,123 @@ async fn send_message(cx: &Cx, form: Option>) -> Result back(&format!("/settings?notice=message&queued={count}")), + Ok(count) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "message.queue", + target_kind: "settings", + target_id: None, + ip: None, + data: serde_json::json!({}), + }) + .await; + state.live.bump(&Topic::Admin(AdminSection::Settings)); + back(&format!("/settings?notice=message&queued={count}")) + } + Err(error) => { + let message = user_text(error)?; + let page = settings_view(state, language, None, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} + +/// `POST /settings/members/{sub}/role`: sets a member's role. The store refuses to demote the last +/// administrator, and a viewer or none loses their assignments. +#[route(POST "/settings/members/{sub}/role")] +async fn save_role(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let target = path_param_segment(cx, "sub").to_owned(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let outcome: iz_core::Result<()> = async { + let role = Role::parse(&form.role) + .ok_or_else(|| iz_core::Error::Invalid("unknown role".into()))?; + state.store.set_role(&target, role).await + } + .await; + match outcome { + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "role.set", + target_kind: "member", + target_id: Some(&target), + ip: None, + data: serde_json::json!({ "role": form.role }), + }) + .await; + state.live.bump(&Topic::Admin(AdminSection::Members)); + state.live.bump(&Topic::Person(target.clone())); + state + .live + .bump(&Topic::Board(the_board(&state.store).await?.id)); + back("/settings?notice=role_set") + } + Err(error) => { + let message = user_text(error)?; + let page = settings_view(state, language, None, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} + +/// `POST /settings/limits`: the attachment size (1 to 500 MiB) and the allowed extensions. +#[route(POST "/settings/limits")] +async fn save_limits(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let outcome: iz_core::Result<()> = async { + let mib = form + .limit_mib + .trim() + .parse::() + .ok() + .filter(|mib| (ATTACHMENT_LIMIT_MIB_MIN..=ATTACHMENT_LIMIT_MIB_MAX).contains(mib)) + .ok_or_else(|| { + iz_core::Error::Invalid(format!( + "the size limit must be {ATTACHMENT_LIMIT_MIB_MIN} to {ATTACHMENT_LIMIT_MIB_MAX} MiB" + )) + })?; + let extensions = parse_extensions(&form.extensions); + if extensions.is_empty() { + return Err(iz_core::Error::Invalid( + "at least one extension must be allowed".into(), + )); + } + state.store.set_setting(SETTING_LIMIT_MIB, &mib.to_string()).await?; + state + .store + .set_setting(SETTING_EXTENSIONS, &extensions.join(" ")) + .await + } + .await; + match outcome { + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "limits.save", + target_kind: "settings", + target_id: None, + ip: None, + data: serde_json::json!({}), + }) + .await; + state.live.bump(&Topic::Admin(AdminSection::Settings)); + back("/settings?notice=limits") + } Err(error) => { let message = user_text(error)?; let page = settings_view(state, language, None, None, Some(message)).await?; diff --git a/crates/iz-web/src/pages/tags.rs b/crates/iz-web/src/pages/tags.rs new file mode 100644 index 0000000..937ed6a --- /dev/null +++ b/crates/iz-web/src/pages/tags.rs @@ -0,0 +1,323 @@ +//! The projects page (`GET /tags` and its POSTs): add, rename, colour from the fixed palette, move and +//! delete. Administrators only; a non-administrator gets `404` (see `auth::require_role`). Every write +//! checks the CSRF token before any side effect, bumps the board and admin-structure live topics after it +//! commits, and writes one audit row. A project in use is refused by the store with a message. + +use iz_core::store::audit::AuditEntry; +use iz_core::store::board::Direction; +use iz_core::store::board::{TAG_COLOURS, Tag}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::response::Response; +use topcoat::router::{StatusCode, path_param_segment, route}; +use topcoat::view::view; + +use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; +use crate::i18n::structure::{K, t}; +use crate::i18n::{Lang, lang}; +use crate::live::{AdminSection, Topic}; +use crate::pages::admin::{REFUSED, back, user_text, viewer_of}; +use crate::pages::board::the_board; +use crate::pages::task::core_err; +use crate::state::AppState; +use crate::views::structure::{TagRow, TagsView, tags_content}; +use crate::views::{ViewerInfo, respond, shell}; + +/// The add-project form. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct AddSubmit { + csrf: String, + name: String, + colour: String, +} + +/// The rename form. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct RenameSubmit { + csrf: String, + name: String, +} + +/// The colour form. An empty value clears the colour. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct ColourSubmit { + csrf: String, + colour: String, +} + +/// The move form: `up` or `down`. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct MoveSubmit { + csrf: String, + direction: String, +} + +/// The page's data: every project with its usage, and the palette. +async fn tags_page( + state: &AppState, + lang: Lang, + notice: Option, + alert: Option, +) -> Result { + let board = the_board(&state.store).await?; + let tags: Vec = state.store.tags(&board.id).await.map_err(core_err)?; + let usage = state.store.tag_usage(&board.id).await.map_err(core_err)?; + let rows = tags + .into_iter() + .map(|tag| TagRow { + uses: usage + .iter() + .find(|(id, _)| *id == tag.id) + .map_or(0, |(_, count)| *count), + id: tag.id, + name: tag.name, + colour: tag.color, + is_default: tag.is_default, + }) + .collect(); + Ok(TagsView { + lang, + tags: rows, + palette: palette(), + notice, + alert, + }) +} + +/// The palette names, `c0` to `c7`. +fn palette() -> Vec { + (0..TAG_COLOURS).map(|n| format!("c{n}")).collect() +} + +/// The notice text of a project redirect. Unknown codes give `None`. +pub fn tag_notice(lang: Lang, code: &str) -> Option { + let text = match code { + "tag_added" => t(lang, K::NoticeTagAdded), + "tag_renamed" => t(lang, K::NoticeTagRenamed), + "tag_coloured" => t(lang, K::NoticeTagColoured), + "tag_deleted" => t(lang, K::NoticeTagDeleted), + "tag_moved" => t(lang, K::NoticeTagMoved), + _ => return None, + }; + Some(text.to_owned()) +} + +/// Renders the projects page with `status` and the CSRF token of the session. +async fn render( + cx: &Cx, + me: &CurrentMember, + page: TagsView, + status: StatusCode, +) -> Result { + let lang = page.lang; + let viewer: ViewerInfo = viewer_of(me); + let csrf = me.session.csrf_token.clone(); + let document = view! { + cx => + (status) + shell(title: t(lang, K::TagsTitle), lang: lang, + viewer: Some(&viewer), page_script: None, + tags_content(page: &page, csrf: csrf.as_str()) + ) + }; + respond(cx, document).await +} + +/// Bumps what a structure write changes: the board (cards show projects) and the admin section. +fn bump_structure(state: &AppState, board_id: &str) { + state.live.bump(&Topic::Board(board_id.to_owned())); + state.live.bump(&Topic::Admin(AdminSection::Structure)); +} + +/// `GET /tags`. Administrators only. +#[route(GET "/tags")] +async fn tags_get(cx: &Cx) -> Result { + let state = app_context::(cx); + let me = require_role(cx, Need::Admin).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let notice = query_param(cx, "notice").and_then(|code| tag_notice(language, &code)); + let page = tags_page(state, language, notice, None).await?; + render(cx, &me, page, StatusCode::OK).await +} + +/// `POST /tags`: adds a project at the end. +#[route(POST "/tags")] +async fn add_tag(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + let colour = (!form.colour.is_empty()).then_some(form.colour.as_str()); + let outcome = state.store.add_tag(&board.id, &form.name, colour).await; + match outcome { + Ok(tag) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "tag.add", + target_kind: "tag", + target_id: Some(&tag.id), + ip: None, + data: serde_json::json!({ "name": tag.name }), + }) + .await; + bump_structure(state, &board.id); + back("/tags?notice=tag_added") + } + Err(error) => { + let message = user_text(error)?; + let page = tags_page(state, language, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} + +/// `POST /tags/{id}/rename`. +#[route(POST "/tags/{id}/rename")] +async fn rename_tag(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let tag_id = path_param_segment(cx, "id").to_owned(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + match state.store.rename_tag(&board.id, &tag_id, &form.name).await { + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "tag.rename", + target_kind: "tag", + target_id: Some(&tag_id), + ip: None, + data: serde_json::json!({ "name": form.name.trim() }), + }) + .await; + bump_structure(state, &board.id); + back("/tags?notice=tag_renamed") + } + Err(error) => { + let message = user_text(error)?; + let page = tags_page(state, language, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} + +/// `POST /tags/{id}/colour`: sets a colour from the palette, or clears it. +#[route(POST "/tags/{id}/colour")] +async fn colour_tag(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let tag_id = path_param_segment(cx, "id").to_owned(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + let colour = (!form.colour.is_empty()).then_some(form.colour.as_str()); + match state.store.set_tag_colour(&board.id, &tag_id, colour).await { + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "tag.colour", + target_kind: "tag", + target_id: Some(&tag_id), + ip: None, + data: serde_json::json!({ "colour": colour }), + }) + .await; + bump_structure(state, &board.id); + back("/tags?notice=tag_coloured") + } + Err(error) => { + let message = user_text(error)?; + let page = tags_page(state, language, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} + +/// `POST /tags/{id}/move`: one place earlier or later. +#[route(POST "/tags/{id}/move")] +async fn move_tag(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let tag_id = path_param_segment(cx, "id").to_owned(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let board = the_board(&state.store).await?; + let direction = match form.direction.as_str() { + "up" => Direction::Up, + "down" => Direction::Down, + _ => { + return Err(core_err(iz_core::Error::Invalid( + "unknown direction".into(), + ))); + } + }; + state + .store + .move_tag(&board.id, &tag_id, direction) + .await + .map_err(core_err)?; + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "tag.move", + target_kind: "tag", + target_id: Some(&tag_id), + ip: None, + data: serde_json::json!({ "direction": form.direction }), + }) + .await; + bump_structure(state, &board.id); + back("/tags?notice=tag_moved") +} + +/// `POST /tags/{id}/delete`: refused by the store while any card is in the project. +#[route(POST "/tags/{id}/delete")] +async fn delete_tag(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let tag_id = path_param_segment(cx, "id").to_owned(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + match state.store.delete_tag(&board.id, &tag_id).await { + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "tag.delete", + target_kind: "tag", + target_id: Some(&tag_id), + ip: None, + data: serde_json::json!({}), + }) + .await; + bump_structure(state, &board.id); + back("/tags?notice=tag_deleted") + } + Err(error) => { + let message = user_text(error)?; + let page = tags_page(state, language, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} diff --git a/crates/iz-web/src/pages/task.rs b/crates/iz-web/src/pages/task.rs index 125ed1d..2210408 100644 --- a/crates/iz-web/src/pages/task.rs +++ b/crates/iz-web/src/pages/task.rs @@ -662,11 +662,17 @@ async fn assign(cx: &Cx, form: Option>) -> Result { } match state .store - .assign(&begun.board_id, &task_id, &[sub], &begun.me.member.sub) + .assign( + &begun.board_id, + &task_id, + std::slice::from_ref(&sub), + &begun.me.member.sub, + ) .await { Ok(()) => { bump(state, &begun.board_id, &task_id); + state.live.bump(&Topic::Person(sub.clone())); back(&form.next, Some(key.as_str())) } Err(iz_core::Error::Invalid(_)) => { @@ -706,6 +712,7 @@ async fn unassign(cx: &Cx, form: Option>) -> Result { .await .map_err(core_err)?; bump(state, &begun.board_id, &task_id); + state.live.bump(&Topic::Person(form.sub.trim().to_owned())); back(&form.next, Some(key.as_str())) } diff --git a/crates/iz-web/src/state.rs b/crates/iz-web/src/state.rs index 966e55f..0d41d32 100644 --- a/crates/iz-web/src/state.rs +++ b/crates/iz-web/src/state.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use iz_core::config::Config; use iz_core::store::Store; +use crate::family::FamilyCache; use crate::live::LiveHub; use crate::oidc::OidcClient; @@ -22,4 +23,6 @@ pub struct AppState { pub live: Arc, /// The `im` client. `None` when no `[oidc]` section is configured, so sign-in is off. pub oidc: Option>, + /// The family service list that the topbar switcher shows. Filled by the `family` worker. + pub family: Arc, } diff --git a/crates/iz-web/src/sweeper.rs b/crates/iz-web/src/sweeper.rs new file mode 100644 index 0000000..37d3d07 --- /dev/null +++ b/crates/iz-web/src/sweeper.rs @@ -0,0 +1,166 @@ +//! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the +//! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the +//! attachment bytes still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass +//! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, and removes staged +//! uploads left in `data_dir/tmp` by a crash. +//! +//! It never deletes live data: pending mail, pending deletions that are not yet due, and sessions that have +//! not expired are left alone. A failed step is logged and the next step still runs. + +use std::future::Future; +use std::path::Path; +use std::time::{Duration, SystemTime}; + +use iz_core::staging::{TMP_DIR, remove_blob}; +use iz_core::store::sweep::RETENTION_DAYS; +use jiff::{SignedDuration, Timestamp}; +use tokio::sync::watch; + +use crate::attachments::retry_delay; +use crate::state::AppState; + +/// How often the sweeper runs after its first pass. Reason: none of this is urgent. +const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60); +/// Rows deleted per statement. Reason: keeps each write short so the writer is not held for long. +const BATCH: i64 = 500; +/// A staged upload older than this is an orphan. Reason: no upload stays in staging for a day. +const TEMP_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60); + +/// Starts the sweeper. It runs at once, then every [`SWEEP_EVERY`], until `stop` is set. +pub fn spawn(state: AppState, mut stop: watch::Receiver) { + tokio::spawn(async move { + loop { + sweep(&state).await; + tokio::select! { + () = tokio::time::sleep(SWEEP_EVERY) => {} + _ = stop.wait_for(|stopped| *stopped) => break, + } + } + tracing::info!("sweeper stopped"); + }); +} + +/// One full run. Each step is independent: a failure is logged and the run goes on. +async fn sweep(state: &AppState) { + note("expired sessions", state.store.sweep_sessions().await); + note("expired logout tokens", state.store.sweep_jti().await); + retry_blob_deletions(state).await; + match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * RETENTION_DAYS)) { + Ok(cutoff) => { + drain("activity", |batch| { + state.store.prune_activity(cutoff, batch) + }) + .await; + drain("mail decisions", |batch| { + state.store.prune_mail_decisions(cutoff, batch) + }) + .await; + drain("finished mail", |batch| { + state.store.prune_mail_outbox(cutoff, batch) + }) + .await; + } + Err(error) => { + tracing::warn!(error = %error, "retention cutoff is out of range; not pruned") + } + } + note( + "stale staged uploads", + remove_stale_temp_files(&state.config.data_dir).await, + ); +} + +/// Logs a step's count when it is not zero, and logs a failed step. Returns nothing: a sweep step has no +/// result the caller needs. +fn note(what: &str, result: iz_core::Result) { + match result { + Ok(0) => {} + Ok(count) => tracing::info!(count, what, "sweeper removed rows"), + Err(error) => tracing::warn!(error = %error, what, "sweeper step failed"), + } +} + +/// Runs a batched delete until a batch comes back short, a batch fails, or the step runs out of rows. Logs +/// the total when it is not zero. +async fn drain(what: &str, mut step: F) +where + F: FnMut(i64) -> Fut, + Fut: Future>, +{ + let mut total: u64 = 0; + loop { + match step(BATCH).await { + Ok(deleted) => { + total += deleted; + if deleted < u64::try_from(BATCH).unwrap_or(0) { + break; + } + } + Err(error) => { + tracing::warn!(error = %error, what, "sweeper batch failed"); + break; + } + } + } + note(what, Ok(total)); +} + +/// Retries the attachment bytes that are owed and due. A removal that fails is scheduled again with the +/// same backoff the deleter uses. Returns nothing; the deleter logs its own failures. +async fn retry_blob_deletions(state: &AppState) { + let due = match state.store.due_blob_deletions(BATCH).await { + Ok(due) => due, + Err(error) => { + tracing::warn!(error = %error, "reading the due attachment deletions failed"); + return; + } + }; + let mut removed: u64 = 0; + for (id, attempts) in due { + match remove_blob(&state.config.data_dir, &id).await { + Ok(()) => match state.store.finish_blob_deletion(&id).await { + Ok(()) => removed += 1, + Err(error) => { + tracing::warn!(error = %error, "clearing a finished attachment deletion failed"); + } + }, + Err(error) => { + tracing::warn!(attempts, error = %error, "removing attachment bytes failed; retrying"); + if let Err(error) = state + .store + .defer_blob_deletion(&id, attempts, retry_delay(attempts)) + .await + { + tracing::warn!(error = %error, "scheduling an attachment deletion retry failed"); + } + } + } + } + note("attachment bytes removed", Ok(removed)); +} + +/// Removes regular files in `data_dir/tmp` that were last changed more than [`TEMP_MAX_AGE`] ago. A missing +/// staging directory means there is nothing to remove. Links and directories are left alone. +async fn remove_stale_temp_files(data_dir: &Path) -> iz_core::Result { + let dir = data_dir.join(TMP_DIR); + let mut entries = match tokio::fs::read_dir(&dir).await { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0), + Err(error) => return Err(error.into()), + }; + let cutoff = SystemTime::now() + .checked_sub(TEMP_MAX_AGE) + .unwrap_or(SystemTime::UNIX_EPOCH); + let mut removed: u64 = 0; + while let Some(entry) = entries.next_entry().await? { + let meta = entry.metadata().await?; + if !meta.is_file() { + continue; + } + if meta.modified()? < cutoff { + tokio::fs::remove_file(entry.path()).await?; + removed += 1; + } + } + Ok(removed) +} diff --git a/crates/iz-web/src/views/admin.rs b/crates/iz-web/src/views/admin.rs index 150ab53..640d735 100644 --- a/crates/iz-web/src/views/admin.rs +++ b/crates/iz-web/src/views/admin.rs @@ -10,7 +10,9 @@ use topcoat::view::{View, component, view}; use crate::i18n::Lang; use crate::i18n::admin::{K, t}; +use crate::i18n::structure::{K as StructureK, t as structure_t}; use crate::views::board::flag; +use crate::views::structure::{limits_section, members_section, server_section}; use crate::views::{alert, notice}; /// The sender form as it is shown. The password is never here, only `password_set`. @@ -126,6 +128,14 @@ pub struct SettingsView { pub notice: Option, /// A refusal to show above the page, already translated or a store message. pub alert: Option, + /// Members and their roles, in name order. + pub members: Vec, + /// The attachment size limit in MiB, as text for the form. + pub limit_mib: String, + /// The allowed attachment extensions, space separated, for the form. + pub extensions: String, + /// Read-only facts about the server. + pub server: crate::views::structure::ServerInfo, } /// The rules page: the list, the form (new or editing), and the choices of the form. @@ -169,9 +179,21 @@ pub async fn admin_tabs(lang: Lang, current: &str) -> Result { } else { "tab" }; + let tags = if current == "tags" { + "tab current" + } else { + "tab" + }; + let columns = if current == "columns" { + "tab current" + } else { + "tab" + }; Ok(view! { @@ -288,6 +310,9 @@ pub async fn settings_content(page: &SettingsView, csrf: &str) -> Result(t(lang, K::SendMessage)) + members_section(lang: lang, members: &page.members, csrf: csrf) + limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf) + server_section(lang: lang, info: &page.server) }) } diff --git a/crates/iz-web/src/views/mod.rs b/crates/iz-web/src/views/mod.rs index 9df7b8c..e1afa14 100644 --- a/crates/iz-web/src/views/mod.rs +++ b/crates/iz-web/src/views/mod.rs @@ -4,18 +4,24 @@ //! emits an inline script, style or event handler; see `security.rs`. use topcoat::Result; -use topcoat::context::Cx; +use topcoat::context::{Cx, app_context}; use topcoat::router::response::{IntoResponse, Response}; use topcoat::view::{Child, View, ViewExt, component, view}; pub mod admin; pub mod board; pub mod files; +pub mod structure; pub mod task; use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; +use crate::family::Service; use crate::i18n::Lang; use crate::i18n::shell::{K, t}; +use crate::state::AppState; + +/// The family key of this app. The switcher marks the service with this key as the current one. +const APP_KEY: &str = "iz"; /// What the shell shows about the signed-in person: the name in the user menu, the administrator /// badge, and the CSRF token of the sign-out form in that menu. @@ -32,10 +38,12 @@ pub struct ViewerInfo { /// app name. `child` is the page, placed in `
`. `page_script` is the one script of this page /// (for example `board.js`), or `None`; it is loaded with `defer` and only on the page that needs it. /// -/// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and -/// the viewer's name on the right. `nav.js` reads the restart text from ``. +/// The topbar has the wordmark on the left, the service switcher in the middle and the viewer's name +/// on the right. The switcher lists the family services from the cache in `AppState`; it is left out +/// when the list is empty. `nav.js` reads the restart text from ``. #[component] pub async fn shell( + cx: &Cx, title: &str, lang: Lang, viewer: Option<&ViewerInfo>, @@ -43,6 +51,7 @@ pub async fn shell( #[default] child: Child<'_>, ) -> Result { let document_title = format!("{title} \u{b7} iz"); + let services = app_context::(cx).family.snapshot(); Ok(view! { @@ -61,7 +70,15 @@ pub async fn shell(
"iz" - + if !services.is_empty() { + + }
if let Some(viewer) = viewer {
@@ -83,6 +100,11 @@ pub async fn shell( }) } +/// Whether `service` is the app that renders the page, which the switcher marks with `aria-current`. +fn service_is_current(service: &Service) -> Option<&'static str> { + (service.key == APP_KEY).then_some("true") +} + /// The body of a message page: a title, one sentence, an optional detail (escaped, in a code /// element) and a way back to the start. #[component] diff --git a/crates/iz-web/src/views/structure.rs b/crates/iz-web/src/views/structure.rs new file mode 100644 index 0000000..beac9bb --- /dev/null +++ b/crates/iz-web/src/views/structure.rs @@ -0,0 +1,413 @@ +//! Markup of the structure and people pages: projects (`/tags`), columns (`/columns`), the members, limits +//! and server sections of `/settings`, and the person card (`/people/{sub}`). Plain data in, markup out. +//! Every value is escaped by `view!`; no script or inline style is emitted. + +use topcoat::Result; +use topcoat::view::{View, component, view}; + +use crate::i18n::Lang; +use crate::i18n::admin::fill; +use crate::i18n::structure::{K, t}; +use crate::views::admin::admin_tabs; +use crate::views::board::flag; +use crate::views::{alert, notice}; + +/// One project as the tags page shows it. +#[derive(Debug, Clone)] +pub struct TagRow { + /// Project id. + pub id: String, + /// Project name. + pub name: String, + /// Palette colour name (`c0` to `c7`), if set. + pub colour: Option, + /// Whether this is the default project. + pub is_default: bool, + /// Live cards in the project. + pub uses: i64, +} + +/// The tags page: the list, the add form, and the palette. +#[derive(Debug, Clone)] +pub struct TagsView { + /// The language. + pub lang: Lang, + /// Projects in board order. + pub tags: Vec, + /// The palette colour names, in order. + pub palette: Vec, + /// A confirmation, already translated. + pub notice: Option, + /// A refusal, already translated or a store message. + pub alert: Option, +} + +/// One column as the columns page shows it. +#[derive(Debug, Clone)] +pub struct ColumnRow { + /// Column id. + pub id: String, + /// Column name. + pub name: String, + /// Whether this is the done column. + pub is_done: bool, + /// Live cards in the column. + pub cards: i64, +} + +/// The columns page: the list in board order and the add form. +#[derive(Debug, Clone)] +pub struct ColumnsView { + /// The language. + pub lang: Lang, + /// Live columns in board order. + pub columns: Vec, + /// A confirmation, already translated. + pub notice: Option, + /// A refusal, already translated or a store message. + pub alert: Option, +} + +/// One member as the settings page shows them. +#[derive(Debug, Clone)] +pub struct MemberRow { + /// Member id (the OIDC `sub`). + pub sub: String, + /// Display name. + pub name: String, + /// Address. + pub email: String, + /// Stored role: `admin`, `member`, `viewer` or `none`. + pub role: String, + /// The directory marks this person as an administrator. + pub im_admin: bool, + /// The directory has disabled this person. + pub disabled: bool, +} + +/// Read-only facts about the running server. +#[derive(Debug, Clone, Default)] +pub struct ServerInfo { + /// The public base address. + pub base_url: String, + /// The listen address. + pub listen: String, + /// The data directory. + pub data_dir: String, + /// The database file. + pub database: String, + /// The highest applied migration. + pub schema: i64, + /// The build id. + pub build: String, + /// Whether sign-in through im is configured. + pub sign_in: bool, + /// Whether attachments go to the Files service. + pub storage_in: bool, +} + +/// The projects page body. +#[component] +pub async fn tags_content(page: &TagsView, csrf: &str) -> Result { + let lang = page.lang; + Ok(view! { +

(t(lang, K::TagsTitle))

+ admin_tabs(lang: lang, current: "tags") + if let Some(message) = &page.alert { + alert(message: message.as_str()) + } + if let Some(message) = &page.notice { + notice(message: message.as_str()) + } +

(t(lang, K::TagsHelp))

+
+ + + for tag in page.tags.iter() { + + + + + + + + } + +
+ + " " (tag.name.as_str()) + if tag.is_default { + " " (t(lang, K::TagDefault)) + } + " " (fill(t(lang, K::TagUsedBy), &[&tag.uses.to_string()])) + +
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ if !tag.is_default { +
+ + +
+ } +
+
+
+

(t(lang, K::TagsNew))

+
+ +
+ + +
+
+ + +
+ +
+
+ }) +} + +/// The columns page body. +#[component] +pub async fn columns_content(page: &ColumnsView, csrf: &str) -> Result { + let lang = page.lang; + Ok(view! { +

(t(lang, K::ColumnsTitle))

+ admin_tabs(lang: lang, current: "columns") + if let Some(message) = &page.alert { + alert(message: message.as_str()) + } + if let Some(message) = &page.notice { + notice(message: message.as_str()) + } +

(t(lang, K::ColumnsHelp))

+
+ + + for column in page.columns.iter() { + + + + + + + } + +
+ (column.name.as_str()) + if column.is_done { + " " (t(lang, K::ColumnDone)) + } + " " (fill(t(lang, K::ColumnCards), &[&column.cards.to_string()])) + +
+ + + +
+
+
+ + + +
+
+ if !column.is_done { +
+ + +
+ } +
+
+
+

(t(lang, K::ColumnsNew))

+
+ +
+ + +
+ +
+
+ }) +} + +/// The members and roles section of `/settings`. One row per member, each with its own role form. +#[component] +pub async fn members_section(lang: Lang, members: &[MemberRow], csrf: &str) -> Result { + Ok(view! { +
+

(t(lang, K::MembersHeading))

+

(t(lang, K::MembersHelp))

+ + + + + + + + + + + for member in members.iter() { + + + + + + + } + +
(t(lang, K::MemberName))(t(lang, K::MemberEmail))(t(lang, K::MemberFlags))(t(lang, K::MemberRole))
(member.name.as_str())(member.email.as_str()) + if member.im_admin { + (t(lang, K::MemberImAdmin)) + } + if member.disabled { + (t(lang, K::MemberDisabled)) + } + +
+ + + +
+
+
+ }) +} + +/// The limits section of `/settings`: attachment size and allowed extensions. +#[component] +pub async fn limits_section( + lang: Lang, + limit_mib: &str, + extensions: &str, + csrf: &str, +) -> Result { + Ok(view! { +
+

(t(lang, K::LimitsHeading))

+

(t(lang, K::LimitsHelp))

+
+ +
+ + +
+
+ + +
+ +
+
+ }) +} + +/// The server section of `/settings`: read-only facts. +#[component] +pub async fn server_section(lang: Lang, info: &ServerInfo) -> Result { + let (on_text, off_text) = (t(lang, K::On), t(lang, K::Off)); + let storage = if info.storage_in { + t(lang, K::StorageIn) + } else { + t(lang, K::StorageLocal) + }; + let schema = info.schema.to_string(); + Ok(view! { +
+

(t(lang, K::ServerHeading))

+

(t(lang, K::ServerHelp))

+
+
(t(lang, K::ServerBase))
(info.base_url.as_str())
+
(t(lang, K::ServerListen))
(info.listen.as_str())
+
(t(lang, K::ServerData))
(info.data_dir.as_str())
+
(t(lang, K::ServerDatabase))
(info.database.as_str())
+
(t(lang, K::ServerSchema))
(schema.as_str())
+
(t(lang, K::ServerBuild))
(info.build.as_str())
+
(t(lang, K::ServerSignIn))
(if info.sign_in { on_text } else { off_text })
+
(t(lang, K::ServerStorage))
(storage)
+
+
+ }) +} + +/// The person card body: name, role and zone, counts, and the recent activity of this member on the board. +#[component] +pub async fn person_content( + lang: Lang, + name: &str, + role: &str, + zone: &str, + last_sign_in: &str, + counts: &[(&'static str, String)], + recent: &[(String, String, String)], +) -> Result { + let role_line = fill(t(lang, K::PersonRole), &[role]); + Ok(view! { +

(name)

+

(role_line.as_str())

+
+
+ for (label, value) in counts.iter() { +
(*label)
(value.as_str())
+ } +
(t(lang, K::PersonZone))
(zone)
+
(t(lang, K::PersonLastSignIn))
(last_sign_in)
+
+
+
+

(t(lang, K::PersonRecent))

+ if recent.is_empty() { +

(t(lang, K::PersonNoActivity))

+ } +
    + for (when, sentence, task) in recent.iter() { +
  • + + " " + (sentence.as_str()) + " " + (task.as_str()) +
  • + } +
+
+

(t(lang, K::PersonBack))

+ }) +} diff --git a/deploy/ferron.conf b/deploy/ferron.conf new file mode 100644 index 0000000..0dc32e3 --- /dev/null +++ b/deploy/ferron.conf @@ -0,0 +1,17 @@ +# Ferron reverse proxy for iz. Same format as the forge example (ferron.conf, not KDL). +# Replace iz.example.com with the public host name (base_url in /etc/iz/iz.toml must match it). +# A bare host block gets automatic TLS. +# +# The proxy sends X-Forwarded-For for the client. iz reads that header only from peers listed in +# trusted_proxies; with Ferron on the same machine the peer is 127.0.0.1, so set +# trusted_proxies = ["127.0.0.1/32"] in iz.toml. +# +# Buffering is off because the live update streams (server-sent events) must reach the browser +# as they are written. +iz.example.com { + buffer_request 0 + buffer_response 0 + proxy { + upstream http://127.0.0.1:7654 + } +} diff --git a/deploy/iz.service b/deploy/iz.service new file mode 100644 index 0000000..506390c --- /dev/null +++ b/deploy/iz.service @@ -0,0 +1,52 @@ +# systemd unit for iz, the family task board. +# +# This file is installed by hand. Nothing enables it automatically: copy it to +# /etc/systemd/system/iz.service, run `systemctl daemon-reload`, then enable and +# start it yourself. See README.md, "First run". + +[Unit] +Description=iz family task board +After=network-online.target +Wants=network-online.target +StartLimitIntervalSec=60 +StartLimitBurst=5 + +[Service] +Type=simple +User=iz +Group=iz +ExecStart=/usr/local/bin/iz --config /etc/iz/iz.toml serve +WorkingDirectory=/var/lib/iz +Restart=on-failure +RestartSec=5 +UMask=0077 + +# Hardening +NoNewPrivileges=yes +ProtectSystem=strict +# Only the data directory is writable: database, iz.key, attachments, backups. +ReadWritePaths=/var/lib/iz +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProcSubset=pid +RestrictSUIDSGID=yes +RestrictRealtime=yes +RestrictNamespaces=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +LockPersonality=yes +MemoryDenyWriteExecute=yes +SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallErrorNumber=EPERM +CapabilityBoundingSet= +AmbientCapabilities= +KeyringMode=private + +[Install] +WantedBy=multi-user.target diff --git a/docs/architecture.md b/docs/architecture.md index 28e7704..e47d5e3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -213,10 +213,12 @@ Board page fingerprint is cheap (max `updated_at` + counts), so a burst of chang ## 10. CLI -`iz admin backup --out DIR` (DB snapshot + local attachments + manifest), `iz admin backup-verify SET`, -`iz admin restore --from SET --data-dir NEW`, `iz admin export --out DIR` (JSON of the board, tasks, comments, -activity, plus attachments by name), `iz admin set-role `, `iz admin audit-purge ---older-than-days N`. +`iz` (or `iz serve`) runs the server. `iz export --out DIR` writes the board as JSON with its attachments and a +manifest, and never writes outside `DIR`. `iz restore --from SET` verifies a backup set (manifest, digests, the +database's `integrity_check` and contiguous migrations) before it replaces the database and attachments in the +configured data directory, and keeps the files it replaces. `iz fsck` checks the database and the attachment bytes +read-only. Every command except `export` refuses while a server holds `data_dir/iz.lock`. Backups are written by +the `[backup]` worker (`VACUUM INTO` plus attachment copies and `manifest.json`, see `iz_core::manifest`). --- diff --git a/style/_components.scss b/style/_components.scss index 99cc0c5..874a823 100644 --- a/style/_components.scss +++ b/style/_components.scss @@ -313,3 +313,38 @@ textarea::placeholder { transition: none; } } + +// Admin pages: tables of projects, columns and members; name and value lists; inline forms; the colour swatch. +.admin-table { + width: 100%; + border-collapse: collapse; + td, th { padding: 0.4rem 0.5rem; vertical-align: middle; text-align: start; } +} +.inline { + display: inline-flex; + flex-wrap: wrap; + gap: 0.4rem; + align-items: center; +} +.facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 0.3rem 1rem; + dt { color: var(--muted); } + dd { margin: 0; } +} +.tone-dot { + display: inline-block; + width: 0.75em; + height: 0.75em; + border-radius: 50%; + background: var(--muted); + &[data-colour="c0"] { background: #c2d0ff; } + &[data-colour="c1"] { background: #9fe0b4; } + &[data-colour="c2"] { background: #f2c265; } + &[data-colour="c3"] { background: #f5a3a3; } + &[data-colour="c4"] { background: #a8d8f0; } + &[data-colour="c5"] { background: #d7b3f0; } + &[data-colour="c6"] { background: #ffd1a6; } + &[data-colour="c7"] { background: #c9d6c2; } +} diff --git a/style/_layout.scss b/style/_layout.scss index 3b94fb1..f252e3c 100644 --- a/style/_layout.scss +++ b/style/_layout.scss @@ -52,7 +52,7 @@ white-space: nowrap; } -.switcher a[aria-current="page"], +.switcher a[aria-current="true"], .switcher a:hover { background: var(--surface-2); color: var(--text);