Admin pages (tags, columns, members, limits, server), people cards, audit, family switcher, backups, sweeper, export/restore/fsck CLI, systemd unit, Ferron example, README
Browse files at this commitcc5a8a02f31f3768e4105e2f5e2f3ac6ac45d762Parent: de84062- feat
- admin pages (tags, columns, members, limits, server), people cards, audit, family switcher, backups, sweeper, export/restore/fsck CLI, systemd unit, Ferron example, README
45 changed files +5282 -100
- Cargo.lock +14 -0
- Cargo.toml +1 -0
- README.md +176 -0
- crates/iz-core/src/config.rs +6 -6
- crates/iz-core/src/lib.rs +1 -0
- crates/iz-core/src/manifest.rs +255 -0
- crates/iz-core/src/store/audit.rs +107 -0
- crates/iz-core/src/store/board.rs +64 -4
- crates/iz-core/src/store/export.rs +365 -0
- crates/iz-core/src/store/mod.rs +17 -0
- crates/iz-core/src/store/outbox.rs +3 -2
- crates/iz-core/src/store/people.rs +91 -0
- crates/iz-core/src/store/sweep.rs +120 -0
- crates/iz-web/Cargo.toml +1 -0
- crates/iz-web/src/auth.rs +15 -11
- crates/iz-web/src/backup.rs +270 -0
- crates/iz-web/src/boot.rs +9 -0
- crates/iz-web/src/cli/export.rs +291 -0
- crates/iz-web/src/cli/fsck.rs +314 -0
- crates/iz-web/src/cli/mod.rs +175 -0
- crates/iz-web/src/cli/restore.rs +457 -0
- crates/iz-web/src/family.rs +257 -0
- crates/iz-web/src/i18n/mod.rs +1 -0
- crates/iz-web/src/i18n/structure.rs +364 -0
- crates/iz-web/src/live.rs +4 -0
- crates/iz-web/src/main.rs +23 -57
- crates/iz-web/src/pages/admin.rs +102 -0
- crates/iz-web/src/pages/columns.rs +278 -0
- crates/iz-web/src/pages/logs.rs +13 -1
- crates/iz-web/src/pages/mod.rs +3 -0
- crates/iz-web/src/pages/people.rs +119 -0
- crates/iz-web/src/pages/rules.rs +50 -4
- crates/iz-web/src/pages/settings.rs +241 -5
- crates/iz-web/src/pages/tags.rs +323 -0
- crates/iz-web/src/pages/task.rs +8 -1
- crates/iz-web/src/state.rs +3 -0
- crates/iz-web/src/sweeper.rs +166 -0
- crates/iz-web/src/views/admin.rs +25 -0
- crates/iz-web/src/views/mod.rs +26 -4
- crates/iz-web/src/views/structure.rs +413 -0
- deploy/ferron.conf +17 -0
- deploy/iz.service +52 -0
- docs/architecture.md +6 -4
- style/_components.scss +35 -0
- style/_layout.scss +1 -1
Cargo.lockmodified+14 -0
| @@ -576,6 +576,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 576 | checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" | 576 | checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" |
| 577 | dependencies = [ | 577 | dependencies = [ |
| 578 | "clap_builder", | 578 | "clap_builder", |
| 579 | + "clap_derive", | ||
| 579 | ] | 580 | ] |
| 580 | 581 | ||
| 581 | [[package]] | 582 | [[package]] |
| @@ -590,6 +591,18 @@ dependencies = [ | |||
| 590 | "strsim", | 591 | "strsim", |
| 591 | ] | 592 | ] |
| 592 | 593 | ||
| 594 | +[[package]] | ||
| 595 | +name = "clap_derive" | ||
| 596 | +version = "4.6.7" | ||
| 597 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 598 | +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" | ||
| 599 | +dependencies = [ | ||
| 600 | + "heck", | ||
| 601 | + "proc-macro2", | ||
| 602 | + "quote", | ||
| 603 | + "syn 3.0.9", | ||
| 604 | +] | ||
| 605 | + | ||
| 593 | [[package]] | 606 | [[package]] |
| 594 | name = "clap_lex" | 607 | name = "clap_lex" |
| 595 | version = "1.1.1" | 608 | version = "1.1.1" |
| @@ -1896,6 +1909,7 @@ dependencies = [ | |||
| 1896 | "aws-lc-rs", | 1909 | "aws-lc-rs", |
| 1897 | "base64 0.23.1", | 1910 | "base64 0.23.1", |
| 1898 | "bytes", | 1911 | "bytes", |
| 1912 | + "clap", | ||
| 1899 | "futures-util", | 1913 | "futures-util", |
| 1900 | "grass", | 1914 | "grass", |
| 1901 | "hex", | 1915 | "hex", |
Cargo.tomlmodified+1 -0
| @@ -23,6 +23,7 @@ http = "1.5.0" | |||
| 23 | http-body = "1.1.0" | 23 | http-body = "1.1.0" |
| 24 | http-body-util = "0.1.5" | 24 | http-body-util = "0.1.5" |
| 25 | chacha20poly1305 = "0.11.0" | 25 | chacha20poly1305 = "0.11.0" |
| 26 | +clap = "4.6.7" | ||
| 26 | hex = "0.4.3" | 27 | hex = "0.4.3" |
| 27 | ipnet = "2.12.2" | 28 | ipnet = "2.12.2" |
| 28 | lettre = { version = "0.11.23", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] } | 29 | lettre = { version = "0.11.23", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] } |
README.mdadded+176 -0
| @@ -0,0 +1,176 @@ | |||
| 1 | +# iz | ||
| 2 | + | ||
| 3 | +iz is the family task board. It has columns, cards (with one level of subtasks, dependencies and | ||
| 4 | +assignees), projects (tags), deadlines with meeting times and reminders, comments, attachments with | ||
| 5 | +in-page viewers (images, media, PDF, spreadsheets, slides), an activity trail, and admin-defined mail | ||
| 6 | +rules with a durable outbox. Sign-in goes through the family's `im` identity provider. | ||
| 7 | + | ||
| 8 | +Design notes are in `docs/architecture.md`. The HTTP contracts with `im` and `in` are in | ||
| 9 | +`docs/contracts.md`, and the code conventions are in `docs/conventions.md`. | ||
| 10 | + | ||
| 11 | +## Build | ||
| 12 | + | ||
| 13 | +```sh | ||
| 14 | +cargo build --release -p iz-web | ||
| 15 | +``` | ||
| 16 | + | ||
| 17 | +The binary is `target/release/iz`. Nothing in the build or the runtime uses Node. Use `bun` for any | ||
| 18 | +JavaScript tooling. | ||
| 19 | + | ||
| 20 | +## Configuration | ||
| 21 | + | ||
| 22 | +Copy the example and edit it: | ||
| 23 | + | ||
| 24 | +```sh | ||
| 25 | +cp config/iz.example.toml config/iz.toml | ||
| 26 | +``` | ||
| 27 | + | ||
| 28 | +Or pass any path with `--config <path>`. The config path is chosen in this order: the `--config` | ||
| 29 | +flag, then the `IZ_CONFIG` environment variable, then `config/iz.toml`. If the file does not exist, | ||
| 30 | +iz writes the example there on first run. | ||
| 31 | + | ||
| 32 | +Keys: | ||
| 33 | + | ||
| 34 | +| Key | Meaning | | ||
| 35 | +|---|---| | ||
| 36 | +| `database` | SQLite database file. Its `-wal` and `-shm` files sit next to it. | | ||
| 37 | +| `data_dir` | Directory for `iz.key`, the lock file, attachments and other local files. | | ||
| 38 | +| `listen` | HTTP listen address. Keep it on `127.0.0.1` behind the reverse proxy. | | ||
| 39 | +| `base_url` | Public URL used in links and mail. `https://` or `http://`, no trailing slash. | | ||
| 40 | +| `trusted_proxies` | Peers whose `X-Forwarded-For` is trusted for client IPs. IPs or CIDR networks. | | ||
| 41 | +| `[oidc]` | `issuer` (the `im` origin, `https://`, no trailing slash), `client_id`, `client_secret_file`. Remove the section to run without sign-in. | | ||
| 42 | +| `[in_store]` | `enabled`. Stores attachments in the `in` Files service instead of local disk. Off by default. | | ||
| 43 | +| `[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. | | ||
| 44 | + | ||
| 45 | +Unknown keys are an error at boot, so a typo stops the start instead of being ignored. | ||
| 46 | + | ||
| 47 | +Secrets are never in the TOML: | ||
| 48 | + | ||
| 49 | +- The OIDC client secret goes in the file named by `client_secret_file`. The file must be mode | ||
| 50 | + `0600` or `0400`, owned by the service user. iz reads it at boot. | ||
| 51 | +- The SMTP password is entered in the `/settings` page. iz seals it in the database. | ||
| 52 | + | ||
| 53 | +## Production layout | ||
| 54 | + | ||
| 55 | +The example unit and reverse proxy config assume this layout: | ||
| 56 | + | ||
| 57 | +- `/usr/local/bin/iz`: the binary. | ||
| 58 | +- `/etc/iz/iz.toml`: the config. `data_dir = "/var/lib/iz/data"` and `database = "/var/lib/iz/data/iz.db"`. | ||
| 59 | +- `/etc/iz/oidc_client_secret`: the client secret, mode `0600`, owned by `iz`. | ||
| 60 | +- `/var/lib/iz`: the working directory. The data lives in `/var/lib/iz/data`. Backups can go in | ||
| 61 | + `/var/lib/iz/backups`. The unit makes all of `/var/lib/iz` writable and nothing else. | ||
| 62 | + | ||
| 63 | +The reverse proxy example is `deploy/ferron.conf`. The unit is `deploy/iz.service`. | ||
| 64 | + | ||
| 65 | +## First run | ||
| 66 | + | ||
| 67 | +1. Create the service user and directories: | ||
| 68 | + | ||
| 69 | + ```sh | ||
| 70 | + sudo useradd --system --home-dir /var/lib/iz --shell /usr/sbin/nologin iz | ||
| 71 | + sudo install -d -m 0750 -o iz -g iz /var/lib/iz /var/lib/iz/data | ||
| 72 | + sudo install -d -m 0750 -o root -g iz /etc/iz | ||
| 73 | + ``` | ||
| 74 | + | ||
| 75 | +2. Install the binary and the config: | ||
| 76 | + | ||
| 77 | + ```sh | ||
| 78 | + sudo install -m 0755 target/release/iz /usr/local/bin/iz | ||
| 79 | + sudo install -m 0640 -o root -g iz config/iz.toml /etc/iz/iz.toml | ||
| 80 | + ``` | ||
| 81 | + | ||
| 82 | + Edit `/etc/iz/iz.toml` so `data_dir`, `database` and `base_url` match the layout above. | ||
| 83 | + | ||
| 84 | +3. Register the client at `im` and write its secret file (see the next section). | ||
| 85 | + | ||
| 86 | +4. Install the unit by hand. Nothing enables it for you: | ||
| 87 | + | ||
| 88 | + ```sh | ||
| 89 | + sudo install -m 0644 deploy/iz.service /etc/systemd/system/iz.service | ||
| 90 | + sudo systemctl daemon-reload | ||
| 91 | + sudo systemctl enable --now iz | ||
| 92 | + ``` | ||
| 93 | + | ||
| 94 | +5. Check it answers: `curl -fsS http://127.0.0.1:7654/healthz` should print `ok <build sha>`. | ||
| 95 | + | ||
| 96 | +On the first run iz creates `iz.key` in `data_dir` (32 random bytes, mode `0600`). Sealed secrets in the | ||
| 97 | +database, including the SMTP password, cannot be read without this key. Back up `iz.key` together with | ||
| 98 | +the database, and store the copy somewhere other than the server. Losing `iz.key` means re-entering the | ||
| 99 | +SMTP password and the sealed values, and any backup that lacks the key cannot restore those secrets. | ||
| 100 | + | ||
| 101 | +## Registering the client at im | ||
| 102 | + | ||
| 103 | +iz is a client of `im`. Register it on the machine where `im` runs, with the `im` tools: | ||
| 104 | + | ||
| 105 | +```sh | ||
| 106 | +im client add --name iz --family-key iz \ | ||
| 107 | + --redirect-uri https://iz.example.com/auth/callback \ | ||
| 108 | + --post-logout-uri https://iz.example.com/ \ | ||
| 109 | + --backchannel-uri https://iz.example.com/auth/backchannel-logout \ | ||
| 110 | + --scopes "openid profile email directory.read" | ||
| 111 | +``` | ||
| 112 | + | ||
| 113 | +Replace `https://iz.example.com` with your `base_url`. If the flags differ, run `im client add --help`. | ||
| 114 | + | ||
| 115 | +- `im` prints `client_id` and `client_secret`. The secret is shown once. Save it into the file named | ||
| 116 | + by `client_secret_file`, mode `0600`, owned by `iz`. | ||
| 117 | +- `im` generates the `client_id` itself. Copy the printed value into `client_id` in `iz.toml`. | ||
| 118 | +- The scopes must include `openid profile email` for sign-in and `directory.read` for the people | ||
| 119 | + directory. | ||
| 120 | +- The redirect, post-logout and back-channel URLs are the paths iz serves: `{base_url}/auth/callback`, | ||
| 121 | + `{base_url}/` and `{base_url}/auth/backchannel-logout`. | ||
| 122 | + | ||
| 123 | +Then set the `[oidc]` section in `iz.toml`: | ||
| 124 | + | ||
| 125 | +```toml | ||
| 126 | +[oidc] | ||
| 127 | +issuer = "https://im.example.com" | ||
| 128 | +client_id = "<the client_id im printed>" | ||
| 129 | +client_secret_file = "/etc/iz/oidc_client_secret" | ||
| 130 | +``` | ||
| 131 | + | ||
| 132 | +Restart iz after changing the config. `im client list` shows the registered clients, and | ||
| 133 | +`im client disable <client_id>` turns one off. | ||
| 134 | + | ||
| 135 | +## Backups | ||
| 136 | + | ||
| 137 | +With a `[backup]` section, iz writes a backup set into `dir` every `interval_hours` and keeps the newest | ||
| 138 | +`keep` sets. A set is a directory with: | ||
| 139 | + | ||
| 140 | +- `iz.db`: a consistent copy of the database, | ||
| 141 | +- `attachments/`: the local attachment files, | ||
| 142 | +- `manifest.json`: a SHA-256 for each file. | ||
| 143 | + | ||
| 144 | +Backups do not copy `iz.key`. Keep that copy separately, as described in First run. | ||
| 145 | + | ||
| 146 | +Restore with the server stopped: | ||
| 147 | + | ||
| 148 | +```sh | ||
| 149 | +sudo systemctl stop iz | ||
| 150 | +iz restore --from /var/lib/iz/backups/<set dir> | ||
| 151 | +sudo systemctl start iz | ||
| 152 | +``` | ||
| 153 | + | ||
| 154 | +`iz restore` checks the set against `manifest.json` before it writes anything. A set that fails the | ||
| 155 | +check is not restored. Do not copy the live database file by hand: it is written while iz runs. | ||
| 156 | + | ||
| 157 | +## Command line | ||
| 158 | + | ||
| 159 | +Run these as the `iz` user, or with `sudo -u iz`, using the same config as the server. | ||
| 160 | + | ||
| 161 | +- `iz serve`: run the server. This is the default when no command is given. | ||
| 162 | +- `iz export --out DIR`: write an export into `DIR`. It never writes outside `DIR`. | ||
| 163 | +- `iz restore --from <set dir>`: restore a backup set. The server must be stopped. | ||
| 164 | +- `iz fsck`: check the database and files. It is read-only. | ||
| 165 | + | ||
| 166 | +`export`, `restore` and `fsck` refuse to run while the server holds the lock file `data_dir/iz.lock`. | ||
| 167 | +Stop the service first. Exit status is 0 for success, 1 for a failure, and 2 for a usage error. | ||
| 168 | + | ||
| 169 | +Logs go to stderr at `info` level. Set `RUST_LOG` to change the level. Under systemd, read them with | ||
| 170 | +`journalctl -u iz`. | ||
| 171 | + | ||
| 172 | +## Where to read more | ||
| 173 | + | ||
| 174 | +- `docs/architecture.md`: modules, data model, routes, workers and rules. | ||
| 175 | +- `docs/contracts.md`: the HTTP contracts shared with `im` (sign-in, logout, directory) and `in` (object store). | ||
| 176 | +- `docs/conventions.md`: boot order, config rules, store and deploy rules. | ||
crates/iz-core/src/config.rsmodified+6 -6
| @@ -71,10 +71,10 @@ pub struct InStoreConfig { | |||
| 71 | pub struct BackupConfig { | 71 | pub struct BackupConfig { |
| 72 | /// Directory that receives the backup sets. | 72 | /// Directory that receives the backup sets. |
| 73 | pub dir: PathBuf, | 73 | pub dir: PathBuf, |
| 74 | - /// Hours between backups. Between 1 and 720. | 74 | + /// Hours between backups. Between 1 and 168 (one week). |
| 75 | #[serde(default = "default_backup_interval_hours")] | 75 | #[serde(default = "default_backup_interval_hours")] |
| 76 | pub interval_hours: u32, | 76 | pub interval_hours: u32, |
| 77 | - /// Backup sets to keep. Between 1 and 365. | 77 | + /// Finished backup sets to keep; older sets are deleted after each backup. At least 1. |
| 78 | #[serde(default = "default_backup_keep")] | 78 | #[serde(default = "default_backup_keep")] |
| 79 | pub keep: u32, | 79 | pub keep: u32, |
| 80 | /// Optional URL pinged after each successful backup (for example a dead-man's switch). | 80 | /// Optional URL pinged after each successful backup (for example a dead-man's switch). |
| @@ -186,13 +186,13 @@ impl Config { | |||
| 186 | if backup.dir.as_os_str().is_empty() { | 186 | if backup.dir.as_os_str().is_empty() { |
| 187 | return Err(Error::Config("backup.dir must not be empty".into())); | 187 | return Err(Error::Config("backup.dir must not be empty".into())); |
| 188 | } | 188 | } |
| 189 | - if !(1..=720).contains(&backup.interval_hours) { | 189 | + if !(1..=168).contains(&backup.interval_hours) { |
| 190 | return Err(Error::Config( | 190 | return Err(Error::Config( |
| 191 | - "backup.interval_hours must be 1 to 720".into(), | 191 | + "backup.interval_hours must be 1 to 168".into(), |
| 192 | )); | 192 | )); |
| 193 | } | 193 | } |
| 194 | - if !(1..=365).contains(&backup.keep) { | 194 | + if backup.keep == 0 { |
| 195 | - return Err(Error::Config("backup.keep must be 1 to 365".into())); | 195 | + return Err(Error::Config("backup.keep must be at least 1".into())); |
| 196 | } | 196 | } |
| 197 | if let Some(url) = &backup.healthcheck_url | 197 | if let Some(url) = &backup.healthcheck_url |
| 198 | && !(url.starts_with("https://") || url.starts_with("http://")) | 198 | && !(url.starts_with("https://") || url.starts_with("http://")) |
crates/iz-core/src/lib.rsmodified+1 -0
| @@ -11,6 +11,7 @@ pub mod config; | |||
| 11 | pub mod error; | 11 | pub mod error; |
| 12 | pub mod limits; | 12 | pub mod limits; |
| 13 | pub mod mail_text; | 13 | pub mod mail_text; |
| 14 | +pub mod manifest; | ||
| 14 | pub mod preview; | 15 | pub mod preview; |
| 15 | pub mod rules; | 16 | pub mod rules; |
| 16 | pub mod secret; | 17 | pub mod secret; |
crates/iz-core/src/manifest.rsadded+255 -0
| @@ -0,0 +1,255 @@ | |||
| 1 | +//! The manifest of a backup set: the list of files in the set with their sizes and SHA-256 digests, and | ||
| 2 | +//! the check that a set on disk still matches it. | ||
| 3 | +//! | ||
| 4 | +//! A set is one directory: `manifest.json` plus the files it lists, with `/`-separated relative paths. | ||
| 5 | +//! The writer (`iz-web` backup worker) writes every listed file first and the manifest last, so a set | ||
| 6 | +//! without a manifest is an unfinished set. The verifier (`iz restore`, `iz fsck`) refuses a set when a | ||
| 7 | +//! listed file is missing, has another size or digest, a path is unsafe (absolute, `..`, a link), or a | ||
| 8 | +//! file is in the directory that the manifest does not list. A manifest that is not valid JSON, or | ||
| 9 | +//! names another version, is refused too. | ||
| 10 | +//! | ||
| 11 | +//! The manifest only detects changes to the set: someone who rewrites files and the manifest together | ||
| 12 | +//! is not caught. Keeping the backup directory readable only by the service user is the protection | ||
| 13 | +//! against that. | ||
| 14 | + | ||
| 15 | +use std::collections::BTreeSet; | ||
| 16 | +use std::fs::File; | ||
| 17 | +use std::io::Read; | ||
| 18 | +use std::path::{Component, Path, PathBuf}; | ||
| 19 | + | ||
| 20 | +use serde::{Deserialize, Serialize}; | ||
| 21 | +use sha2::{Digest, Sha256}; | ||
| 22 | + | ||
| 23 | +use crate::error::{Error, Result}; | ||
| 24 | + | ||
| 25 | +/// The file name of the manifest inside a set. | ||
| 26 | +pub const MANIFEST_NAME: &str = "manifest.json"; | ||
| 27 | +/// The only manifest version this build reads and writes. | ||
| 28 | +pub const MANIFEST_VERSION: u32 = 1; | ||
| 29 | +/// Largest manifest read, in bytes. Reason: a manifest lists files; a huge one is not ours. | ||
| 30 | +pub const MANIFEST_MAX_BYTES: u64 = 16 * 1024 * 1024; | ||
| 31 | + | ||
| 32 | +/// One file of a set. | ||
| 33 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 34 | +pub struct ManifestFile { | ||
| 35 | + /// Path inside the set, `/`-separated, relative, without `..` or a leading `/`. | ||
| 36 | + pub path: String, | ||
| 37 | + /// Size in bytes. | ||
| 38 | + pub size: u64, | ||
| 39 | + /// SHA-256 of the contents, lowercase hex. | ||
| 40 | + pub sha256: String, | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// The manifest as stored in `manifest.json`. | ||
| 44 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 45 | +pub struct Manifest { | ||
| 46 | + /// Always [`MANIFEST_VERSION`] for this build. | ||
| 47 | + pub version: u32, | ||
| 48 | + /// UTC stamp of when the set was written. | ||
| 49 | + pub created_at: String, | ||
| 50 | + /// The build that wrote the set. | ||
| 51 | + pub build: String, | ||
| 52 | + /// Every file of the set except the manifest itself. | ||
| 53 | + pub files: Vec<ManifestFile>, | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +/// The SHA-256 and size of one file, read in chunks. | ||
| 57 | +pub fn digest_file(path: &Path) -> Result<(u64, String)> { | ||
| 58 | + let mut file = File::open(path)?; | ||
| 59 | + let mut hasher = Sha256::new(); | ||
| 60 | + let mut size: u64 = 0; | ||
| 61 | + let mut buffer = vec![0u8; 64 * 1024]; | ||
| 62 | + loop { | ||
| 63 | + let read = file.read(&mut buffer)?; | ||
| 64 | + if read == 0 { | ||
| 65 | + break; | ||
| 66 | + } | ||
| 67 | + hasher.update(&buffer[..read]); | ||
| 68 | + size += read as u64; | ||
| 69 | + } | ||
| 70 | + Ok((size, hex::encode(hasher.finalize()))) | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Whether `path` is a safe relative set path: non-empty, no leading `/`, no `..`, no `.`, no empty | ||
| 74 | +/// component, no NUL or backslash. | ||
| 75 | +pub fn is_safe_relative(path: &str) -> bool { | ||
| 76 | + if path.is_empty() || path.contains('\0') || path.contains('\\') { | ||
| 77 | + return false; | ||
| 78 | + } | ||
| 79 | + !path.split('/').any(str::is_empty) | ||
| 80 | + && Path::new(path) | ||
| 81 | + .components() | ||
| 82 | + .all(|component| matches!(component, Component::Normal(_))) | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// Writes `manifest.json` into `dir` with the given files. Each listed file must already exist in | ||
| 86 | +/// `dir` and is hashed here, so the manifest describes what is on disk. The manifest is written to a | ||
| 87 | +/// temporary name and renamed into place, so a crash leaves either no manifest or a whole one. | ||
| 88 | +pub fn write_manifest( | ||
| 89 | + dir: &Path, | ||
| 90 | + created_at: &str, | ||
| 91 | + build: &str, | ||
| 92 | + paths: &[String], | ||
| 93 | +) -> Result<Manifest> { | ||
| 94 | + let mut files = Vec::with_capacity(paths.len()); | ||
| 95 | + for path in paths { | ||
| 96 | + if !is_safe_relative(path) { | ||
| 97 | + return Err(Error::Invalid(format!( | ||
| 98 | + "unsafe path in a backup set: {path}" | ||
| 99 | + ))); | ||
| 100 | + } | ||
| 101 | + let (size, sha256) = digest_file(&dir.join(path))?; | ||
| 102 | + files.push(ManifestFile { | ||
| 103 | + path: path.clone(), | ||
| 104 | + size, | ||
| 105 | + sha256, | ||
| 106 | + }); | ||
| 107 | + } | ||
| 108 | + let manifest = Manifest { | ||
| 109 | + version: MANIFEST_VERSION, | ||
| 110 | + created_at: created_at.to_owned(), | ||
| 111 | + build: build.to_owned(), | ||
| 112 | + files, | ||
| 113 | + }; | ||
| 114 | + let json = serde_json::to_vec_pretty(&manifest) | ||
| 115 | + .map_err(|e| Error::Invalid(format!("encoding the manifest: {e}")))?; | ||
| 116 | + let tmp = dir.join(format!("{MANIFEST_NAME}.tmp")); | ||
| 117 | + std::fs::write(&tmp, json)?; | ||
| 118 | + File::open(&tmp)?.sync_all()?; | ||
| 119 | + std::fs::rename(&tmp, dir.join(MANIFEST_NAME))?; | ||
| 120 | + Ok(manifest) | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// Reads and checks a set. Returns the manifest when every listed file matches its size and digest and | ||
| 124 | +/// no other file sits in the set. Errors name the first problem found. | ||
| 125 | +pub fn verify_set(dir: &Path) -> Result<Manifest> { | ||
| 126 | + let manifest = read_manifest(&dir.join(MANIFEST_NAME))?; | ||
| 127 | + let mut listed = BTreeSet::new(); | ||
| 128 | + for file in &manifest.files { | ||
| 129 | + if !is_safe_relative(&file.path) { | ||
| 130 | + return Err(refused(format!( | ||
| 131 | + "unsafe path in the manifest: {}", | ||
| 132 | + file.path | ||
| 133 | + ))); | ||
| 134 | + } | ||
| 135 | + if !listed.insert(file.path.clone()) { | ||
| 136 | + return Err(refused(format!("the manifest lists {} twice", file.path))); | ||
| 137 | + } | ||
| 138 | + let path = dir.join(&file.path); | ||
| 139 | + let meta = std::fs::symlink_metadata(&path) | ||
| 140 | + .map_err(|_| refused(format!("missing from the set: {}", file.path)))?; | ||
| 141 | + if !meta.file_type().is_file() { | ||
| 142 | + return Err(refused(format!("not a regular file: {}", file.path))); | ||
| 143 | + } | ||
| 144 | + let (size, sha256) = digest_file(&path)?; | ||
| 145 | + if size != file.size || sha256 != file.sha256 { | ||
| 146 | + return Err(refused(format!( | ||
| 147 | + "changed since the set was written: {}", | ||
| 148 | + file.path | ||
| 149 | + ))); | ||
| 150 | + } | ||
| 151 | + } | ||
| 152 | + let mut on_disk = BTreeSet::new(); | ||
| 153 | + collect_files(dir, dir, &mut on_disk)?; | ||
| 154 | + on_disk.remove(MANIFEST_NAME); | ||
| 155 | + if let Some(extra) = on_disk.difference(&listed).next() { | ||
| 156 | + return Err(refused(format!("not listed in the manifest: {extra}"))); | ||
| 157 | + } | ||
| 158 | + Ok(manifest) | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +/// Reads the manifest with its size limit and checks its version. | ||
| 162 | +pub fn read_manifest(path: &Path) -> Result<Manifest> { | ||
| 163 | + let meta = std::fs::symlink_metadata(path) | ||
| 164 | + .map_err(|_| refused("the set has no manifest".to_owned()))?; | ||
| 165 | + if !meta.file_type().is_file() || meta.len() > MANIFEST_MAX_BYTES { | ||
| 166 | + return Err(refused( | ||
| 167 | + "the manifest is not a regular file of a sane size".to_owned(), | ||
| 168 | + )); | ||
| 169 | + } | ||
| 170 | + let bytes = std::fs::read(path)?; | ||
| 171 | + let manifest: Manifest = serde_json::from_slice(&bytes) | ||
| 172 | + .map_err(|e| refused(format!("the manifest is not valid: {e}")))?; | ||
| 173 | + if manifest.version != MANIFEST_VERSION { | ||
| 174 | + return Err(refused(format!( | ||
| 175 | + "the manifest has version {}, this build reads {MANIFEST_VERSION}", | ||
| 176 | + manifest.version | ||
| 177 | + ))); | ||
| 178 | + } | ||
| 179 | + Ok(manifest) | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// Every regular file below `root` as a `/`-separated path relative to `base`. Links and other | ||
| 183 | +/// non-regular entries are refused, so a set cannot hide a file behind a link. | ||
| 184 | +fn collect_files(base: &Path, dir: &Path, out: &mut BTreeSet<String>) -> Result<()> { | ||
| 185 | + for entry in std::fs::read_dir(dir)? { | ||
| 186 | + let entry = entry?; | ||
| 187 | + let path: PathBuf = entry.path(); | ||
| 188 | + let meta = std::fs::symlink_metadata(&path)?; | ||
| 189 | + if meta.file_type().is_dir() { | ||
| 190 | + collect_files(base, &path, out)?; | ||
| 191 | + } else if meta.file_type().is_file() { | ||
| 192 | + let relative = path | ||
| 193 | + .strip_prefix(base) | ||
| 194 | + .map_err(|_| refused("a file escaped the set".to_owned()))?; | ||
| 195 | + let text = relative | ||
| 196 | + .components() | ||
| 197 | + .map(|c| c.as_os_str().to_string_lossy().into_owned()) | ||
| 198 | + .collect::<Vec<_>>() | ||
| 199 | + .join("/"); | ||
| 200 | + out.insert(text); | ||
| 201 | + } else { | ||
| 202 | + return Err(refused(format!("not a regular file: {}", path.display()))); | ||
| 203 | + } | ||
| 204 | + } | ||
| 205 | + Ok(()) | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +/// A refused set: the manifest's problem as the user reads it. | ||
| 209 | +fn refused(text: String) -> Error { | ||
| 210 | + Error::Invalid(format!("the backup set is refused: {text}")) | ||
| 211 | +} | ||
| 212 | + | ||
| 213 | +#[cfg(test)] | ||
| 214 | +mod tests { | ||
| 215 | + use super::*; | ||
| 216 | + | ||
| 217 | + #[test] | ||
| 218 | + fn a_relative_path_must_stay_inside_the_set() { | ||
| 219 | + assert!(is_safe_relative("iz.db")); | ||
| 220 | + assert!(is_safe_relative("attachments/0a/01J")); | ||
| 221 | + for bad in [ | ||
| 222 | + "", | ||
| 223 | + "/etc/passwd", | ||
| 224 | + "../x", | ||
| 225 | + "a/../b", | ||
| 226 | + "a//b", | ||
| 227 | + "a/", | ||
| 228 | + "./a", | ||
| 229 | + "a\\b", | ||
| 230 | + "a\0b", | ||
| 231 | + ] { | ||
| 232 | + assert!(!is_safe_relative(bad), "accepted {bad:?}"); | ||
| 233 | + } | ||
| 234 | + } | ||
| 235 | + | ||
| 236 | + #[test] | ||
| 237 | + fn a_tampered_file_or_an_extra_file_is_refused() { | ||
| 238 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 239 | + std::fs::write(dir.path().join("iz.db"), b"one").expect("write"); | ||
| 240 | + write_manifest( | ||
| 241 | + dir.path(), | ||
| 242 | + "2026-10-28T00:00:00.000000000Z", | ||
| 243 | + "t", | ||
| 244 | + &["iz.db".into()], | ||
| 245 | + ) | ||
| 246 | + .expect("manifest"); | ||
| 247 | + verify_set(dir.path()).expect("a fresh set verifies"); | ||
| 248 | + | ||
| 249 | + std::fs::write(dir.path().join("iz.db"), b"two").expect("tamper"); | ||
| 250 | + assert!(verify_set(dir.path()).is_err()); | ||
| 251 | + std::fs::write(dir.path().join("iz.db"), b"one").expect("restore"); | ||
| 252 | + std::fs::write(dir.path().join("extra"), b"x").expect("extra"); | ||
| 253 | + assert!(verify_set(dir.path()).is_err()); | ||
| 254 | + } | ||
| 255 | +} | ||
crates/iz-core/src/store/audit.rsadded+107 -0
| @@ -0,0 +1,107 @@ | |||
| 1 | +//! The audit trail of administrator and account actions: one append-only row per action, written after | ||
| 2 | +//! the change it records has committed. | ||
| 3 | +//! | ||
| 4 | +//! A failed audit write never fails the request. The write is logged at error level and the caller gets | ||
| 5 | +//! nothing back, because a request that already changed data must still answer as a success. The `data` | ||
| 6 | +//! column holds what an operator needs to read the action (names, roles, counts), never a password, a | ||
| 7 | +//! token, a cookie or a secret: the caller is responsible for that. | ||
| 8 | + | ||
| 9 | +use serde_json::Value; | ||
| 10 | + | ||
| 11 | +use super::{db_err, new_id}; | ||
| 12 | +use crate::error::Result; | ||
| 13 | +use crate::store::Store; | ||
| 14 | +use crate::time::now_stamp; | ||
| 15 | + | ||
| 16 | +/// The kinds of actor an audit row can name. Matches the CHECK constraint of `audit_log.actor_kind`. | ||
| 17 | +pub const ACTOR_KINDS: [&str; 4] = ["member", "admin", "system", "anonymous"]; | ||
| 18 | + | ||
| 19 | +/// One row to append. `actor_id` is the member id (the OIDC `sub`) when there is one. | ||
| 20 | +#[derive(Debug, Clone)] | ||
| 21 | +pub struct AuditEntry<'a> { | ||
| 22 | + /// The member who acted, if any. | ||
| 23 | + pub actor: Option<&'a str>, | ||
| 24 | + /// `member`, `admin`, `system` or `anonymous`. | ||
| 25 | + pub actor_kind: &'static str, | ||
| 26 | + /// Dotted action name, for example `role.set` or `tag.delete`. | ||
| 27 | + pub action: &'static str, | ||
| 28 | + /// What kind of thing was changed, for example `member`, `tag`, `column`, `settings`. | ||
| 29 | + pub target_kind: &'static str, | ||
| 30 | + /// The id of the changed thing, if it has one. | ||
| 31 | + pub target_id: Option<&'a str>, | ||
| 32 | + /// The client address as iz saw it, when the request has one. | ||
| 33 | + pub ip: Option<&'a str>, | ||
| 34 | + /// Details for the operator. Never a secret. | ||
| 35 | + pub data: Value, | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +impl Store { | ||
| 39 | + /// Appends one audit row. Never fails: an error is logged and dropped, so the caller's answer does | ||
| 40 | + /// not depend on the audit trail. Call it after the change commits. | ||
| 41 | + pub async fn audit(&self, entry: AuditEntry<'_>) { | ||
| 42 | + if let Err(error) = self.append_audit(&entry).await { | ||
| 43 | + tracing::error!( | ||
| 44 | + error = %error, | ||
| 45 | + action = entry.action, | ||
| 46 | + "audit: could not record an action" | ||
| 47 | + ); | ||
| 48 | + } | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + /// The write behind [`Store::audit`]. Returns the error instead of logging it, so tests can check it. | ||
| 52 | + pub async fn append_audit(&self, entry: &AuditEntry<'_>) -> Result<()> { | ||
| 53 | + let data = serde_json::to_string(&entry.data).unwrap_or_else(|_| "{}".to_owned()); | ||
| 54 | + let conn = self.inner.conn.lock().await; | ||
| 55 | + conn.execute( | ||
| 56 | + "INSERT INTO audit_log (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data) \ | ||
| 57 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | ||
| 58 | + ( | ||
| 59 | + new_id(), | ||
| 60 | + now_stamp(), | ||
| 61 | + entry.actor.map(str::to_owned), | ||
| 62 | + entry.actor_kind.to_owned(), | ||
| 63 | + entry.action.to_owned(), | ||
| 64 | + entry.target_kind.to_owned(), | ||
| 65 | + entry.target_id.map(str::to_owned), | ||
| 66 | + entry.ip.map(str::to_owned), | ||
| 67 | + data, | ||
| 68 | + ), | ||
| 69 | + ) | ||
| 70 | + .await | ||
| 71 | + .map_err(db_err)?; | ||
| 72 | + Ok(()) | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +#[cfg(test)] | ||
| 77 | +mod tests { | ||
| 78 | + use super::*; | ||
| 79 | + | ||
| 80 | + #[tokio::test] | ||
| 81 | + async fn an_audit_row_is_appended_with_its_action() { | ||
| 82 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 83 | + let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); | ||
| 84 | + store | ||
| 85 | + .append_audit(&AuditEntry { | ||
| 86 | + actor: Some("sub-1"), | ||
| 87 | + actor_kind: "admin", | ||
| 88 | + action: "role.set", | ||
| 89 | + target_kind: "member", | ||
| 90 | + target_id: Some("sub-2"), | ||
| 91 | + ip: None, | ||
| 92 | + data: serde_json::json!({"role": "viewer"}), | ||
| 93 | + }) | ||
| 94 | + .await | ||
| 95 | + .expect("append"); | ||
| 96 | + let conn = store.read_conn().await; | ||
| 97 | + let count = super::super::fetch_opt( | ||
| 98 | + &conn, | ||
| 99 | + "SELECT COUNT(*) FROM audit_log WHERE action = 'role.set' AND actor_kind = 'admin'", | ||
| 100 | + (), | ||
| 101 | + |row| super::super::col_int(row, 0), | ||
| 102 | + ) | ||
| 103 | + .await | ||
| 104 | + .expect("count"); | ||
| 105 | + assert_eq!(count, Some(1)); | ||
| 106 | + } | ||
| 107 | +} | ||
crates/iz-core/src/store/board.rsmodified+64 -4
| @@ -26,8 +26,6 @@ const DEFAULT_COLUMNS: [(&str, bool); 4] = [ | |||
| 26 | ]; | 26 | ]; |
| 27 | /// Name of the tag every task wears when no other is chosen. | 27 | /// Name of the tag every task wears when no other is chosen. |
| 28 | pub const DEFAULT_TAG_NAME: &str = "General"; | 28 | pub const DEFAULT_TAG_NAME: &str = "General"; |
| 29 | -/// Longest tag colour name, in characters. Reason: colours come from a short fixed palette. | ||
| 30 | -const COLOR_MAX: usize = 20; | ||
| 31 | 29 | ||
| 32 | /// The board row. | 30 | /// The board row. |
| 33 | #[derive(Debug, Clone, PartialEq, Eq)] | 31 | #[derive(Debug, Clone, PartialEq, Eq)] |
| @@ -124,6 +122,17 @@ fn map_tag(row: &turso::Row) -> Result<Tag> { | |||
| 124 | } | 122 | } |
| 125 | 123 | ||
| 126 | /// A board key prefix: two to six uppercase ASCII letters. | 124 | /// A board key prefix: two to six uppercase ASCII letters. |
| 125 | +/// The number of colours in the fixed project palette. The names are `c0` to `c{TAG_COLOURS - 1}`; the | ||
| 126 | +/// board view maps each name to one tone of the stylesheet. | ||
| 127 | +pub const TAG_COLOURS: usize = 8; | ||
| 128 | + | ||
| 129 | +/// Whether `name` is one colour of the fixed palette (`c0` to `c7`). | ||
| 130 | +pub fn valid_colour(name: &str) -> bool { | ||
| 131 | + name.strip_prefix('c') | ||
| 132 | + .and_then(|n| n.parse::<usize>().ok()) | ||
| 133 | + .is_some_and(|n| n < TAG_COLOURS && name == format!("c{n}")) | ||
| 134 | +} | ||
| 135 | + | ||
| 127 | pub fn valid_prefix(prefix: &str) -> bool { | 136 | pub fn valid_prefix(prefix: &str) -> bool { |
| 128 | (2..=6).contains(&prefix.len()) && prefix.bytes().all(|b| b.is_ascii_uppercase()) | 137 | (2..=6).contains(&prefix.len()) && prefix.bytes().all(|b| b.is_ascii_uppercase()) |
| 129 | } | 138 | } |
| @@ -463,8 +472,8 @@ impl Store { | |||
| 463 | pub async fn add_tag(&self, board_id: &str, name: &str, color: Option<&str>) -> Result<Tag> { | 472 | pub async fn add_tag(&self, board_id: &str, name: &str, color: Option<&str>) -> Result<Tag> { |
| 464 | let name = clean_tag_name(name)?; | 473 | let name = clean_tag_name(name)?; |
| 465 | let color = match color.map(str::trim).filter(|c| !c.is_empty()) { | 474 | let color = match color.map(str::trim).filter(|c| !c.is_empty()) { |
| 466 | - Some(c) if c.chars().count() <= COLOR_MAX => Some(c.to_owned()), | 475 | + Some(c) if valid_colour(c) => Some(c.to_owned()), |
| 467 | - Some(_) => return Err(Error::Invalid("colour name is too long".into())), | 476 | + Some(_) => return Err(Error::Invalid("that colour is not in the palette".into())), |
| 468 | None => None, | 477 | None => None, |
| 469 | }; | 478 | }; |
| 470 | let conn = self.inner.conn.lock().await; | 479 | let conn = self.inner.conn.lock().await; |
| @@ -502,6 +511,57 @@ impl Store { | |||
| 502 | finish(tx, outcome).await | 511 | finish(tx, outcome).await |
| 503 | } | 512 | } |
| 504 | 513 | ||
| 514 | + /// Sets the colour of a project from the fixed palette, or clears it (`None`). `NotFound` for a tag | ||
| 515 | + /// that is not on this board. | ||
| 516 | + pub async fn set_tag_colour( | ||
| 517 | + &self, | ||
| 518 | + board_id: &str, | ||
| 519 | + tag_id: &str, | ||
| 520 | + colour: Option<&str>, | ||
| 521 | + ) -> Result<()> { | ||
| 522 | + let colour = match colour.map(str::trim).filter(|c| !c.is_empty()) { | ||
| 523 | + Some(c) if valid_colour(c) => Some(c.to_owned()), | ||
| 524 | + Some(_) => return Err(Error::Invalid("that colour is not in the palette".into())), | ||
| 525 | + None => None, | ||
| 526 | + }; | ||
| 527 | + let conn = self.inner.conn.lock().await; | ||
| 528 | + let changed = conn | ||
| 529 | + .execute( | ||
| 530 | + "UPDATE tags SET color = ?3 WHERE id = ?1 AND board_id = ?2", | ||
| 531 | + (tag_id.to_owned(), board_id.to_owned(), colour), | ||
| 532 | + ) | ||
| 533 | + .await | ||
| 534 | + .map_err(db_err)?; | ||
| 535 | + if changed == 0 { | ||
| 536 | + return Err(Error::NotFound); | ||
| 537 | + } | ||
| 538 | + Ok(()) | ||
| 539 | + } | ||
| 540 | + | ||
| 541 | + /// Live task counts per project of `board_id`, as `(tag id, count)`. Projects with no task are absent. | ||
| 542 | + pub async fn tag_usage(&self, board_id: &str) -> Result<Vec<(String, i64)>> { | ||
| 543 | + let conn = self.read_conn().await; | ||
| 544 | + fetch_all( | ||
| 545 | + &conn, | ||
| 546 | + "SELECT tag_id, COUNT(*) FROM tasks WHERE board_id = ?1 AND deleted_at IS NULL GROUP BY tag_id", | ||
| 547 | + (board_id.to_owned(),), | ||
| 548 | + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), | ||
| 549 | + ) | ||
| 550 | + .await | ||
| 551 | + } | ||
| 552 | + | ||
| 553 | + /// Live task counts per live column of `board_id`, as `(column id, count)`. | ||
| 554 | + pub async fn column_usage(&self, board_id: &str) -> Result<Vec<(String, i64)>> { | ||
| 555 | + let conn = self.read_conn().await; | ||
| 556 | + fetch_all( | ||
| 557 | + &conn, | ||
| 558 | + "SELECT column_id, COUNT(*) FROM tasks WHERE board_id = ?1 AND deleted_at IS NULL GROUP BY column_id", | ||
| 559 | + (board_id.to_owned(),), | ||
| 560 | + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), | ||
| 561 | + ) | ||
| 562 | + .await | ||
| 563 | + } | ||
| 564 | + | ||
| 505 | /// Renames a tag. The new name must be unique per board, ignoring case. | 565 | /// Renames a tag. The new name must be unique per board, ignoring case. |
| 506 | pub async fn rename_tag(&self, board_id: &str, tag_id: &str, name: &str) -> Result<()> { | 566 | pub async fn rename_tag(&self, board_id: &str, tag_id: &str, name: &str) -> Result<()> { |
| 507 | let name = clean_tag_name(name)?; | 567 | let name = clean_tag_name(name)?; |
crates/iz-core/src/store/export.rsadded+365 -0
| @@ -0,0 +1,365 @@ | |||
| 1 | +//! Read-only access to a database file, for the operator commands (`iz export`, `iz restore`, `iz fsck`). | ||
| 2 | +//! | ||
| 3 | +//! What it is: a connection that never migrates, never writes and reads a board as JSON rows with the | ||
| 4 | +//! column names the export file uses. What it is not: the server's store. Opening through [`Store::open`] | ||
| 5 | +//! would apply migrations, so a check of a damaged or foreign file would change it. The invariant: nothing | ||
| 6 | +//! in this module writes to the database, and the migration history is checked by [`migrations_problem`] | ||
| 7 | +//! against the versions this build knows. | ||
| 8 | + | ||
| 9 | +use std::path::Path; | ||
| 10 | + | ||
| 11 | +use turso::{Builder, Connection, Database, IntoParams, Value}; | ||
| 12 | + | ||
| 13 | +use super::migrate::MIGRATIONS; | ||
| 14 | +use super::{col_text, db_err, fetch_all}; | ||
| 15 | +use crate::error::{Error, Result}; | ||
| 16 | + | ||
| 17 | +/// A database file opened read-only. Keep it alive while its rows are used. | ||
| 18 | +pub struct ReadOnly { | ||
| 19 | + /// Keeps the database handle alive as long as the connection exists. | ||
| 20 | + _db: Database, | ||
| 21 | + conn: Connection, | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +/// One attachment row as stored. `location` is `local` (bytes on this disk), `in` (bytes in another | ||
| 25 | +/// service) or `moving`. | ||
| 26 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 27 | +pub struct AttachmentRow { | ||
| 28 | + /// Attachment id (ULID). | ||
| 29 | + pub id: String, | ||
| 30 | + /// The task it belongs to. | ||
| 31 | + pub task_id: String, | ||
| 32 | + /// File name as uploaded. | ||
| 33 | + pub name: String, | ||
| 34 | + /// Sniffed MIME type. | ||
| 35 | + pub mime: String, | ||
| 36 | + /// Length in bytes as recorded. | ||
| 37 | + pub size: u64, | ||
| 38 | + /// Lowercase hex SHA-256 as recorded. | ||
| 39 | + pub sha256: String, | ||
| 40 | + /// Uploader's member id. | ||
| 41 | + pub uploaded_by: String, | ||
| 42 | + /// UTC stamp of the upload. | ||
| 43 | + pub created_at: String, | ||
| 44 | + /// Where the bytes are: `local`, `in` or `moving`. | ||
| 45 | + pub location: String, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// A board as JSON rows, one list per table. Each row is an object keyed by the column names. | ||
| 49 | +#[derive(Debug, Clone, PartialEq)] | ||
| 50 | +pub struct BoardDump { | ||
| 51 | + /// The board row (a single object). | ||
| 52 | + pub board: serde_json::Value, | ||
| 53 | + /// Columns, retired ones included, in position order. | ||
| 54 | + pub columns: Vec<serde_json::Value>, | ||
| 55 | + /// Tags (projects), in position order. | ||
| 56 | + pub tags: Vec<serde_json::Value>, | ||
| 57 | + /// Tasks, deleted ones included (with `deleted_at`), oldest first. | ||
| 58 | + pub tasks: Vec<serde_json::Value>, | ||
| 59 | + /// Assignments of tasks. | ||
| 60 | + pub assignees: Vec<serde_json::Value>, | ||
| 61 | + /// Dependency links, cleared ones included (with `cleared_at`). | ||
| 62 | + pub dependencies: Vec<serde_json::Value>, | ||
| 63 | + /// Comments, deleted ones included (with `deleted_at`). | ||
| 64 | + pub comments: Vec<serde_json::Value>, | ||
| 65 | + /// Activity of the board's tasks, oldest first. | ||
| 66 | + pub activity: Vec<serde_json::Value>, | ||
| 67 | + /// Members named by any row above: `sub`, `name` and `email` only. | ||
| 68 | + pub members: Vec<serde_json::Value>, | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// The first problem with a migration history, as the user reads it, or `None` when the versions are | ||
| 72 | +/// exactly `1..=N` and `N` is no newer than this build. An empty history is a problem too. | ||
| 73 | +pub fn migrations_problem(versions: &[i64]) -> Option<String> { | ||
| 74 | + if versions.is_empty() { | ||
| 75 | + return Some("the database has no migration history".into()); | ||
| 76 | + } | ||
| 77 | + for (index, version) in versions.iter().enumerate() { | ||
| 78 | + let expected = i64::try_from(index + 1).unwrap_or(i64::MAX); | ||
| 79 | + if *version != expected { | ||
| 80 | + return Some(format!( | ||
| 81 | + "migration history is not contiguous: expected version {expected}, found {version}" | ||
| 82 | + )); | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + let known = MIGRATIONS | ||
| 86 | + .last() | ||
| 87 | + .map_or(0, |(version, _)| i64::from(*version)); | ||
| 88 | + let newest = versions.last().copied().unwrap_or(0); | ||
| 89 | + if newest > known { | ||
| 90 | + return Some(format!( | ||
| 91 | + "the database is at migration {newest}, this build knows up to {known}" | ||
| 92 | + )); | ||
| 93 | + } | ||
| 94 | + None | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// Column names of an attachment row, in the order `attachment_rows` selects them. | ||
| 98 | +const ATTACHMENT_SQL: &str = "SELECT a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, \ | ||
| 99 | + a.created_at, a.location FROM attachments a"; | ||
| 100 | + | ||
| 101 | +fn map_attachment(row: &turso::Row) -> Result<AttachmentRow> { | ||
| 102 | + let size = match row.get_value(4).map_err(db_err)? { | ||
| 103 | + Value::Integer(n) => { | ||
| 104 | + u64::try_from(n).map_err(|_| Error::Database("attachment size is negative".into()))? | ||
| 105 | + } | ||
| 106 | + _ => return Err(Error::Database("attachment size is not an integer".into())), | ||
| 107 | + }; | ||
| 108 | + Ok(AttachmentRow { | ||
| 109 | + id: col_text(row, 0)?, | ||
| 110 | + task_id: col_text(row, 1)?, | ||
| 111 | + name: col_text(row, 2)?, | ||
| 112 | + mime: col_text(row, 3)?, | ||
| 113 | + size, | ||
| 114 | + sha256: col_text(row, 5)?, | ||
| 115 | + uploaded_by: col_text(row, 6)?, | ||
| 116 | + created_at: col_text(row, 7)?, | ||
| 117 | + location: col_text(row, 8)?, | ||
| 118 | + }) | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// Converts one SQL value to JSON. Blobs are refused: no column of this schema holds one. | ||
| 122 | +fn to_json(value: Value) -> Result<serde_json::Value> { | ||
| 123 | + Ok(match value { | ||
| 124 | + Value::Null => serde_json::Value::Null, | ||
| 125 | + Value::Integer(n) => serde_json::Value::from(n), | ||
| 126 | + Value::Real(f) => serde_json::Number::from_f64(f) | ||
| 127 | + .map(serde_json::Value::Number) | ||
| 128 | + .ok_or_else(|| Error::Database("a real column holds NaN or infinity".into()))?, | ||
| 129 | + Value::Text(s) => serde_json::Value::String(s), | ||
| 130 | + Value::Blob(_) => return Err(Error::Database("unexpected blob in a row".into())), | ||
| 131 | + }) | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// Runs a query and returns each row as an object keyed by `cols`, which name the selected columns in | ||
| 135 | +/// order. | ||
| 136 | +async fn json_rows( | ||
| 137 | + conn: &Connection, | ||
| 138 | + sql: &str, | ||
| 139 | + params: impl IntoParams, | ||
| 140 | + cols: &[&str], | ||
| 141 | +) -> Result<Vec<serde_json::Value>> { | ||
| 142 | + fetch_all(conn, sql, params, |row| { | ||
| 143 | + let mut object = serde_json::Map::new(); | ||
| 144 | + for (i, name) in cols.iter().enumerate() { | ||
| 145 | + let value = row.get_value(i).map_err(db_err)?; | ||
| 146 | + object.insert((*name).to_owned(), to_json(value)?); | ||
| 147 | + } | ||
| 148 | + Ok(serde_json::Value::Object(object)) | ||
| 149 | + }) | ||
| 150 | + .await | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +impl ReadOnly { | ||
| 154 | + /// Opens the database file read-only. A missing file is an error: nothing is created. | ||
| 155 | + pub async fn open(path: &Path) -> Result<ReadOnly> { | ||
| 156 | + let text = path.to_str().ok_or_else(|| { | ||
| 157 | + Error::Config(format!("database path is not UTF-8: {}", path.display())) | ||
| 158 | + })?; | ||
| 159 | + let db = Builder::new_local(text) | ||
| 160 | + .read_only(true) | ||
| 161 | + .build() | ||
| 162 | + .await | ||
| 163 | + .map_err(db_err)?; | ||
| 164 | + let conn = db.connect().map_err(db_err)?; | ||
| 165 | + Ok(ReadOnly { _db: db, conn }) | ||
| 166 | + } | ||
| 167 | + | ||
| 168 | + /// The rows `PRAGMA integrity_check` returns. A healthy database returns exactly `ok`. | ||
| 169 | + pub async fn integrity_check(&self) -> Result<Vec<String>> { | ||
| 170 | + fetch_all(&self.conn, "PRAGMA integrity_check", (), |row| { | ||
| 171 | + col_text(row, 0) | ||
| 172 | + }) | ||
| 173 | + .await | ||
| 174 | + } | ||
| 175 | + | ||
| 176 | + /// The migration versions recorded, ascending. | ||
| 177 | + pub async fn migration_versions(&self) -> Result<Vec<i64>> { | ||
| 178 | + fetch_all( | ||
| 179 | + &self.conn, | ||
| 180 | + "SELECT version FROM schema_migrations ORDER BY version", | ||
| 181 | + (), | ||
| 182 | + |row| match row.get_value(0).map_err(db_err)? { | ||
| 183 | + Value::Integer(n) => Ok(n), | ||
| 184 | + _ => Err(Error::Database( | ||
| 185 | + "schema_migrations.version is not an integer".into(), | ||
| 186 | + )), | ||
| 187 | + }, | ||
| 188 | + ) | ||
| 189 | + .await | ||
| 190 | + } | ||
| 191 | + | ||
| 192 | + /// Every attachment row of the database, oldest first. | ||
| 193 | + pub async fn attachment_rows(&self) -> Result<Vec<AttachmentRow>> { | ||
| 194 | + fetch_all( | ||
| 195 | + &self.conn, | ||
| 196 | + &format!("{ATTACHMENT_SQL} ORDER BY a.id"), | ||
| 197 | + (), | ||
| 198 | + map_attachment, | ||
| 199 | + ) | ||
| 200 | + .await | ||
| 201 | + } | ||
| 202 | + | ||
| 203 | + /// The attachment rows of the tasks of `board_id`, oldest first. | ||
| 204 | + pub async fn board_attachment_rows(&self, board_id: &str) -> Result<Vec<AttachmentRow>> { | ||
| 205 | + fetch_all( | ||
| 206 | + &self.conn, | ||
| 207 | + &format!( | ||
| 208 | + "{ATTACHMENT_SQL} JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 \ | ||
| 209 | + ORDER BY a.created_at, a.id" | ||
| 210 | + ), | ||
| 211 | + (board_id.to_owned(),), | ||
| 212 | + map_attachment, | ||
| 213 | + ) | ||
| 214 | + .await | ||
| 215 | + } | ||
| 216 | + | ||
| 217 | + /// The ids of the boards in the database. One board per instance is the rule, but the export names | ||
| 218 | + /// the board it reads, so it checks. | ||
| 219 | + pub async fn board_ids(&self) -> Result<Vec<String>> { | ||
| 220 | + fetch_all(&self.conn, "SELECT id FROM boards ORDER BY id", (), |row| { | ||
| 221 | + col_text(row, 0) | ||
| 222 | + }) | ||
| 223 | + .await | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + /// Reads a board, its tasks and everything hanging off them, as JSON rows. Every query names its | ||
| 227 | + /// columns, so the export file does not depend on the column order of the schema. | ||
| 228 | + pub async fn export_board(&self, board_id: &str) -> Result<BoardDump> { | ||
| 229 | + let conn = &self.conn; | ||
| 230 | + let board_param = || (board_id.to_owned(),); | ||
| 231 | + let board = json_rows( | ||
| 232 | + conn, | ||
| 233 | + "SELECT id, name, key_prefix, next_task_number, created_at FROM boards WHERE id = ?1", | ||
| 234 | + board_param(), | ||
| 235 | + &["id", "name", "key_prefix", "next_task_number", "created_at"], | ||
| 236 | + ) | ||
| 237 | + .await? | ||
| 238 | + .into_iter() | ||
| 239 | + .next() | ||
| 240 | + .ok_or(Error::NotFound)?; | ||
| 241 | + let columns = json_rows( | ||
| 242 | + conn, | ||
| 243 | + "SELECT id, name, position, is_done, created_at, deleted_at FROM columns \ | ||
| 244 | + WHERE board_id = ?1 ORDER BY position, id", | ||
| 245 | + board_param(), | ||
| 246 | + &[ | ||
| 247 | + "id", | ||
| 248 | + "name", | ||
| 249 | + "position", | ||
| 250 | + "is_done", | ||
| 251 | + "created_at", | ||
| 252 | + "deleted_at", | ||
| 253 | + ], | ||
| 254 | + ) | ||
| 255 | + .await?; | ||
| 256 | + let tags = json_rows( | ||
| 257 | + conn, | ||
| 258 | + "SELECT id, name, position, is_default, color, created_at FROM tags \ | ||
| 259 | + WHERE board_id = ?1 ORDER BY position, id", | ||
| 260 | + board_param(), | ||
| 261 | + &[ | ||
| 262 | + "id", | ||
| 263 | + "name", | ||
| 264 | + "position", | ||
| 265 | + "is_default", | ||
| 266 | + "color", | ||
| 267 | + "created_at", | ||
| 268 | + ], | ||
| 269 | + ) | ||
| 270 | + .await?; | ||
| 271 | + let tasks = json_rows( | ||
| 272 | + conn, | ||
| 273 | + "SELECT id, key, parent_id, title, description, column_id, tag_id, deadline, meeting_at, \ | ||
| 274 | + position, created_by, created_at, updated_at, done_at, deleted_at FROM tasks \ | ||
| 275 | + WHERE board_id = ?1 ORDER BY created_at, id", | ||
| 276 | + board_param(), | ||
| 277 | + &[ | ||
| 278 | + "id", | ||
| 279 | + "key", | ||
| 280 | + "parent_id", | ||
| 281 | + "title", | ||
| 282 | + "description", | ||
| 283 | + "column_id", | ||
| 284 | + "tag_id", | ||
| 285 | + "deadline", | ||
| 286 | + "meeting_at", | ||
| 287 | + "position", | ||
| 288 | + "created_by", | ||
| 289 | + "created_at", | ||
| 290 | + "updated_at", | ||
| 291 | + "done_at", | ||
| 292 | + "deleted_at", | ||
| 293 | + ], | ||
| 294 | + ) | ||
| 295 | + .await?; | ||
| 296 | + let assignees = json_rows( | ||
| 297 | + conn, | ||
| 298 | + "SELECT a.task_id, a.sub, a.assigned_at FROM task_assignees a \ | ||
| 299 | + JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 ORDER BY a.task_id, a.sub", | ||
| 300 | + board_param(), | ||
| 301 | + &["task_id", "sub", "assigned_at"], | ||
| 302 | + ) | ||
| 303 | + .await?; | ||
| 304 | + let dependencies = json_rows( | ||
| 305 | + conn, | ||
| 306 | + "SELECT d.blocked_id, d.blocking_id, d.created_at, d.cleared_at FROM dependencies d \ | ||
| 307 | + JOIN tasks t ON t.id = d.blocked_id WHERE t.board_id = ?1 ORDER BY d.created_at", | ||
| 308 | + board_param(), | ||
| 309 | + &["blocked_id", "blocking_id", "created_at", "cleared_at"], | ||
| 310 | + ) | ||
| 311 | + .await?; | ||
| 312 | + let comments = json_rows( | ||
| 313 | + conn, | ||
| 314 | + "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at \ | ||
| 315 | + FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1 \ | ||
| 316 | + ORDER BY c.created_at, c.id", | ||
| 317 | + board_param(), | ||
| 318 | + &[ | ||
| 319 | + "id", | ||
| 320 | + "task_id", | ||
| 321 | + "author", | ||
| 322 | + "body", | ||
| 323 | + "created_at", | ||
| 324 | + "edited_at", | ||
| 325 | + "deleted_at", | ||
| 326 | + ], | ||
| 327 | + ) | ||
| 328 | + .await?; | ||
| 329 | + let activity = json_rows( | ||
| 330 | + conn, | ||
| 331 | + "SELECT x.id, x.task_id, x.actor, x.subject, x.kind, x.detail, x.at FROM activity x \ | ||
| 332 | + JOIN tasks t ON t.id = x.task_id WHERE t.board_id = ?1 ORDER BY x.at, x.id", | ||
| 333 | + board_param(), | ||
| 334 | + &["id", "task_id", "actor", "subject", "kind", "detail", "at"], | ||
| 335 | + ) | ||
| 336 | + .await?; | ||
| 337 | + let members = json_rows( | ||
| 338 | + conn, | ||
| 339 | + "SELECT sub, name, email FROM members WHERE sub IN (\ | ||
| 340 | + SELECT created_by FROM tasks WHERE board_id = ?1 \ | ||
| 341 | + UNION SELECT a.sub FROM task_assignees a JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 \ | ||
| 342 | + UNION SELECT c.author FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1 \ | ||
| 343 | + UNION SELECT x.actor FROM activity x JOIN tasks t ON t.id = x.task_id \ | ||
| 344 | + WHERE t.board_id = ?1 AND x.actor IS NOT NULL \ | ||
| 345 | + UNION SELECT x.subject FROM activity x JOIN tasks t ON t.id = x.task_id \ | ||
| 346 | + WHERE t.board_id = ?1 AND x.subject IS NOT NULL \ | ||
| 347 | + UNION SELECT at.uploaded_by FROM attachments at JOIN tasks t ON t.id = at.task_id \ | ||
| 348 | + WHERE t.board_id = ?1) ORDER BY sub", | ||
| 349 | + board_param(), | ||
| 350 | + &["sub", "name", "email"], | ||
| 351 | + ) | ||
| 352 | + .await?; | ||
| 353 | + Ok(BoardDump { | ||
| 354 | + board, | ||
| 355 | + columns, | ||
| 356 | + tags, | ||
| 357 | + tasks, | ||
| 358 | + assignees, | ||
| 359 | + dependencies, | ||
| 360 | + comments, | ||
| 361 | + activity, | ||
| 362 | + members, | ||
| 363 | + }) | ||
| 364 | + } | ||
| 365 | +} | ||
crates/iz-core/src/store/mod.rsmodified+17 -0
| @@ -9,18 +9,22 @@ | |||
| 9 | 9 | ||
| 10 | pub mod activity; | 10 | pub mod activity; |
| 11 | pub mod attachments; | 11 | pub mod attachments; |
| 12 | +pub mod audit; | ||
| 12 | pub mod board; | 13 | pub mod board; |
| 13 | pub mod comments; | 14 | pub mod comments; |
| 14 | pub mod events; | 15 | pub mod events; |
| 16 | +pub mod export; | ||
| 15 | pub mod members; | 17 | pub mod members; |
| 16 | pub mod migrate; | 18 | pub mod migrate; |
| 17 | pub mod outbox; | 19 | pub mod outbox; |
| 20 | +pub mod people; | ||
| 18 | pub mod reminders; | 21 | pub mod reminders; |
| 19 | pub mod rules; | 22 | pub mod rules; |
| 20 | pub mod rules_engine; | 23 | pub mod rules_engine; |
| 21 | pub mod sender; | 24 | pub mod sender; |
| 22 | pub mod sessions; | 25 | pub mod sessions; |
| 23 | pub mod snapshot; | 26 | pub mod snapshot; |
| 27 | +pub mod sweep; | ||
| 24 | pub mod tasks; | 28 | pub mod tasks; |
| 25 | 29 | ||
| 26 | use std::path::Path; | 30 | use std::path::Path; |
| @@ -128,6 +132,19 @@ impl Store { | |||
| 128 | Ok(()) | 132 | Ok(()) |
| 129 | } | 133 | } |
| 130 | 134 | ||
| 135 | + /// The highest applied migration version, for the server page. | ||
| 136 | + pub async fn schema_version(&self) -> Result<i64> { | ||
| 137 | + let conn = self.read_conn().await; | ||
| 138 | + let value = fetch_opt( | ||
| 139 | + &conn, | ||
| 140 | + "SELECT MAX(version) FROM schema_migrations", | ||
| 141 | + (), | ||
| 142 | + |row| col_int(row, 0), | ||
| 143 | + ) | ||
| 144 | + .await?; | ||
| 145 | + Ok(value.unwrap_or(0)) | ||
| 146 | + } | ||
| 147 | + | ||
| 131 | /// Runs `SELECT 1` on a pooled reader and fails when the database does not answer. The health | 148 | /// Runs `SELECT 1` on a pooled reader and fails when the database does not answer. The health |
| 132 | /// route calls it with a deadline, so a stuck lock shows up as a failed probe. | 149 | /// route calls it with a deadline, so a stuck lock shows up as a failed probe. |
| 133 | pub async fn ping(&self) -> Result<()> { | 150 | pub async fn ping(&self) -> Result<()> { |
crates/iz-core/src/store/outbox.rsmodified+3 -2
| @@ -1,7 +1,7 @@ | |||
| 1 | //! The outbox: every mail iz sends is a row here first, written in the transaction that decided it. The | 1 | //! The outbox: every mail iz sends is a row here first, written in the transaction that decided it. The |
| 2 | //! worker in `iz-web` claims due rows under a lease, sends them and records the result. Nothing else sends. | 2 | //! worker in `iz-web` claims due rows under a lease, sends them and records the result. Nothing else sends. |
| 3 | //! | 3 | //! |
| 4 | -//! Retries: a failed attempt waits `BACKOFF_MINUTES` (1, 5, 15, then 60) before the next one; the fifth | 4 | +//! Retries: a failed attempt waits `BACKOFF_MINUTES` (5, 10, 20, then 40) before the next one; the fifth |
| 5 | //! failure, or a permanent refusal by the server, abandons the row. A row that cannot be sent for lack of a | 5 | //! failure, or a permanent refusal by the server, abandons the row. A row that cannot be sent for lack of a |
| 6 | //! sender is held for `HOLD_MINUTES` and spends no attempt. A claim is a lease of `LEASE_MINUTES`: a worker | 6 | //! sender is held for `HOLD_MINUTES` and spends no attempt. A claim is a lease of `LEASE_MINUTES`: a worker |
| 7 | //! that dies lets the row go again after that. Rows of a member who is no longer eligible are abandoned at | 7 | //! 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; | |||
| 22 | /// Failed attempts before a row is abandoned. | 22 | /// Failed attempts before a row is abandoned. |
| 23 | pub const MAX_ATTEMPTS: i64 = 5; | 23 | pub const MAX_ATTEMPTS: i64 = 5; |
| 24 | /// The wait after the first, second, third and fourth failure, in minutes. The fifth failure abandons. | 24 | /// The wait after the first, second, third and fourth failure, in minutes. The fifth failure abandons. |
| 25 | -pub const BACKOFF_MINUTES: [i64; 4] = [1, 5, 15, 60]; | 25 | +/// Reason: architecture section 5 fixes these values. |
| 26 | +pub const BACKOFF_MINUTES: [i64; 4] = [5, 10, 20, 40]; | ||
| 26 | /// The wait before trying again when no sender is configured. It spends no attempt. | 27 | /// The wait before trying again when no sender is configured. It spends no attempt. |
| 27 | pub const HOLD_MINUTES: i64 = 1; | 28 | pub const HOLD_MINUTES: i64 = 1; |
| 28 | /// How long a claim holds a row before another worker may take it, in minutes. | 29 | /// How long a claim holds a row before another worker may take it, in minutes. |
crates/iz-core/src/store/people.rsadded+91 -0
| @@ -0,0 +1,91 @@ | |||
| 1 | +//! The person card of `/people/{sub}`: how many open and finished tasks a member of this board is | ||
| 2 | +//! assigned to, how many tasks they created, how many comments and files they posted. Every count is | ||
| 3 | +//! limited to live tasks of one board, so a member of another board or a deleted card adds nothing. | ||
| 4 | + | ||
| 5 | +use turso::Connection; | ||
| 6 | + | ||
| 7 | +use super::{col_int, fetch_opt}; | ||
| 8 | +use crate::error::Result; | ||
| 9 | +use crate::store::Store; | ||
| 10 | + | ||
| 11 | +/// The counts shown on a person card. | ||
| 12 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | ||
| 13 | +pub struct PersonCounts { | ||
| 14 | + /// Assigned live tasks that are not done. | ||
| 15 | + pub open: i64, | ||
| 16 | + /// Assigned live tasks that are done. | ||
| 17 | + pub done: i64, | ||
| 18 | + /// Live tasks the member created. | ||
| 19 | + pub created: i64, | ||
| 20 | + /// Live comments the member wrote. | ||
| 21 | + pub comments: i64, | ||
| 22 | + /// Files the member attached to live tasks. | ||
| 23 | + pub files: i64, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// Counts for one member on one board. One statement per figure, all reads. | ||
| 27 | +pub async fn counts(conn: &Connection, board_id: &str, sub: &str) -> Result<PersonCounts> { | ||
| 28 | + let open = count( | ||
| 29 | + conn, | ||
| 30 | + "SELECT COUNT(*) FROM task_assignees a JOIN tasks t ON t.id = a.task_id \ | ||
| 31 | + WHERE a.sub = ?2 AND t.board_id = ?1 AND t.deleted_at IS NULL AND t.done_at IS NULL", | ||
| 32 | + board_id, | ||
| 33 | + sub, | ||
| 34 | + ) | ||
| 35 | + .await?; | ||
| 36 | + let done = count( | ||
| 37 | + conn, | ||
| 38 | + "SELECT COUNT(*) FROM task_assignees a JOIN tasks t ON t.id = a.task_id \ | ||
| 39 | + WHERE a.sub = ?2 AND t.board_id = ?1 AND t.deleted_at IS NULL AND t.done_at IS NOT NULL", | ||
| 40 | + board_id, | ||
| 41 | + sub, | ||
| 42 | + ) | ||
| 43 | + .await?; | ||
| 44 | + let created = count( | ||
| 45 | + conn, | ||
| 46 | + "SELECT COUNT(*) FROM tasks WHERE board_id = ?1 AND created_by = ?2 AND deleted_at IS NULL", | ||
| 47 | + board_id, | ||
| 48 | + sub, | ||
| 49 | + ) | ||
| 50 | + .await?; | ||
| 51 | + let comments = count( | ||
| 52 | + conn, | ||
| 53 | + "SELECT COUNT(*) FROM comments c JOIN tasks t ON t.id = c.task_id \ | ||
| 54 | + WHERE t.board_id = ?1 AND c.author = ?2 AND c.deleted_at IS NULL AND t.deleted_at IS NULL", | ||
| 55 | + board_id, | ||
| 56 | + sub, | ||
| 57 | + ) | ||
| 58 | + .await?; | ||
| 59 | + let files = count( | ||
| 60 | + conn, | ||
| 61 | + "SELECT COUNT(*) FROM attachments f JOIN tasks t ON t.id = f.task_id \ | ||
| 62 | + WHERE t.board_id = ?1 AND f.uploaded_by = ?2 AND t.deleted_at IS NULL", | ||
| 63 | + board_id, | ||
| 64 | + sub, | ||
| 65 | + ) | ||
| 66 | + .await?; | ||
| 67 | + Ok(PersonCounts { | ||
| 68 | + open, | ||
| 69 | + done, | ||
| 70 | + created, | ||
| 71 | + comments, | ||
| 72 | + files, | ||
| 73 | + }) | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// One `COUNT(*)` with the board and the member as its two parameters. | ||
| 77 | +async fn count(conn: &Connection, sql: &str, board_id: &str, sub: &str) -> Result<i64> { | ||
| 78 | + let value = fetch_opt(conn, sql, (board_id.to_owned(), sub.to_owned()), |row| { | ||
| 79 | + col_int(row, 0) | ||
| 80 | + }) | ||
| 81 | + .await?; | ||
| 82 | + Ok(value.unwrap_or(0)) | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +impl Store { | ||
| 86 | + /// The counts of one member on `board_id`, read on a pooled reader. | ||
| 87 | + pub async fn person_counts(&self, board_id: &str, sub: &str) -> Result<PersonCounts> { | ||
| 88 | + let conn = self.read_conn().await; | ||
| 89 | + counts(&conn, board_id, sub).await | ||
| 90 | + } | ||
| 91 | +} | ||
crates/iz-core/src/store/sweep.rsadded+120 -0
| @@ -0,0 +1,120 @@ | |||
| 1 | +//! Retention and housekeeping deletes that the sweeper worker runs on a timer: old activity, old rows of | ||
| 2 | +//! the mail ledger, and finished mail outbox rows. Every delete is batched, so one call never holds the | ||
| 3 | +//! writer for long, and the caller loops until a batch comes back short. | ||
| 4 | +//! | ||
| 5 | +//! This module only deletes rows that nothing needs any more. Pending mail, pending attachment deletions | ||
| 6 | +//! and live sessions are never touched here; their own modules own those rules. | ||
| 7 | + | ||
| 8 | +use jiff::Timestamp; | ||
| 9 | + | ||
| 10 | +use super::db_err; | ||
| 11 | +use crate::clock::stamp_of; | ||
| 12 | +use crate::error::Result; | ||
| 13 | +use crate::store::Store; | ||
| 14 | + | ||
| 15 | +/// Days kept for activity, mail decisions and finished mail. Reason: a year covers a full review cycle of | ||
| 16 | +/// the family board; older rows are noise for the admin pages. | ||
| 17 | +pub const RETENTION_DAYS: i64 = 365; | ||
| 18 | + | ||
| 19 | +impl Store { | ||
| 20 | + /// Deletes up to `batch` activity rows recorded before `cutoff`. Returns how many were deleted. | ||
| 21 | + /// Activity is ordered by its stored stamp, which is fixed width, so text comparison is time order. | ||
| 22 | + pub async fn prune_activity(&self, cutoff: Timestamp, batch: i64) -> Result<u64> { | ||
| 23 | + let cutoff = stamp_of(cutoff)?; | ||
| 24 | + let conn = self.inner.conn.lock().await; | ||
| 25 | + conn.execute( | ||
| 26 | + "DELETE FROM activity WHERE id IN (SELECT id FROM activity WHERE at < ?1 LIMIT ?2)", | ||
| 27 | + (cutoff, batch), | ||
| 28 | + ) | ||
| 29 | + .await | ||
| 30 | + .map_err(db_err) | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + /// Deletes up to `batch` mail decisions created before `cutoff`. Returns how many were deleted. | ||
| 34 | + pub async fn prune_mail_decisions(&self, cutoff: Timestamp, batch: i64) -> Result<u64> { | ||
| 35 | + let cutoff = stamp_of(cutoff)?; | ||
| 36 | + let conn = self.inner.conn.lock().await; | ||
| 37 | + conn.execute( | ||
| 38 | + "DELETE FROM mail_decisions WHERE id IN \ | ||
| 39 | + (SELECT id FROM mail_decisions WHERE created_at < ?1 LIMIT ?2)", | ||
| 40 | + (cutoff, batch), | ||
| 41 | + ) | ||
| 42 | + .await | ||
| 43 | + .map_err(db_err) | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /// Deletes up to `batch` mail outbox rows that are finished (`sent` or `abandoned`) and were created | ||
| 47 | + /// before `cutoff`. Pending and failed rows are never deleted: they still owe a send. | ||
| 48 | + pub async fn prune_mail_outbox(&self, cutoff: Timestamp, batch: i64) -> Result<u64> { | ||
| 49 | + let cutoff = stamp_of(cutoff)?; | ||
| 50 | + let conn = self.inner.conn.lock().await; | ||
| 51 | + conn.execute( | ||
| 52 | + "DELETE FROM mail_outbox WHERE id IN (SELECT id FROM mail_outbox \ | ||
| 53 | + WHERE state IN ('sent', 'abandoned') AND created_at < ?1 LIMIT ?2)", | ||
| 54 | + (cutoff, batch), | ||
| 55 | + ) | ||
| 56 | + .await | ||
| 57 | + .map_err(db_err) | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + /// The attachments whose bytes are on this machine (`location = 'local'`), as ids. The backup worker | ||
| 61 | + /// copies exactly these files. | ||
| 62 | + pub async fn local_attachment_ids(&self) -> Result<Vec<String>> { | ||
| 63 | + let conn = self.read_conn().await; | ||
| 64 | + super::fetch_all( | ||
| 65 | + &conn, | ||
| 66 | + "SELECT id FROM attachments WHERE location = 'local' ORDER BY id", | ||
| 67 | + (), | ||
| 68 | + |row| super::col_text(row, 0), | ||
| 69 | + ) | ||
| 70 | + .await | ||
| 71 | + } | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +#[cfg(test)] | ||
| 75 | +mod tests { | ||
| 76 | + use super::*; | ||
| 77 | + use crate::store::fetch_opt; | ||
| 78 | + | ||
| 79 | + async fn count(store: &Store, sql: &str) -> i64 { | ||
| 80 | + let conn = store.read_conn().await; | ||
| 81 | + fetch_opt(&conn, sql, (), |row| super::super::col_int(row, 0)) | ||
| 82 | + .await | ||
| 83 | + .unwrap() | ||
| 84 | + .unwrap() | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + #[tokio::test] | ||
| 88 | + async fn pruning_deletes_only_old_finished_rows() { | ||
| 89 | + let dir = tempfile::tempdir().unwrap(); | ||
| 90 | + let store = Store::open(&dir.path().join("iz.db")).await.unwrap(); | ||
| 91 | + { | ||
| 92 | + let conn = store.inner.conn.lock().await; | ||
| 93 | + conn.execute_batch( | ||
| 94 | + "INSERT INTO members (sub, email, name, first_seen_at) VALUES ('u1', 'a@example.com', 'Ada', 'then'); | ||
| 95 | + INSERT INTO activity (id, kind, detail, at) VALUES ('old', 'account_changed', '{}', '2020-01-01T00:00:00.000000000Z'); | ||
| 96 | + INSERT INTO activity (id, kind, detail, at) VALUES ('new', 'account_changed', '{}', '2030-01-01T00:00:00.000000000Z'); | ||
| 97 | + INSERT INTO mail_outbox (id, event_id, recipient, kind, subject, body, state, next_attempt_at, created_at, sent_at) | ||
| 98 | + VALUES ('sent', 'e1', 'u1', 'test', 's', 'b', 'sent', 'then', '2020-01-01T00:00:00.000000000Z', '2020-01-01T00:00:00.000000000Z'); | ||
| 99 | + INSERT INTO mail_outbox (id, event_id, recipient, kind, subject, body, state, next_attempt_at, created_at) | ||
| 100 | + VALUES ('pending', 'e2', 'u1', 'test', 's', 'b', 'pending', 'then', '2020-01-01T00:00:00.000000000Z');", | ||
| 101 | + ) | ||
| 102 | + .await | ||
| 103 | + .unwrap(); | ||
| 104 | + } | ||
| 105 | + let cutoff = Timestamp::now(); | ||
| 106 | + assert_eq!(store.prune_activity(cutoff, 10).await.unwrap(), 1); | ||
| 107 | + assert_eq!(store.prune_mail_outbox(cutoff, 10).await.unwrap(), 1); | ||
| 108 | + assert_eq!(store.prune_mail_decisions(cutoff, 10).await.unwrap(), 0); | ||
| 109 | + assert_eq!(count(&store, "SELECT COUNT(*) FROM activity").await, 1); | ||
| 110 | + assert_eq!( | ||
| 111 | + count( | ||
| 112 | + &store, | ||
| 113 | + "SELECT COUNT(*) FROM mail_outbox WHERE state = 'pending'" | ||
| 114 | + ) | ||
| 115 | + .await, | ||
| 116 | + 1, | ||
| 117 | + "a pending row must survive pruning" | ||
| 118 | + ); | ||
| 119 | + } | ||
| 120 | +} | ||
crates/iz-web/Cargo.tomlmodified+1 -0
| @@ -12,6 +12,7 @@ path = "src/main.rs" | |||
| 12 | 12 | ||
| 13 | [dependencies] | 13 | [dependencies] |
| 14 | base64.workspace = true | 14 | base64.workspace = true |
| 15 | +clap = { workspace = true, features = ["derive"] } | ||
| 15 | bytes.workspace = true | 16 | bytes.workspace = true |
| 16 | futures-util.workspace = true | 17 | futures-util.workspace = true |
| 17 | hex.workspace = true | 18 | hex.workspace = true |
crates/iz-web/src/auth.rsmodified+15 -11
| @@ -124,24 +124,28 @@ pub async fn require_member(cx: &Cx) -> Result<CurrentMember> { | |||
| 124 | } | 124 | } |
| 125 | } | 125 | } |
| 126 | 126 | ||
| 127 | -/// The signed-in member with the level `need`. A viewer who tries a write gets `403`; a member | 127 | +/// The signed-in member with the level `need`. A viewer or member who tries a write gets `403`; a |
| 128 | -/// with no access, or a disabled one, gets `404`, so the page does not reveal that it exists. | 128 | +/// member with no access, or a disabled one, gets `404`, so the page does not reveal that it exists. |
| 129 | +/// Administrator pages answer `404` to everyone who is not an administrator, anonymous visitors | ||
| 130 | +/// included: an admin page does not reveal that it exists, so it never redirects to sign-in. | ||
| 129 | pub async fn require_role(cx: &Cx, need: Need) -> Result<CurrentMember> { | 131 | pub async fn require_role(cx: &Cx, need: Need) -> Result<CurrentMember> { |
| 132 | + if need == Need::Admin { | ||
| 133 | + let Some(me) = current_member(cx).await? else { | ||
| 134 | + return Err(not_found().into()); | ||
| 135 | + }; | ||
| 136 | + return match authorize(&me.actor(), &Action::Administer) { | ||
| 137 | + Ok(()) => Ok(me), | ||
| 138 | + Err(_) => Err(not_found().into()), | ||
| 139 | + }; | ||
| 140 | + } | ||
| 130 | let me = require_member(cx).await?; | 141 | let me = require_member(cx).await?; |
| 131 | let action = match need { | 142 | let action = match need { |
| 132 | Need::Viewer => Action::ReadBoard, | 143 | Need::Viewer => Action::ReadBoard, |
| 133 | - Need::Member => Action::WriteTask, | 144 | + _ => Action::WriteTask, |
| 134 | - Need::Admin => Action::Administer, | ||
| 135 | }; | 145 | }; |
| 136 | match authorize(&me.actor(), &action) { | 146 | match authorize(&me.actor(), &action) { |
| 137 | Ok(()) => Ok(me), | 147 | Ok(()) => Ok(me), |
| 138 | - // An active member who is refused an admin page is told so (403). A disabled member is not, | 148 | + Err(Denied::Forbidden) => Err(forbidden().into()), |
| 139 | - // so a disabled administrator sees the same 404 as anyone without access. | ||
| 140 | - Err(Denied::Forbidden) | ||
| 141 | - if need == Need::Member || (need == Need::Admin && !me.member.disabled) => | ||
| 142 | - { | ||
| 143 | - Err(forbidden().into()) | ||
| 144 | - } | ||
| 145 | Err(_) => Err(not_found().into()), | 149 | Err(_) => Err(not_found().into()), |
| 146 | } | 150 | } |
| 147 | } | 151 | } |
crates/iz-web/src/backup.rsadded+270 -0
| @@ -0,0 +1,270 @@ | |||
| 1 | +//! The scheduled backup worker. Every `interval_hours` it writes one backup set under `[backup] dir`, then | ||
| 2 | +//! keeps the newest `keep` finished sets and deletes the rest. It runs only when the config has a `[backup]` | ||
| 3 | +//! section, and stops with the stop flag. | ||
| 4 | +//! | ||
| 5 | +//! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a | ||
| 6 | +//! `VACUUM INTO` snapshot), `attachments/<id>` for every attachment whose bytes are local, and | ||
| 7 | +//! `manifest.json` written last (`iz_core::manifest`). A set is built in `.tmp-<ulid>` and renamed to its | ||
| 8 | +//! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed. | ||
| 9 | +//! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever | ||
| 10 | +//! deleted. Nothing is written in place. | ||
| 11 | + | ||
| 12 | +use std::os::unix::fs::DirBuilderExt; | ||
| 13 | +use std::path::{Path, PathBuf}; | ||
| 14 | +use std::time::Duration; | ||
| 15 | + | ||
| 16 | +use iz_core::clock::stamp_of; | ||
| 17 | +use iz_core::config::BackupConfig; | ||
| 18 | +use iz_core::manifest::{self, MANIFEST_NAME}; | ||
| 19 | +use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; | ||
| 20 | +use iz_core::store::{Store, new_id}; | ||
| 21 | +use iz_core::{Error, Result}; | ||
| 22 | +use tokio::sync::watch; | ||
| 23 | + | ||
| 24 | +use crate::state::AppState; | ||
| 25 | + | ||
| 26 | +/// Prefix of a set that is still being written. Reason: a crash leaves a visibly unfinished directory. | ||
| 27 | +const TMP_PREFIX: &str = ".tmp-"; | ||
| 28 | +/// The database copy inside a set. | ||
| 29 | +const DB_FILE: &str = "iz.db"; | ||
| 30 | +/// How long a healthcheck ping may take, in seconds. Reason: a slow ping must not hold the worker. | ||
| 31 | +const PING_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 32 | +/// The stamp format of a set's directory name. Reason: no colons, so the name is portable. | ||
| 33 | +const SET_STAMP_FORMAT: &str = "%Y%m%dT%H%M%SZ"; | ||
| 34 | +/// Length of a set's directory name, which is the stamp format above. | ||
| 35 | +const SET_NAME_LEN: usize = 16; | ||
| 36 | + | ||
| 37 | +/// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing. | ||
| 38 | +/// The first backup runs at once, then one every `interval_hours`. | ||
| 39 | +pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) { | ||
| 40 | + let Some(policy) = state.config.backup.clone() else { | ||
| 41 | + return; | ||
| 42 | + }; | ||
| 43 | + tokio::spawn(async move { | ||
| 44 | + let client = match reqwest::Client::builder() | ||
| 45 | + .timeout(PING_TIMEOUT) | ||
| 46 | + .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) | ||
| 47 | + .build() | ||
| 48 | + { | ||
| 49 | + Ok(client) => Some(client), | ||
| 50 | + Err(error) => { | ||
| 51 | + tracing::warn!(error = %error, "healthcheck client not built; pings are off"); | ||
| 52 | + None | ||
| 53 | + } | ||
| 54 | + }; | ||
| 55 | + let interval = Duration::from_secs(u64::from(policy.interval_hours) * 3600); | ||
| 56 | + loop { | ||
| 57 | + run_once(&state, &policy, client.as_ref(), &mut stop).await; | ||
| 58 | + tokio::select! { | ||
| 59 | + () = tokio::time::sleep(interval) => {} | ||
| 60 | + _ = stop.wait_for(|stopped| *stopped) => break, | ||
| 61 | + } | ||
| 62 | + } | ||
| 63 | + tracing::info!("backup worker stopped"); | ||
| 64 | + }); | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// One backup: write a set, publish it, prune the old sets, ping the healthcheck. A failure is logged and | ||
| 68 | +/// leaves no partial set. A stop request cancels a set in progress and removes it. | ||
| 69 | +async fn run_once( | ||
| 70 | + state: &AppState, | ||
| 71 | + policy: &BackupConfig, | ||
| 72 | + client: Option<&reqwest::Client>, | ||
| 73 | + stop: &mut watch::Receiver<bool>, | ||
| 74 | +) { | ||
| 75 | + if let Err(error) = ensure_dir(&policy.dir) { | ||
| 76 | + tracing::warn!(error = %error, "backup directory cannot be created"); | ||
| 77 | + return; | ||
| 78 | + } | ||
| 79 | + let now = jiff::Timestamp::now(); | ||
| 80 | + let name = now.strftime(SET_STAMP_FORMAT).to_string(); | ||
| 81 | + let created_at = match stamp_of(now) { | ||
| 82 | + Ok(stamp) => stamp, | ||
| 83 | + Err(error) => { | ||
| 84 | + tracing::warn!(error = %error, "backup time cannot be stamped"); | ||
| 85 | + return; | ||
| 86 | + } | ||
| 87 | + }; | ||
| 88 | + let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id())); | ||
| 89 | + let outcome = tokio::select! { | ||
| 90 | + result = write_set(&state.store, &state.config.data_dir, &tmp, &created_at) => result, | ||
| 91 | + _ = stop.wait_for(|stopped| *stopped) => { | ||
| 92 | + Err(Error::Io(std::io::Error::other("stopped before the set was finished"))) | ||
| 93 | + } | ||
| 94 | + }; | ||
| 95 | + let outcome = outcome.and_then(|files| publish(&tmp, &policy.dir, &name).map(|()| files)); | ||
| 96 | + match outcome { | ||
| 97 | + Ok(files) => { | ||
| 98 | + tracing::info!(set = %name, files, "backup set written"); | ||
| 99 | + let keep = usize::try_from(policy.keep).unwrap_or(usize::MAX); | ||
| 100 | + match prune(&policy.dir, keep) { | ||
| 101 | + Ok(0) => {} | ||
| 102 | + Ok(removed) => tracing::info!(removed, "old backup sets deleted"), | ||
| 103 | + Err(error) => tracing::warn!(error = %error, "pruning old backup sets failed"), | ||
| 104 | + } | ||
| 105 | + if let (Some(url), Some(client)) = (policy.healthcheck_url.as_deref(), client) { | ||
| 106 | + ping(client, url).await; | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | + Err(error) => { | ||
| 110 | + // Only the directory this run created is removed, by its exact path. | ||
| 111 | + let _ = std::fs::remove_dir_all(&tmp); | ||
| 112 | + tracing::warn!(error = %error, "backup failed; the partial set was removed"); | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +/// Writes the files of one set into `tmp` and the manifest last. Returns the number of files listed, not | ||
| 118 | +/// counting the manifest. The caller removes `tmp` on error. | ||
| 119 | +async fn write_set(store: &Store, data_dir: &Path, tmp: &Path, created_at: &str) -> Result<usize> { | ||
| 120 | + create_dir(tmp, false)?; | ||
| 121 | + store.snapshot_to(&tmp.join(DB_FILE)).await?; | ||
| 122 | + let mut paths = vec![DB_FILE.to_owned()]; | ||
| 123 | + let attachments = tmp.join(ATTACHMENTS_DIR); | ||
| 124 | + create_dir(&attachments, false)?; | ||
| 125 | + for id in store.local_attachment_ids().await? { | ||
| 126 | + let source = blob_path(data_dir, &id)?; | ||
| 127 | + let relative = format!("{ATTACHMENTS_DIR}/{id}"); | ||
| 128 | + let target = tmp.join(&relative); | ||
| 129 | + tokio::fs::copy(&source, &target).await?; | ||
| 130 | + tokio::fs::File::open(&target).await?.sync_all().await?; | ||
| 131 | + paths.push(relative); | ||
| 132 | + } | ||
| 133 | + let files = paths.len(); | ||
| 134 | + // Hashing reads every file, which can take a while; it runs off the async threads. | ||
| 135 | + let dir = tmp.to_owned(); | ||
| 136 | + let created = created_at.to_owned(); | ||
| 137 | + let build = env!("IZ_BUILD_SHA").to_owned(); | ||
| 138 | + tokio::task::spawn_blocking(move || manifest::write_manifest(&dir, &created, &build, &paths)) | ||
| 139 | + .await | ||
| 140 | + .map_err(|error| Error::Io(std::io::Error::other(error)))??; | ||
| 141 | + Ok(files) | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +/// Creates the backup directory and any missing parents, unless it already exists. | ||
| 145 | +fn ensure_dir(dir: &Path) -> std::io::Result<()> { | ||
| 146 | + if dir.is_dir() { | ||
| 147 | + return Ok(()); | ||
| 148 | + } | ||
| 149 | + create_dir(dir, true) | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +/// Renames a complete set to its stamp and makes the rename durable. Refuses to replace an existing name. | ||
| 153 | +fn publish(tmp: &Path, dir: &Path, name: &str) -> Result<()> { | ||
| 154 | + let target = dir.join(name); | ||
| 155 | + if std::fs::symlink_metadata(&target).is_ok() { | ||
| 156 | + return Err(Error::Conflict(format!("backup set {name} already exists"))); | ||
| 157 | + } | ||
| 158 | + std::fs::rename(tmp, &target)?; | ||
| 159 | + std::fs::File::open(dir)?.sync_all()?; | ||
| 160 | + Ok(()) | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +/// Deletes all finished sets except the newest `keep`. Only directories named like a set and holding a | ||
| 164 | +/// manifest are candidates, so an unrelated directory in the backup dir is never touched. Returns the count. | ||
| 165 | +fn prune(dir: &Path, keep: usize) -> Result<usize> { | ||
| 166 | + let mut sets: Vec<PathBuf> = std::fs::read_dir(dir)? | ||
| 167 | + .filter_map(std::result::Result::ok) | ||
| 168 | + .filter(|entry| is_set_name(&entry.file_name().to_string_lossy())) | ||
| 169 | + .map(|entry| entry.path()) | ||
| 170 | + .filter(|path| is_finished_set(path)) | ||
| 171 | + .collect(); | ||
| 172 | + // The stamp is fixed width and sorts in time order, so the name order is the age order. | ||
| 173 | + sets.sort(); | ||
| 174 | + let excess = sets.len().saturating_sub(keep); | ||
| 175 | + for old in &sets[..excess] { | ||
| 176 | + std::fs::remove_dir_all(old)?; | ||
| 177 | + } | ||
| 178 | + Ok(excess) | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/// Whether `name` has the shape of a set's directory name: `YYYYMMDDTHHMMSSZ`. | ||
| 182 | +fn is_set_name(name: &str) -> bool { | ||
| 183 | + let bytes = name.as_bytes(); | ||
| 184 | + bytes.len() == SET_NAME_LEN | ||
| 185 | + && bytes.iter().enumerate().all(|(i, byte)| match i { | ||
| 186 | + 8 => *byte == b'T', | ||
| 187 | + 15 => *byte == b'Z', | ||
| 188 | + _ => byte.is_ascii_digit(), | ||
| 189 | + }) | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +/// Whether `path` is a real directory (not a link) that holds a manifest. | ||
| 193 | +fn is_finished_set(path: &Path) -> bool { | ||
| 194 | + let is_dir = std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir()); | ||
| 195 | + let has_manifest = std::fs::symlink_metadata(path.join(MANIFEST_NAME)) | ||
| 196 | + .is_ok_and(|meta| meta.file_type().is_file()); | ||
| 197 | + is_dir && has_manifest | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// Creates a directory with mode 0700. `recursive` also creates missing parents. | ||
| 201 | +fn create_dir(path: &Path, recursive: bool) -> std::io::Result<()> { | ||
| 202 | + std::fs::DirBuilder::new() | ||
| 203 | + .recursive(recursive) | ||
| 204 | + .mode(0o700) | ||
| 205 | + .create(path) | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +/// Pings the healthcheck once. A failure is logged without the URL, because the URL can carry a secret key. | ||
| 209 | +async fn ping(client: &reqwest::Client, url: &str) { | ||
| 210 | + match client.get(url).send().await { | ||
| 211 | + Ok(response) if response.status().is_success() => {} | ||
| 212 | + Ok(response) => { | ||
| 213 | + tracing::warn!(status = %response.status(), "healthcheck ping was refused"); | ||
| 214 | + } | ||
| 215 | + Err(error) => { | ||
| 216 | + tracing::warn!(error = %error.without_url(), "healthcheck ping failed"); | ||
| 217 | + } | ||
| 218 | + } | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +#[cfg(test)] | ||
| 222 | +mod tests { | ||
| 223 | + use super::*; | ||
| 224 | + | ||
| 225 | + /// A finished set on disk: a directory with a manifest, named by its stamp. | ||
| 226 | + fn fake_set(dir: &Path, name: &str) { | ||
| 227 | + let set = dir.join(name); | ||
| 228 | + std::fs::create_dir(&set).expect("set dir"); | ||
| 229 | + std::fs::write(set.join(MANIFEST_NAME), b"{}").expect("manifest"); | ||
| 230 | + } | ||
| 231 | + | ||
| 232 | + #[tokio::test] | ||
| 233 | + async fn a_written_set_verifies_and_is_published_by_its_stamp() { | ||
| 234 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 235 | + let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); | ||
| 236 | + let tmp = dir.path().join(format!("{TMP_PREFIX}{}", new_id())); | ||
| 237 | + let created = "2026-10-28T09:30:00.000000000Z"; | ||
| 238 | + write_set(&store, dir.path(), &tmp, created) | ||
| 239 | + .await | ||
| 240 | + .expect("set written"); | ||
| 241 | + publish(&tmp, dir.path(), "20261028T093000Z").expect("published"); | ||
| 242 | + let published = dir.path().join("20261028T093000Z"); | ||
| 243 | + let verified = manifest::verify_set(&published).expect("the set verifies"); | ||
| 244 | + assert_eq!(verified.created_at, created); | ||
| 245 | + assert!(verified.files.iter().any(|file| file.path == DB_FILE)); | ||
| 246 | + assert!(!tmp.exists(), "the temporary name is gone after the rename"); | ||
| 247 | + } | ||
| 248 | + | ||
| 249 | + #[test] | ||
| 250 | + fn prune_keeps_the_newest_sets_and_leaves_other_directories() { | ||
| 251 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 252 | + for name in [ | ||
| 253 | + "20260101T000000Z", | ||
| 254 | + "20260102T000000Z", | ||
| 255 | + "20260103T000000Z", | ||
| 256 | + "20260104T000000Z", | ||
| 257 | + ] { | ||
| 258 | + fake_set(dir.path(), name); | ||
| 259 | + } | ||
| 260 | + std::fs::create_dir(dir.path().join("notes")).expect("unrelated dir"); | ||
| 261 | + std::fs::create_dir(dir.path().join(format!("{TMP_PREFIX}abc"))).expect("tmp dir"); | ||
| 262 | + assert_eq!(prune(dir.path(), 2).expect("prune"), 2); | ||
| 263 | + assert!(!dir.path().join("20260101T000000Z").exists()); | ||
| 264 | + assert!(!dir.path().join("20260102T000000Z").exists()); | ||
| 265 | + assert!(dir.path().join("20260103T000000Z").exists()); | ||
| 266 | + assert!(dir.path().join("20260104T000000Z").exists()); | ||
| 267 | + assert!(dir.path().join("notes").exists()); | ||
| 268 | + assert!(dir.path().join(format!("{TMP_PREFIX}abc")).exists()); | ||
| 269 | + } | ||
| 270 | +} | ||
crates/iz-web/src/boot.rsmodified+9 -0
| @@ -35,6 +35,10 @@ const DEFAULT_KEY_PREFIX: &str = "IZ"; | |||
| 35 | pub async fn serve(config_path: &Path) -> iz_core::Result<()> { | 35 | pub async fn serve(config_path: &Path) -> iz_core::Result<()> { |
| 36 | let config = Config::load(config_path)?; | 36 | let config = Config::load(config_path)?; |
| 37 | let listen = config.listen; | 37 | let listen = config.listen; |
| 38 | + // One server per data directory: the lock is held until this function returns, so a second `iz` | ||
| 39 | + // (or an operator command) refuses to touch the same files while this one runs. | ||
| 40 | + std::fs::create_dir_all(&config.data_dir)?; | ||
| 41 | + let _lock = crate::cli::lock_data_dir(&config.data_dir).map_err(iz_core::Error::Config)?; | ||
| 38 | let state = open_state(config).await?; | 42 | let state = open_state(config).await?; |
| 39 | 43 | ||
| 40 | let listener = TcpListener::bind(listen).await.map_err(|error| { | 44 | let listener = TcpListener::bind(listen).await.map_err(|error| { |
| @@ -52,6 +56,9 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> { | |||
| 52 | directory::spawn(state.clone(), stop_rx.clone()); | 56 | directory::spawn(state.clone(), stop_rx.clone()); |
| 53 | attachments::spawn(state.clone(), stop_rx.clone()); | 57 | attachments::spawn(state.clone(), stop_rx.clone()); |
| 54 | crate::mail::spawn(state.clone(), stop_rx.clone()); | 58 | crate::mail::spawn(state.clone(), stop_rx.clone()); |
| 59 | + crate::family::spawn(state.clone(), stop_rx.clone()); | ||
| 60 | + crate::backup::spawn(state.clone(), stop_rx.clone()); | ||
| 61 | + crate::sweeper::spawn(state.clone(), stop_rx.clone()); | ||
| 55 | tokio::spawn(async move { | 62 | tokio::spawn(async move { |
| 56 | shutdown_signal().await; | 63 | shutdown_signal().await; |
| 57 | tracing::info!("shutdown signal received"); | 64 | tracing::info!("shutdown signal received"); |
| @@ -103,6 +110,7 @@ async fn open_state(config: Config) -> iz_core::Result<AppState> { | |||
| 103 | key: Arc::new(key), | 110 | key: Arc::new(key), |
| 104 | live: Arc::new(LiveHub::default()), | 111 | live: Arc::new(LiveHub::default()), |
| 105 | oidc, | 112 | oidc, |
| 113 | + family: Arc::default(), | ||
| 106 | }) | 114 | }) |
| 107 | } | 115 | } |
| 108 | 116 | ||
| @@ -179,6 +187,7 @@ mod tests { | |||
| 179 | key: Arc::new(key), | 187 | key: Arc::new(key), |
| 180 | live: Arc::new(LiveHub::default()), | 188 | live: Arc::new(LiveHub::default()), |
| 181 | oidc: None, | 189 | oidc: None, |
| 190 | + family: Arc::default(), | ||
| 182 | }; | 191 | }; |
| 183 | (dir, state) | 192 | (dir, state) |
| 184 | } | 193 | } |
crates/iz-web/src/cli/export.rsadded+291 -0
| @@ -0,0 +1,291 @@ | |||
| 1 | +//! `iz export --out <dir>`: writes the board to a new directory so it can be read or kept without the | ||
| 2 | +//! database. | ||
| 3 | +//! | ||
| 4 | +//! The directory holds `board.json` (the board, its tasks, assignees, dependencies, comments, activity, | ||
| 5 | +//! attachment metadata and the members named by those rows), `attachments/<id>` for every attachment whose | ||
| 6 | +//! bytes are on this disk, and `manifest.json` for all of them. An attachment whose bytes are elsewhere | ||
| 7 | +//! (location `in`) or that is moving is listed with `"bytes": false`; the export then exits 1 after writing | ||
| 8 | +//! everything else, so an incomplete export is never silent. The output is refused unless `--out` is missing | ||
| 9 | +//! or an empty directory, and no path in it is built from anything but fixed names and validated ULIDs. No | ||
| 10 | +//! symlink is created, and nothing is written outside `--out`. | ||
| 11 | + | ||
| 12 | +use std::fs::{DirBuilder, OpenOptions}; | ||
| 13 | +use std::io::{Read, Write}; | ||
| 14 | +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; | ||
| 15 | +use std::path::Path; | ||
| 16 | +use std::process::ExitCode; | ||
| 17 | + | ||
| 18 | +use iz_core::config::Config; | ||
| 19 | +use iz_core::manifest::write_manifest; | ||
| 20 | +use iz_core::staging::blob_path; | ||
| 21 | +use iz_core::store::export::{AttachmentRow, ReadOnly}; | ||
| 22 | +use iz_core::time::now_stamp; | ||
| 23 | +use sha2::{Digest, Sha256}; | ||
| 24 | + | ||
| 25 | +use super::{database_file, describe, existing_data_dir, fail, take_lock}; | ||
| 26 | + | ||
| 27 | +/// The file that holds the board. | ||
| 28 | +const BOARD_FILE: &str = "board.json"; | ||
| 29 | +/// The directory inside `--out` that holds the attachment bytes. | ||
| 30 | +const ATTACHMENTS_DIR: &str = "attachments"; | ||
| 31 | +/// Read chunk for copying bytes. Reason: keeps memory flat for large attachments. | ||
| 32 | +const CHUNK: usize = 64 * 1024; | ||
| 33 | + | ||
| 34 | +/// Runs the export and maps its outcome to an exit status. | ||
| 35 | +pub async fn run(config_path: &Path, out: &Path) -> ExitCode { | ||
| 36 | + let config = match Config::load(config_path) { | ||
| 37 | + Ok(config) => config, | ||
| 38 | + Err(error) => return fail(describe(&error)), | ||
| 39 | + }; | ||
| 40 | + let data_dir = match existing_data_dir(&config) { | ||
| 41 | + Ok(dir) => dir, | ||
| 42 | + Err(message) => return fail(message), | ||
| 43 | + }; | ||
| 44 | + let _lock = match take_lock(&data_dir) { | ||
| 45 | + Ok(lock) => lock, | ||
| 46 | + Err(code) => return code, | ||
| 47 | + }; | ||
| 48 | + if let Err(message) = prepare_out(out) { | ||
| 49 | + return fail(message); | ||
| 50 | + } | ||
| 51 | + match write_export(&config, &data_dir, out).await { | ||
| 52 | + Ok(report) => { | ||
| 53 | + println!( | ||
| 54 | + "exported {} attachments with bytes and {} without to {}", | ||
| 55 | + report.with_bytes, | ||
| 56 | + report.without_bytes.len(), | ||
| 57 | + out.display() | ||
| 58 | + ); | ||
| 59 | + if report.without_bytes.is_empty() { | ||
| 60 | + return ExitCode::SUCCESS; | ||
| 61 | + } | ||
| 62 | + for (id, reason) in &report.without_bytes { | ||
| 63 | + eprintln!("iz: attachment {id} has no bytes in the export: {reason}"); | ||
| 64 | + } | ||
| 65 | + eprintln!( | ||
| 66 | + "iz: the export is incomplete; {} attachments have no bytes", | ||
| 67 | + report.without_bytes.len() | ||
| 68 | + ); | ||
| 69 | + ExitCode::FAILURE | ||
| 70 | + } | ||
| 71 | + Err(message) => fail(message), | ||
| 72 | + } | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// What an export wrote, for the summary. | ||
| 76 | +struct Report { | ||
| 77 | + /// Attachments whose bytes are in the export. | ||
| 78 | + with_bytes: usize, | ||
| 79 | + /// Attachments whose bytes are not, with the reason. | ||
| 80 | + without_bytes: Vec<(String, String)>, | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// Makes `out` a new directory with mode 0700, or accepts an existing empty one. A link or a file is | ||
| 84 | +/// refused, and so is a directory with anything in it. | ||
| 85 | +fn prepare_out(out: &Path) -> Result<(), String> { | ||
| 86 | + match std::fs::symlink_metadata(out) { | ||
| 87 | + Ok(meta) => { | ||
| 88 | + if !meta.file_type().is_dir() { | ||
| 89 | + return Err(format!("{} exists and is not a directory", out.display())); | ||
| 90 | + } | ||
| 91 | + let mut entries = std::fs::read_dir(out) | ||
| 92 | + .map_err(|error| format!("cannot read {}: {error}", out.display()))?; | ||
| 93 | + if entries.next().is_some() { | ||
| 94 | + return Err(format!("{} is not empty", out.display())); | ||
| 95 | + } | ||
| 96 | + Ok(()) | ||
| 97 | + } | ||
| 98 | + Err(_) => DirBuilder::new() | ||
| 99 | + .mode(0o700) | ||
| 100 | + .create(out) | ||
| 101 | + .map_err(|error| format!("cannot create {}: {error}", out.display())), | ||
| 102 | + } | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// Reads the database and writes the export. Every failure before the manifest leaves the directory | ||
| 106 | +/// partly written; the caller reports it and the operator removes it. | ||
| 107 | +async fn write_export(config: &Config, data_dir: &Path, out: &Path) -> Result<Report, String> { | ||
| 108 | + let database = database_file(config)?; | ||
| 109 | + let db = ReadOnly::open(&database) | ||
| 110 | + .await | ||
| 111 | + .map_err(|error| describe(&error))?; | ||
| 112 | + let board_ids = db.board_ids().await.map_err(|error| describe(&error))?; | ||
| 113 | + let [board_id] = board_ids.as_slice() else { | ||
| 114 | + return Err(format!( | ||
| 115 | + "expected one board in the database, found {}", | ||
| 116 | + board_ids.len() | ||
| 117 | + )); | ||
| 118 | + }; | ||
| 119 | + let dump = db | ||
| 120 | + .export_board(board_id) | ||
| 121 | + .await | ||
| 122 | + .map_err(|error| describe(&error))?; | ||
| 123 | + let rows = db | ||
| 124 | + .board_attachment_rows(board_id) | ||
| 125 | + .await | ||
| 126 | + .map_err(|error| describe(&error))?; | ||
| 127 | + | ||
| 128 | + DirBuilder::new() | ||
| 129 | + .mode(0o700) | ||
| 130 | + .recursive(true) | ||
| 131 | + .create(out.join(ATTACHMENTS_DIR)) | ||
| 132 | + .map_err(|error| format!("cannot create the attachments directory: {error}"))?; | ||
| 133 | + let mut written = vec![BOARD_FILE.to_owned()]; | ||
| 134 | + let mut attachments = Vec::with_capacity(rows.len()); | ||
| 135 | + let mut report = Report { | ||
| 136 | + with_bytes: 0, | ||
| 137 | + without_bytes: Vec::new(), | ||
| 138 | + }; | ||
| 139 | + for row in &rows { | ||
| 140 | + // The id is used in two file names, so it must be the canonical ULID text, or it is refused. | ||
| 141 | + let source = blob_path(data_dir, &row.id).map_err(|error| describe(&error))?; | ||
| 142 | + let mut entry = attachment_json(row); | ||
| 143 | + if row.location == "local" { | ||
| 144 | + match copy_blob(&source, &out.join(ATTACHMENTS_DIR).join(&row.id), row)? { | ||
| 145 | + Ok(()) => { | ||
| 146 | + let relative = format!("{ATTACHMENTS_DIR}/{}", row.id); | ||
| 147 | + entry["bytes"] = serde_json::Value::Bool(true); | ||
| 148 | + entry["file"] = serde_json::Value::String(relative.clone()); | ||
| 149 | + written.push(relative); | ||
| 150 | + report.with_bytes += 1; | ||
| 151 | + } | ||
| 152 | + Err(reason) => { | ||
| 153 | + entry["bytes"] = serde_json::Value::Bool(false); | ||
| 154 | + report.without_bytes.push((row.id.clone(), reason)); | ||
| 155 | + } | ||
| 156 | + } | ||
| 157 | + } else { | ||
| 158 | + entry["bytes"] = serde_json::Value::Bool(false); | ||
| 159 | + report.without_bytes.push(( | ||
| 160 | + row.id.clone(), | ||
| 161 | + format!( | ||
| 162 | + "location is {}, the bytes are not on this disk", | ||
| 163 | + row.location | ||
| 164 | + ), | ||
| 165 | + )); | ||
| 166 | + } | ||
| 167 | + attachments.push(entry); | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + let members = dump.members; | ||
| 171 | + let board = serde_json::json!({ | ||
| 172 | + "format": "iz-export", | ||
| 173 | + "version": 1, | ||
| 174 | + "exported_at": now_stamp(), | ||
| 175 | + "board": dump.board, | ||
| 176 | + "columns": dump.columns, | ||
| 177 | + "tags": dump.tags, | ||
| 178 | + "tasks": dump.tasks, | ||
| 179 | + "assignees": dump.assignees, | ||
| 180 | + "dependencies": dump.dependencies, | ||
| 181 | + "comments": dump.comments, | ||
| 182 | + "activity": dump.activity, | ||
| 183 | + "attachments": attachments, | ||
| 184 | + "members": members, | ||
| 185 | + }); | ||
| 186 | + let bytes = serde_json::to_vec_pretty(&board) | ||
| 187 | + .map_err(|error| format!("encoding {BOARD_FILE}: {error}"))?; | ||
| 188 | + write_new(&out.join(BOARD_FILE), &bytes)?; | ||
| 189 | + | ||
| 190 | + write_manifest(out, &now_stamp(), env!("IZ_BUILD_SHA"), &written) | ||
| 191 | + .map_err(|error| describe(&error))?; | ||
| 192 | + Ok(report) | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +/// The metadata of an attachment row as the export file states it. | ||
| 196 | +fn attachment_json(row: &AttachmentRow) -> serde_json::Value { | ||
| 197 | + serde_json::json!({ | ||
| 198 | + "id": row.id, | ||
| 199 | + "task_id": row.task_id, | ||
| 200 | + "name": row.name, | ||
| 201 | + "mime": row.mime, | ||
| 202 | + "size": row.size, | ||
| 203 | + "sha256": row.sha256, | ||
| 204 | + "uploaded_by": row.uploaded_by, | ||
| 205 | + "created_at": row.created_at, | ||
| 206 | + "location": row.location, | ||
| 207 | + }) | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +/// Copies the bytes of a local attachment to `dest` (created new, mode 0600) and checks that they have the | ||
| 211 | +/// size and digest of the row. The source must be a regular file. On a mismatch the copy is removed and the | ||
| 212 | +/// reason is returned as the inner error; the outer error is a failure to write. | ||
| 213 | +fn copy_blob( | ||
| 214 | + source: &Path, | ||
| 215 | + dest: &Path, | ||
| 216 | + row: &AttachmentRow, | ||
| 217 | +) -> Result<Result<(), String>, String> { | ||
| 218 | + let meta = match std::fs::symlink_metadata(source) { | ||
| 219 | + Ok(meta) => meta, | ||
| 220 | + Err(_) => return Ok(Err("the bytes are missing from the store".into())), | ||
| 221 | + }; | ||
| 222 | + if !meta.file_type().is_file() { | ||
| 223 | + return Ok(Err("the stored entry is not a regular file".into())); | ||
| 224 | + } | ||
| 225 | + let mut input = std::fs::File::open(source) | ||
| 226 | + .map_err(|error| format!("cannot read {}: {error}", source.display()))?; | ||
| 227 | + let mut output = OpenOptions::new() | ||
| 228 | + .write(true) | ||
| 229 | + .create_new(true) | ||
| 230 | + .mode(0o600) | ||
| 231 | + .open(dest) | ||
| 232 | + .map_err(|error| format!("cannot create {}: {error}", dest.display()))?; | ||
| 233 | + let mut hasher = Sha256::new(); | ||
| 234 | + let mut size: u64 = 0; | ||
| 235 | + let mut buffer = vec![0u8; CHUNK]; | ||
| 236 | + loop { | ||
| 237 | + let read = input | ||
| 238 | + .read(&mut buffer) | ||
| 239 | + .map_err(|error| format!("cannot read {}: {error}", source.display()))?; | ||
| 240 | + if read == 0 { | ||
| 241 | + break; | ||
| 242 | + } | ||
| 243 | + output | ||
| 244 | + .write_all(&buffer[..read]) | ||
| 245 | + .map_err(|error| format!("cannot write {}: {error}", dest.display()))?; | ||
| 246 | + hasher.update(&buffer[..read]); | ||
| 247 | + size += read as u64; | ||
| 248 | + } | ||
| 249 | + output | ||
| 250 | + .sync_all() | ||
| 251 | + .map_err(|error| format!("cannot sync {}: {error}", dest.display()))?; | ||
| 252 | + let digest = hex::encode(hasher.finalize()); | ||
| 253 | + if size != row.size || digest != row.sha256 { | ||
| 254 | + drop(output); | ||
| 255 | + std::fs::remove_file(dest) | ||
| 256 | + .map_err(|error| format!("cannot remove {}: {error}", dest.display()))?; | ||
| 257 | + return Ok(Err( | ||
| 258 | + "the bytes do not match the recorded size or digest".into() | ||
| 259 | + )); | ||
| 260 | + } | ||
| 261 | + Ok(Ok(())) | ||
| 262 | +} | ||
| 263 | + | ||
| 264 | +/// Writes a new file with mode 0600 and syncs it. Used for `board.json`. | ||
| 265 | +fn write_new(path: &Path, bytes: &[u8]) -> Result<(), String> { | ||
| 266 | + let mut file = OpenOptions::new() | ||
| 267 | + .write(true) | ||
| 268 | + .create_new(true) | ||
| 269 | + .mode(0o600) | ||
| 270 | + .open(path) | ||
| 271 | + .map_err(|error| format!("cannot create {}: {error}", path.display()))?; | ||
| 272 | + file.write_all(bytes) | ||
| 273 | + .and_then(|()| file.sync_all()) | ||
| 274 | + .map_err(|error| format!("cannot write {}: {error}", path.display())) | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +#[cfg(test)] | ||
| 278 | +mod tests { | ||
| 279 | + use super::*; | ||
| 280 | + | ||
| 281 | + #[test] | ||
| 282 | + fn export_refuses_a_non_empty_out_directory() { | ||
| 283 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 284 | + std::fs::write(dir.path().join("keep.txt"), b"x").expect("seed file"); | ||
| 285 | + let error = prepare_out(dir.path()).expect_err("non-empty must be refused"); | ||
| 286 | + assert!(error.contains("is not empty"), "got: {error}"); | ||
| 287 | + let empty = dir.path().join("fresh"); | ||
| 288 | + prepare_out(&empty).expect("a missing directory is created"); | ||
| 289 | + assert!(empty.is_dir()); | ||
| 290 | + } | ||
| 291 | +} | ||
crates/iz-web/src/cli/fsck.rsadded+314 -0
| @@ -0,0 +1,314 @@ | |||
| 1 | +//! `iz fsck`: a read-only check of the database and the attachments. | ||
| 2 | +//! | ||
| 3 | +//! It checks: `integrity_check` returns `ok`; the migration history is contiguous and known to this build; | ||
| 4 | +//! every attachment row with location `local` has its file at the expected path, a regular file whose size | ||
| 5 | +//! and SHA-256 match the row; no row is stuck in `moving`; and every file in `attachments/` is named by a | ||
| 6 | +//! row (unnamed files are reported, not deleted). Rows with location `in` are counted, not checked: their | ||
| 7 | +//! bytes are in another service. The database is opened read-only and never migrated. The lock file is the | ||
| 8 | +//! only thing it may create. Exit status 0 when nothing is wrong, 1 when anything is. | ||
| 9 | + | ||
| 10 | +use std::collections::HashSet; | ||
| 11 | +use std::path::Path; | ||
| 12 | +use std::process::ExitCode; | ||
| 13 | + | ||
| 14 | +use iz_core::config::Config; | ||
| 15 | +use iz_core::manifest::digest_file; | ||
| 16 | +use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; | ||
| 17 | +use iz_core::store::export::{ReadOnly, migrations_problem}; | ||
| 18 | + | ||
| 19 | +use super::{database_file, describe, existing_data_dir, fail, take_lock}; | ||
| 20 | + | ||
| 21 | +/// Runs the check, prints the report, and maps the outcome to an exit status. | ||
| 22 | +pub async fn run(config_path: &Path) -> ExitCode { | ||
| 23 | + let config = match Config::load(config_path) { | ||
| 24 | + Ok(config) => config, | ||
| 25 | + Err(error) => return fail(describe(&error)), | ||
| 26 | + }; | ||
| 27 | + let data_dir = match existing_data_dir(&config) { | ||
| 28 | + Ok(dir) => dir, | ||
| 29 | + Err(message) => return fail(message), | ||
| 30 | + }; | ||
| 31 | + let _lock = match take_lock(&data_dir) { | ||
| 32 | + Ok(lock) => lock, | ||
| 33 | + Err(code) => return code, | ||
| 34 | + }; | ||
| 35 | + let mut report = Report::default(); | ||
| 36 | + check(&config, &data_dir, &mut report).await; | ||
| 37 | + for line in &report.lines { | ||
| 38 | + println!("{line}"); | ||
| 39 | + } | ||
| 40 | + if report.problems == 0 { | ||
| 41 | + println!("fsck: clean"); | ||
| 42 | + ExitCode::SUCCESS | ||
| 43 | + } else { | ||
| 44 | + println!("fsck: {} problems found", report.problems); | ||
| 45 | + ExitCode::FAILURE | ||
| 46 | + } | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// The lines of the report and how many of them are problems. | ||
| 50 | +#[derive(Default)] | ||
| 51 | +struct Report { | ||
| 52 | + /// Every line printed, in order. | ||
| 53 | + lines: Vec<String>, | ||
| 54 | + /// How many lines are problems (the exit status depends on it). | ||
| 55 | + problems: usize, | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +impl Report { | ||
| 59 | + /// Records a line that is fine. | ||
| 60 | + fn ok(&mut self, text: impl Into<String>) { | ||
| 61 | + self.lines.push(format!("ok: {}", text.into())); | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + /// Records a line that is a problem. | ||
| 65 | + fn problem(&mut self, text: impl Into<String>) { | ||
| 66 | + self.problems += 1; | ||
| 67 | + self.lines.push(format!("problem: {}", text.into())); | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// Runs every check. Nothing here writes to the data directory. | ||
| 72 | +async fn check(config: &Config, data_dir: &Path, report: &mut Report) { | ||
| 73 | + let attachments_dir = data_dir.join(ATTACHMENTS_DIR); | ||
| 74 | + let database = match database_file(config) { | ||
| 75 | + Ok(path) => path, | ||
| 76 | + Err(message) => { | ||
| 77 | + report.problem(message); | ||
| 78 | + return; | ||
| 79 | + } | ||
| 80 | + }; | ||
| 81 | + let db = match ReadOnly::open(&database).await { | ||
| 82 | + Ok(db) => db, | ||
| 83 | + Err(error) => { | ||
| 84 | + report.problem(format!("cannot open the database: {}", describe(&error))); | ||
| 85 | + return; | ||
| 86 | + } | ||
| 87 | + }; | ||
| 88 | + match db.integrity_check().await { | ||
| 89 | + Ok(rows) if rows == ["ok"] => report.ok("database integrity_check"), | ||
| 90 | + Ok(rows) => report.problem(format!("integrity_check: {}", rows.join("; "))), | ||
| 91 | + Err(error) => report.problem(format!("integrity_check failed: {}", describe(&error))), | ||
| 92 | + } | ||
| 93 | + match db.migration_versions().await { | ||
| 94 | + Ok(versions) => match migrations_problem(&versions) { | ||
| 95 | + None => report.ok(format!("migrations 1 to {} are contiguous", versions.len())), | ||
| 96 | + Some(problem) => report.problem(problem), | ||
| 97 | + }, | ||
| 98 | + Err(error) => report.problem(format!("cannot read migrations: {}", describe(&error))), | ||
| 99 | + } | ||
| 100 | + let rows = match db.attachment_rows().await { | ||
| 101 | + Ok(rows) => rows, | ||
| 102 | + Err(error) => { | ||
| 103 | + report.problem(format!("cannot read attachments: {}", describe(&error))); | ||
| 104 | + return; | ||
| 105 | + } | ||
| 106 | + }; | ||
| 107 | + | ||
| 108 | + let known: HashSet<&str> = rows.iter().map(|row| row.id.as_str()).collect(); | ||
| 109 | + let mut local_ok = 0usize; | ||
| 110 | + let mut elsewhere = 0usize; | ||
| 111 | + for row in &rows { | ||
| 112 | + match row.location.as_str() { | ||
| 113 | + "local" => {} | ||
| 114 | + "in" => { | ||
| 115 | + elsewhere += 1; | ||
| 116 | + continue; | ||
| 117 | + } | ||
| 118 | + other => { | ||
| 119 | + report.problem(format!( | ||
| 120 | + "attachment {} is in location {other}; a move did not finish", | ||
| 121 | + row.id | ||
| 122 | + )); | ||
| 123 | + continue; | ||
| 124 | + } | ||
| 125 | + } | ||
| 126 | + let path = match blob_path(data_dir, &row.id) { | ||
| 127 | + Ok(path) => path, | ||
| 128 | + Err(_) => { | ||
| 129 | + report.problem(format!("attachment id {} is not a canonical ULID", row.id)); | ||
| 130 | + continue; | ||
| 131 | + } | ||
| 132 | + }; | ||
| 133 | + match std::fs::symlink_metadata(&path) { | ||
| 134 | + Err(_) => { | ||
| 135 | + report.problem(format!( | ||
| 136 | + "attachment {} has no file at {}", | ||
| 137 | + row.id, | ||
| 138 | + path.display() | ||
| 139 | + )); | ||
| 140 | + continue; | ||
| 141 | + } | ||
| 142 | + Ok(meta) if !meta.file_type().is_file() => { | ||
| 143 | + report.problem(format!("attachment {} is not a regular file", row.id)); | ||
| 144 | + continue; | ||
| 145 | + } | ||
| 146 | + Ok(_) => {} | ||
| 147 | + } | ||
| 148 | + match digest_file(&path) { | ||
| 149 | + Ok((size, _)) if size != row.size => report.problem(format!( | ||
| 150 | + "attachment {} is {size} bytes, the row says {}", | ||
| 151 | + row.id, row.size | ||
| 152 | + )), | ||
| 153 | + Ok((_, digest)) if digest != row.sha256 => { | ||
| 154 | + report.problem(format!("attachment {} fails its sha256", row.id)); | ||
| 155 | + } | ||
| 156 | + Ok(_) => local_ok += 1, | ||
| 157 | + Err(error) => report.problem(format!( | ||
| 158 | + "attachment {} cannot be read: {}", | ||
| 159 | + row.id, | ||
| 160 | + describe(&error) | ||
| 161 | + )), | ||
| 162 | + } | ||
| 163 | + } | ||
| 164 | + report.ok(format!( | ||
| 165 | + "{local_ok} local attachments match their rows; {elsewhere} are held elsewhere and not checked" | ||
| 166 | + )); | ||
| 167 | + | ||
| 168 | + // Files in the attachments directory that no row names. They are reported; nothing is deleted. | ||
| 169 | + match std::fs::read_dir(&attachments_dir) { | ||
| 170 | + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { | ||
| 171 | + if local_ok > 0 { | ||
| 172 | + report.problem("the attachments directory does not exist".to_owned()); | ||
| 173 | + } | ||
| 174 | + } | ||
| 175 | + Err(error) => report.problem(format!("cannot list the attachments directory: {error}")), | ||
| 176 | + Ok(entries) => { | ||
| 177 | + let mut unnamed = 0usize; | ||
| 178 | + for entry in entries { | ||
| 179 | + let Ok(entry) = entry else { | ||
| 180 | + report.problem("cannot read an entry of the attachments directory".to_owned()); | ||
| 181 | + continue; | ||
| 182 | + }; | ||
| 183 | + let name = entry.file_name().to_string_lossy().into_owned(); | ||
| 184 | + if !known.contains(name.as_str()) { | ||
| 185 | + unnamed += 1; | ||
| 186 | + report.problem(format!("file {name} in attachments is named by no row")); | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | + if unnamed == 0 { | ||
| 190 | + report.ok("every file in attachments is named by a row"); | ||
| 191 | + } | ||
| 192 | + } | ||
| 193 | + } | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +#[cfg(test)] | ||
| 197 | +mod tests { | ||
| 198 | + use super::*; | ||
| 199 | + use iz_core::authz::Role; | ||
| 200 | + use iz_core::store::members::DirectoryMember; | ||
| 201 | + | ||
| 202 | + /// An attachment whose bytes were edited after the row was written must be reported. The check runs | ||
| 203 | + /// on a real database file built by the store, in a temp directory. | ||
| 204 | + #[tokio::test] | ||
| 205 | + async fn fsck_reports_an_edited_attachment() { | ||
| 206 | + let root = tempfile::tempdir().expect("temp dir"); | ||
| 207 | + let data = root.path().join("data"); | ||
| 208 | + std::fs::create_dir_all(&data).expect("data dir"); | ||
| 209 | + let db_path = data.join("iz.db"); | ||
| 210 | + let store = iz_core::store::Store::open(&db_path).await.expect("store"); | ||
| 211 | + let (board_id, task_id, member) = seed_task(&store).await; | ||
| 212 | + let id = iz_core::store::new_id(); | ||
| 213 | + let bytes = b"original attachment bytes"; | ||
| 214 | + let sha256 = hex::encode(<sha2::Sha256 as sha2::Digest>::digest(bytes)); | ||
| 215 | + store | ||
| 216 | + .add_attachment( | ||
| 217 | + &board_id, | ||
| 218 | + &task_id, | ||
| 219 | + iz_core::store::attachments::NewAttachment { | ||
| 220 | + id: id.clone(), | ||
| 221 | + name: "note.txt".into(), | ||
| 222 | + mime: "text/plain".into(), | ||
| 223 | + size: bytes.len() as u64, | ||
| 224 | + sha256, | ||
| 225 | + uploaded_by: member, | ||
| 226 | + }, | ||
| 227 | + ) | ||
| 228 | + .await | ||
| 229 | + .expect("row"); | ||
| 230 | + let blob = blob_path(&data, &id).expect("path"); | ||
| 231 | + std::fs::create_dir_all(blob.parent().expect("parent")).expect("attachments dir"); | ||
| 232 | + std::fs::write(&blob, bytes).expect("bytes"); | ||
| 233 | + drop(store); | ||
| 234 | + | ||
| 235 | + let config = Config::parse(&format!( | ||
| 236 | + "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", | ||
| 237 | + db_path.display(), | ||
| 238 | + data.display(), | ||
| 239 | + )) | ||
| 240 | + .expect("config"); | ||
| 241 | + let mut clean = Report::default(); | ||
| 242 | + check( | ||
| 243 | + &config, | ||
| 244 | + &data.canonicalize().expect("canonical"), | ||
| 245 | + &mut clean, | ||
| 246 | + ) | ||
| 247 | + .await; | ||
| 248 | + assert_eq!( | ||
| 249 | + clean.problems, 0, | ||
| 250 | + "untouched data is clean: {:?}", | ||
| 251 | + clean.lines | ||
| 252 | + ); | ||
| 253 | + | ||
| 254 | + std::fs::write(&blob, b"edited attachment bytes!").expect("edit"); | ||
| 255 | + let mut dirty = Report::default(); | ||
| 256 | + check( | ||
| 257 | + &config, | ||
| 258 | + &data.canonicalize().expect("canonical"), | ||
| 259 | + &mut dirty, | ||
| 260 | + ) | ||
| 261 | + .await; | ||
| 262 | + assert!( | ||
| 263 | + dirty.problems > 0, | ||
| 264 | + "the edit is reported: {:?}", | ||
| 265 | + dirty.lines | ||
| 266 | + ); | ||
| 267 | + assert!( | ||
| 268 | + dirty.lines.iter().any(|line| line.contains(&id)), | ||
| 269 | + "the report names the attachment: {:?}", | ||
| 270 | + dirty.lines | ||
| 271 | + ); | ||
| 272 | + } | ||
| 273 | + | ||
| 274 | + /// One board, one task and the member who makes it. Returns (board id, task id, member sub). | ||
| 275 | + async fn seed_task(store: &iz_core::store::Store) -> (String, String, String) { | ||
| 276 | + let board = store.ensure_board("IZ").await.expect("board"); | ||
| 277 | + let member = DirectoryMember { | ||
| 278 | + sub: "ada".into(), | ||
| 279 | + email: "ada@example.com".into(), | ||
| 280 | + name: "Ada".into(), | ||
| 281 | + im_admin: false, | ||
| 282 | + disabled: false, | ||
| 283 | + locale: None, | ||
| 284 | + zoneinfo: "UTC".into(), | ||
| 285 | + picture_version: 0, | ||
| 286 | + }; | ||
| 287 | + store | ||
| 288 | + .apply_directory_member(&member, Role::Admin) | ||
| 289 | + .await | ||
| 290 | + .expect("member"); | ||
| 291 | + let member = member.sub; | ||
| 292 | + let columns = store.columns(&board.id).await.expect("columns"); | ||
| 293 | + let tags = store.tags(&board.id).await.expect("tags"); | ||
| 294 | + let task = store | ||
| 295 | + .create_task( | ||
| 296 | + &board.id, | ||
| 297 | + iz_core::store::tasks::NewTask { | ||
| 298 | + title: "Task".into(), | ||
| 299 | + description: String::new(), | ||
| 300 | + column_id: columns[0].id.clone(), | ||
| 301 | + tag_id: tags[0].id.clone(), | ||
| 302 | + deadline: None, | ||
| 303 | + meeting_at: None, | ||
| 304 | + assignees: Vec::new(), | ||
| 305 | + parent_id: None, | ||
| 306 | + link: None, | ||
| 307 | + }, | ||
| 308 | + &member, | ||
| 309 | + ) | ||
| 310 | + .await | ||
| 311 | + .expect("task"); | ||
| 312 | + (board.id, task.id, member) | ||
| 313 | + } | ||
| 314 | +} | ||
crates/iz-web/src/cli/mod.rsadded+175 -0
| @@ -0,0 +1,175 @@ | |||
| 1 | +//! The operator command line: the words `iz` takes after its options, the lock that keeps two processes off | ||
| 2 | +//! one data directory, and the helpers the commands share. | ||
| 3 | +//! | ||
| 4 | +//! Commands: `iz [--config <path>] [serve]` runs the server (a bare `iz` does the same), `export --out <dir>` | ||
| 5 | +//! writes the board to a new directory, `restore --from <set dir>` replaces the database and attachments | ||
| 6 | +//! with a verified backup set, and `fsck` checks the database and attachments without changing them. The | ||
| 7 | +//! configuration file is the `--config` path, then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is | ||
| 8 | +//! success, 1 a failure, 2 a usage error. | ||
| 9 | +//! | ||
| 10 | +//! The lock: every command that touches the data directory takes an exclusive lock on `iz.lock` inside it, | ||
| 11 | +//! held for the life of the process. A second process that finds the lock taken stops at once. What it is | ||
| 12 | +//! not: the lock does not protect the files from other users; the data directory is mode 0700 for that. | ||
| 13 | + | ||
| 14 | +pub mod export; | ||
| 15 | +pub mod fsck; | ||
| 16 | +pub mod restore; | ||
| 17 | + | ||
| 18 | +use std::fs::{File, OpenOptions, TryLockError}; | ||
| 19 | +use std::os::unix::fs::OpenOptionsExt; | ||
| 20 | +use std::path::{Path, PathBuf}; | ||
| 21 | +use std::process::ExitCode; | ||
| 22 | + | ||
| 23 | +use clap::{Parser, Subcommand}; | ||
| 24 | +use iz_core::config::Config; | ||
| 25 | + | ||
| 26 | +/// The file inside the data directory that carries the process lock. | ||
| 27 | +pub const LOCK_FILE: &str = "iz.lock"; | ||
| 28 | + | ||
| 29 | +/// The line printed when another process holds the lock. Operators search for it, so it is fixed. | ||
| 30 | +pub const BUSY_MESSAGE: &str = "iz is already running on this data directory; stop it (systemctl stop iz) before running this command"; | ||
| 31 | + | ||
| 32 | +/// The configuration file when neither `--config` nor `IZ_CONFIG` names one. | ||
| 33 | +pub const DEFAULT_CONFIG: &str = "config/iz.toml"; | ||
| 34 | + | ||
| 35 | +/// The environment variable that names the configuration file. | ||
| 36 | +pub const CONFIG_ENV: &str = "IZ_CONFIG"; | ||
| 37 | + | ||
| 38 | +/// The parsed command line. `--config` is global, so it works before or after the command word. | ||
| 39 | +#[derive(Debug, Parser)] | ||
| 40 | +#[command( | ||
| 41 | + name = "iz", | ||
| 42 | + about = "The iz task board: the server and its operator commands" | ||
| 43 | +)] | ||
| 44 | +pub struct Cli { | ||
| 45 | + /// The configuration file. Without it, `IZ_CONFIG`, then `config/iz.toml`. | ||
| 46 | + #[arg(long, global = true, value_name = "PATH")] | ||
| 47 | + pub config: Option<PathBuf>, | ||
| 48 | + /// What to do. Without a command the server runs. | ||
| 49 | + #[command(subcommand)] | ||
| 50 | + pub command: Option<Command>, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// The commands. `Serve` is the default. | ||
| 54 | +#[derive(Debug, Subcommand)] | ||
| 55 | +pub enum Command { | ||
| 56 | + /// Runs the server until SIGTERM or Ctrl-C. | ||
| 57 | + Serve, | ||
| 58 | + /// Writes the board, its attachments and a manifest into a new directory. | ||
| 59 | + Export { | ||
| 60 | + /// The directory to create. It must not exist or must be empty. | ||
| 61 | + #[arg(long, value_name = "DIR")] | ||
| 62 | + out: PathBuf, | ||
| 63 | + }, | ||
| 64 | + /// Replaces the database and attachments with a verified backup set. The previous files are kept. | ||
| 65 | + Restore { | ||
| 66 | + /// The backup set directory: `manifest.json` and the files it lists. | ||
| 67 | + #[arg(long, value_name = "DIR")] | ||
| 68 | + from: PathBuf, | ||
| 69 | + }, | ||
| 70 | + /// Checks the database and the attachments without changing anything. | ||
| 71 | + Fsck, | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// The configuration path: the flag, else `IZ_CONFIG`, else the default. | ||
| 75 | +pub fn config_path(flag: Option<PathBuf>) -> PathBuf { | ||
| 76 | + flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from)) | ||
| 77 | + .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG)) | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/// Takes the exclusive lock on `data_dir/iz.lock`. The returned file holds the lock until it is dropped, | ||
| 81 | +/// so bind it to a variable that lives as long as the work does. A busy lock gives [`BUSY_MESSAGE`]; any | ||
| 82 | +/// other failure names the lock file. | ||
| 83 | +pub fn lock_data_dir(data_dir: &Path) -> Result<File, String> { | ||
| 84 | + let path = data_dir.join(LOCK_FILE); | ||
| 85 | + // Mode 0600: only this user reads the lock file. `truncate(false)` keeps whatever the file holds. | ||
| 86 | + let file = OpenOptions::new() | ||
| 87 | + .read(true) | ||
| 88 | + .write(true) | ||
| 89 | + .create(true) | ||
| 90 | + .truncate(false) | ||
| 91 | + .mode(0o600) | ||
| 92 | + .open(&path) | ||
| 93 | + .map_err(|error| format!("iz: cannot open the lock file {}: {error}", path.display()))?; | ||
| 94 | + match file.try_lock() { | ||
| 95 | + Ok(()) => Ok(file), | ||
| 96 | + Err(TryLockError::WouldBlock) => Err(BUSY_MESSAGE.to_owned()), | ||
| 97 | + Err(TryLockError::Error(error)) => { | ||
| 98 | + Err(format!("iz: cannot lock {}: {error}", path.display())) | ||
| 99 | + } | ||
| 100 | + } | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// Prints the failure of [`lock_data_dir`] and gives the exit status 1. | ||
| 104 | +pub fn take_lock(data_dir: &Path) -> Result<File, ExitCode> { | ||
| 105 | + lock_data_dir(data_dir).map_err(|message| { | ||
| 106 | + eprintln!("{message}"); | ||
| 107 | + ExitCode::FAILURE | ||
| 108 | + }) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// Prints `iz: <message>` to stderr and gives the exit status 1. | ||
| 112 | +pub fn fail(message: impl std::fmt::Display) -> ExitCode { | ||
| 113 | + eprintln!("iz: {message}"); | ||
| 114 | + ExitCode::FAILURE | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +/// The text of an iz-core error for the user. A refused set or an invalid value is shown as its text | ||
| 118 | +/// alone; everything else keeps its prefix. | ||
| 119 | +pub fn describe(error: &iz_core::Error) -> String { | ||
| 120 | + match error { | ||
| 121 | + iz_core::Error::Invalid(text) | iz_core::Error::Conflict(text) => text.clone(), | ||
| 122 | + other => other.to_string(), | ||
| 123 | + } | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// The data directory as an absolute path. It must exist: the commands that call this never create it. | ||
| 127 | +pub fn existing_data_dir(config: &Config) -> Result<PathBuf, String> { | ||
| 128 | + config.data_dir.canonicalize().map_err(|error| { | ||
| 129 | + format!( | ||
| 130 | + "the data directory {} cannot be used: {error}", | ||
| 131 | + config.data_dir.display() | ||
| 132 | + ) | ||
| 133 | + }) | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// The database path, checked to be a regular file that is not a link. Nothing is created. | ||
| 137 | +pub fn database_file(config: &Config) -> Result<PathBuf, String> { | ||
| 138 | + let meta = std::fs::symlink_metadata(&config.database).map_err(|error| { | ||
| 139 | + format!( | ||
| 140 | + "the database {} cannot be read: {error}", | ||
| 141 | + config.database.display() | ||
| 142 | + ) | ||
| 143 | + })?; | ||
| 144 | + if !meta.file_type().is_file() { | ||
| 145 | + return Err(format!( | ||
| 146 | + "the database {} is not a regular file", | ||
| 147 | + config.database.display() | ||
| 148 | + )); | ||
| 149 | + } | ||
| 150 | + Ok(config.database.clone()) | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +/// A UTC stamp that is safe in a file name: `20261028T093015Z`. | ||
| 154 | +pub fn file_stamp() -> String { | ||
| 155 | + jiff::Timestamp::now() | ||
| 156 | + .strftime("%Y%m%dT%H%M%SZ") | ||
| 157 | + .to_string() | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +#[cfg(test)] | ||
| 161 | +mod tests { | ||
| 162 | + use super::*; | ||
| 163 | + | ||
| 164 | + #[test] | ||
| 165 | + fn a_held_lock_is_refused_and_released_on_drop() { | ||
| 166 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 167 | + let first = lock_data_dir(dir.path()).expect("first lock"); | ||
| 168 | + assert_eq!( | ||
| 169 | + lock_data_dir(dir.path()).err().as_deref(), | ||
| 170 | + Some(BUSY_MESSAGE) | ||
| 171 | + ); | ||
| 172 | + drop(first); | ||
| 173 | + lock_data_dir(dir.path()).expect("lock after release"); | ||
| 174 | + } | ||
| 175 | +} | ||
crates/iz-web/src/cli/restore.rsadded+457 -0
| @@ -0,0 +1,457 @@ | |||
| 1 | +//! `iz restore --from <set dir>`: replaces the database and the attachments with a verified backup set. | ||
| 2 | +//! | ||
| 3 | +//! Order: verify the set with `manifest::verify_set`; check that the configured database is a regular file | ||
| 4 | +//! inside the data directory; copy the set's `iz.db` and attachments into a staging directory inside the data | ||
| 5 | +//! directory and check each copy against the manifest; run `integrity_check` and the migration check on the | ||
| 6 | +//! staged database. Nothing outside the staging directory changes until then. Only after that are the current | ||
| 7 | +//! `iz.db`, `iz.db-wal`, `iz.db-shm` and `attachments` moved aside under a UTC stamp (kept, never deleted) and | ||
| 8 | +//! the staged files moved into place. If a move fails, the moves made so far are undone. | ||
| 9 | +//! | ||
| 10 | +//! Every path is joined from the data directory and fixed names; the only names taken from the set are the | ||
| 11 | +//! ones `verify_set` checked, and they are used only after they parse as canonical ULIDs. | ||
| 12 | + | ||
| 13 | +use std::fs::{DirBuilder, Permissions}; | ||
| 14 | +use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; | ||
| 15 | +use std::path::{Path, PathBuf}; | ||
| 16 | +use std::process::ExitCode; | ||
| 17 | + | ||
| 18 | +use iz_core::config::Config; | ||
| 19 | +use iz_core::manifest::{self, Manifest}; | ||
| 20 | +use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; | ||
| 21 | +use iz_core::store::export::{ReadOnly, migrations_problem}; | ||
| 22 | +use iz_core::store::new_id; | ||
| 23 | + | ||
| 24 | +use super::{describe, existing_data_dir, fail, file_stamp, take_lock}; | ||
| 25 | + | ||
| 26 | +/// The database file name inside a backup set. Fixed: the set writer uses this name too. | ||
| 27 | +const SET_DB: &str = "iz.db"; | ||
| 28 | +/// The directory name prefix of the staging directory inside the data directory. | ||
| 29 | +const STAGING_PREFIX: &str = "restore-staging-"; | ||
| 30 | + | ||
| 31 | +/// Runs the restore and maps its outcome to an exit status. | ||
| 32 | +pub async fn run(config_path: &Path, from: &Path) -> ExitCode { | ||
| 33 | + let config = match Config::load(config_path) { | ||
| 34 | + Ok(config) => config, | ||
| 35 | + Err(error) => return fail(describe(&error)), | ||
| 36 | + }; | ||
| 37 | + if let Err(error) = std::fs::create_dir_all(&config.data_dir) | ||
| 38 | + .and_then(|()| std::fs::set_permissions(&config.data_dir, Permissions::from_mode(0o700))) | ||
| 39 | + { | ||
| 40 | + return fail(format!( | ||
| 41 | + "the data directory {} cannot be created: {error}", | ||
| 42 | + config.data_dir.display() | ||
| 43 | + )); | ||
| 44 | + } | ||
| 45 | + let data_dir = match existing_data_dir(&config) { | ||
| 46 | + Ok(dir) => dir, | ||
| 47 | + Err(message) => return fail(message), | ||
| 48 | + }; | ||
| 49 | + let _lock = match take_lock(&data_dir) { | ||
| 50 | + Ok(lock) => lock, | ||
| 51 | + Err(code) => return code, | ||
| 52 | + }; | ||
| 53 | + match restore(&config, &data_dir, from).await { | ||
| 54 | + Ok(summary) => { | ||
| 55 | + println!("{summary}"); | ||
| 56 | + ExitCode::SUCCESS | ||
| 57 | + } | ||
| 58 | + Err(message) => fail(message), | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// A canonical ULID name from a set. `None` for anything else, so a name is used only when it is the | ||
| 63 | +/// exact text the store would have written. | ||
| 64 | +fn canonical_id(name: &str) -> Option<String> { | ||
| 65 | + // `blob_path` accepts exactly the canonical ULID text, so it is the one check for ids. | ||
| 66 | + blob_path(Path::new("."), name) | ||
| 67 | + .ok() | ||
| 68 | + .map(|_| name.to_owned()) | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// The files a restore takes from a set: `iz.db`, and `attachments/<id>` for each canonical id. Any other | ||
| 72 | +/// listed file is refused, so a set cannot smuggle a file into the data directory. | ||
| 73 | +fn plan_set(manifest: &Manifest) -> Result<Vec<String>, String> { | ||
| 74 | + let mut attachments = Vec::new(); | ||
| 75 | + let mut has_db = false; | ||
| 76 | + for file in &manifest.files { | ||
| 77 | + if file.path == SET_DB { | ||
| 78 | + has_db = true; | ||
| 79 | + } else if let Some(id) = file | ||
| 80 | + .path | ||
| 81 | + .strip_prefix("attachments/") | ||
| 82 | + .and_then(canonical_id) | ||
| 83 | + { | ||
| 84 | + attachments.push(id); | ||
| 85 | + } else { | ||
| 86 | + return Err(format!("the set lists an unexpected file: {}", file.path)); | ||
| 87 | + } | ||
| 88 | + } | ||
| 89 | + if !has_db { | ||
| 90 | + return Err(format!("the set has no {SET_DB}")); | ||
| 91 | + } | ||
| 92 | + Ok(attachments) | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// The database path, joined from the canonical parent directory and the file name. Refused unless it is | ||
| 96 | +/// inside the data directory and is not a link, so the restore cannot replace a file outside it. | ||
| 97 | +fn database_target(config: &Config, data_dir: &Path) -> Result<PathBuf, String> { | ||
| 98 | + let name = config.database.file_name().ok_or_else(|| { | ||
| 99 | + format!( | ||
| 100 | + "the database path has no file name: {}", | ||
| 101 | + config.database.display() | ||
| 102 | + ) | ||
| 103 | + })?; | ||
| 104 | + let parent = config | ||
| 105 | + .database | ||
| 106 | + .parent() | ||
| 107 | + .filter(|p| !p.as_os_str().is_empty()) | ||
| 108 | + .unwrap_or_else(|| Path::new(".")); | ||
| 109 | + let parent = parent.canonicalize().map_err(|error| { | ||
| 110 | + format!( | ||
| 111 | + "the database directory {} cannot be used: {error}", | ||
| 112 | + parent.display() | ||
| 113 | + ) | ||
| 114 | + })?; | ||
| 115 | + if !parent.starts_with(data_dir) { | ||
| 116 | + return Err(format!( | ||
| 117 | + "the database {} is outside the data directory; restore refuses to replace it", | ||
| 118 | + config.database.display() | ||
| 119 | + )); | ||
| 120 | + } | ||
| 121 | + let target = parent.join(name); | ||
| 122 | + if let Ok(meta) = std::fs::symlink_metadata(&target) | ||
| 123 | + && !meta.file_type().is_file() | ||
| 124 | + { | ||
| 125 | + return Err(format!( | ||
| 126 | + "the database {} is not a regular file", | ||
| 127 | + target.display() | ||
| 128 | + )); | ||
| 129 | + } | ||
| 130 | + Ok(target) | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// Copies `source` to `dest` (created new, mode 0600), then checks the copy against the manifest entry | ||
| 134 | +/// for `relative` so a set changed during the copy is refused. | ||
| 135 | +fn copy_checked( | ||
| 136 | + manifest: &Manifest, | ||
| 137 | + relative: &str, | ||
| 138 | + source: &Path, | ||
| 139 | + dest: &Path, | ||
| 140 | +) -> Result<(), String> { | ||
| 141 | + let expected = manifest | ||
| 142 | + .files | ||
| 143 | + .iter() | ||
| 144 | + .find(|file| file.path == relative) | ||
| 145 | + .ok_or_else(|| format!("the set does not list {relative}"))?; | ||
| 146 | + std::fs::copy(source, dest).map_err(|error| format!("cannot copy {relative}: {error}"))?; | ||
| 147 | + std::fs::set_permissions(dest, Permissions::from_mode(0o600)) | ||
| 148 | + .map_err(|error| format!("cannot set the mode of {}: {error}", dest.display()))?; | ||
| 149 | + let (size, digest) = manifest::digest_file(dest) | ||
| 150 | + .map_err(|error| format!("cannot read the copy of {relative}: {}", describe(&error)))?; | ||
| 151 | + if size != expected.size || digest != expected.sha256 { | ||
| 152 | + return Err(format!("the set changed while it was copied: {relative}")); | ||
| 153 | + } | ||
| 154 | + Ok(()) | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/// The staging directory and what it holds, so a failure can remove exactly what was made. | ||
| 158 | +struct Staging { | ||
| 159 | + dir: PathBuf, | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +impl Staging { | ||
| 163 | + /// Makes a new staging directory with a fresh name inside the data directory, mode 0700. | ||
| 164 | + fn create(data_dir: &Path) -> Result<Staging, String> { | ||
| 165 | + let dir = data_dir.join(format!("{STAGING_PREFIX}{}", new_id())); | ||
| 166 | + DirBuilder::new() | ||
| 167 | + .mode(0o700) | ||
| 168 | + .create(&dir) | ||
| 169 | + .map_err(|error| format!("cannot create {}: {error}", dir.display()))?; | ||
| 170 | + Ok(Staging { dir }) | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + /// Removes the files a restore puts in the staging directory, then the directory. It removes only | ||
| 174 | + /// regular files directly inside it and inside its `attachments` directory, and leaves anything else | ||
| 175 | + /// in place. | ||
| 176 | + fn discard(&self) { | ||
| 177 | + let _ = remove_regular_files(&self.dir); | ||
| 178 | + let attachments = self.dir.join(ATTACHMENTS_DIR); | ||
| 179 | + let _ = remove_regular_files(&attachments); | ||
| 180 | + let _ = std::fs::remove_dir(&attachments); | ||
| 181 | + let _ = std::fs::remove_dir(&self.dir); | ||
| 182 | + } | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +/// Removes every regular file directly inside `dir`. Links and directories are not touched. | ||
| 186 | +fn remove_regular_files(dir: &Path) -> std::io::Result<()> { | ||
| 187 | + for entry in std::fs::read_dir(dir)? { | ||
| 188 | + let entry = entry?; | ||
| 189 | + if entry.file_type()?.is_file() { | ||
| 190 | + std::fs::remove_file(entry.path())?; | ||
| 191 | + } | ||
| 192 | + } | ||
| 193 | + Ok(()) | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +/// Checks the staged database: `integrity_check` says `ok` and the migrations are contiguous. Its sidecars | ||
| 197 | +/// are removed when empty; a sidecar with bytes is refused. | ||
| 198 | +async fn check_staged(staged_db: &Path) -> Result<(), String> { | ||
| 199 | + { | ||
| 200 | + let db = ReadOnly::open(staged_db) | ||
| 201 | + .await | ||
| 202 | + .map_err(|error| describe(&error))?; | ||
| 203 | + let rows = db | ||
| 204 | + .integrity_check() | ||
| 205 | + .await | ||
| 206 | + .map_err(|error| describe(&error))?; | ||
| 207 | + if rows != ["ok"] { | ||
| 208 | + return Err(format!( | ||
| 209 | + "the set's database fails integrity_check: {}", | ||
| 210 | + rows.join("; ") | ||
| 211 | + )); | ||
| 212 | + } | ||
| 213 | + let versions = db | ||
| 214 | + .migration_versions() | ||
| 215 | + .await | ||
| 216 | + .map_err(|error| describe(&error))?; | ||
| 217 | + if let Some(problem) = migrations_problem(&versions) { | ||
| 218 | + return Err(format!("the set's database is refused: {problem}")); | ||
| 219 | + } | ||
| 220 | + } | ||
| 221 | + for suffix in ["-wal", "-shm"] { | ||
| 222 | + let mut sidecar = staged_db.as_os_str().to_owned(); | ||
| 223 | + sidecar.push(suffix); | ||
| 224 | + let sidecar = PathBuf::from(sidecar); | ||
| 225 | + match std::fs::symlink_metadata(&sidecar) { | ||
| 226 | + Err(_) => {} | ||
| 227 | + Ok(meta) if meta.len() == 0 => { | ||
| 228 | + std::fs::remove_file(&sidecar) | ||
| 229 | + .map_err(|error| format!("cannot remove {}: {error}", sidecar.display()))?; | ||
| 230 | + } | ||
| 231 | + Ok(meta) => { | ||
| 232 | + return Err(format!( | ||
| 233 | + "the staged database has {} bytes in {}", | ||
| 234 | + meta.len(), | ||
| 235 | + sidecar.display() | ||
| 236 | + )); | ||
| 237 | + } | ||
| 238 | + } | ||
| 239 | + } | ||
| 240 | + Ok(()) | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +/// The whole restore. Returns the summary line on success. | ||
| 244 | +async fn restore(config: &Config, data_dir: &Path, from: &Path) -> Result<String, String> { | ||
| 245 | + let manifest = manifest::verify_set(from).map_err(|error| describe(&error))?; | ||
| 246 | + let attachment_ids = plan_set(&manifest)?; | ||
| 247 | + let db_target = database_target(config, data_dir)?; | ||
| 248 | + let attachments_dir = data_dir.join(ATTACHMENTS_DIR); | ||
| 249 | + if let Ok(meta) = std::fs::symlink_metadata(&attachments_dir) | ||
| 250 | + && !meta.file_type().is_dir() | ||
| 251 | + { | ||
| 252 | + return Err(format!("{} is not a directory", attachments_dir.display())); | ||
| 253 | + } | ||
| 254 | + | ||
| 255 | + // Stage and check everything first. A failure here removes the staging directory and changes nothing else. | ||
| 256 | + let staging = Staging::create(data_dir)?; | ||
| 257 | + let staged = stage(&staging, from, &manifest, &attachment_ids).await; | ||
| 258 | + if let Err(message) = staged { | ||
| 259 | + staging.discard(); | ||
| 260 | + return Err(message); | ||
| 261 | + } | ||
| 262 | + | ||
| 263 | + let stamp = file_stamp(); | ||
| 264 | + let result = swap_into_place(&staging.dir, &db_target, data_dir, &stamp); | ||
| 265 | + match result { | ||
| 266 | + Ok(moved) => { | ||
| 267 | + if let Err(error) = std::fs::remove_dir(&staging.dir) { | ||
| 268 | + eprintln!( | ||
| 269 | + "iz: the staging directory {} could not be removed: {error}", | ||
| 270 | + staging.dir.display() | ||
| 271 | + ); | ||
| 272 | + } | ||
| 273 | + Ok(format!( | ||
| 274 | + "restored from {}: {} attachments; previous files kept as {}", | ||
| 275 | + from.display(), | ||
| 276 | + attachment_ids.len(), | ||
| 277 | + moved.join(", ") | ||
| 278 | + )) | ||
| 279 | + } | ||
| 280 | + Err(message) => { | ||
| 281 | + staging.discard(); | ||
| 282 | + Err(message) | ||
| 283 | + } | ||
| 284 | + } | ||
| 285 | +} | ||
| 286 | + | ||
| 287 | +/// Copies the set's files into the staging directory and checks them. The staging directory always gets | ||
| 288 | +/// an `attachments` directory, even when the set has none, so the swap is the same in both cases. | ||
| 289 | +async fn stage( | ||
| 290 | + staging: &Staging, | ||
| 291 | + from: &Path, | ||
| 292 | + manifest: &Manifest, | ||
| 293 | + attachment_ids: &[String], | ||
| 294 | +) -> Result<(), String> { | ||
| 295 | + let staged_db = staging.dir.join(SET_DB); | ||
| 296 | + copy_checked(manifest, SET_DB, &from.join(SET_DB), &staged_db)?; | ||
| 297 | + let staged_attachments = staging.dir.join(ATTACHMENTS_DIR); | ||
| 298 | + DirBuilder::new() | ||
| 299 | + .mode(0o700) | ||
| 300 | + .create(&staged_attachments) | ||
| 301 | + .map_err(|error| format!("cannot create {}: {error}", staged_attachments.display()))?; | ||
| 302 | + for id in attachment_ids { | ||
| 303 | + let relative = format!("{ATTACHMENTS_DIR}/{id}"); | ||
| 304 | + copy_checked( | ||
| 305 | + manifest, | ||
| 306 | + &relative, | ||
| 307 | + &from.join(ATTACHMENTS_DIR).join(id), | ||
| 308 | + &staged_attachments.join(id), | ||
| 309 | + )?; | ||
| 310 | + } | ||
| 311 | + check_staged(&staged_db).await | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +/// One move made by the swap, so it can be undone. | ||
| 315 | +enum Move { | ||
| 316 | + /// An existing file or directory moved aside, from, to. | ||
| 317 | + Aside(PathBuf, PathBuf), | ||
| 318 | + /// A staged file moved into place, from, to. | ||
| 319 | + Placed(PathBuf, PathBuf), | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +/// Moves the current database files and attachments aside, then the staged ones into place. Returns the | ||
| 323 | +/// names the old files were kept under. If any move fails, the moves made so far are reversed. | ||
| 324 | +fn swap_into_place( | ||
| 325 | + staging: &Path, | ||
| 326 | + db_target: &Path, | ||
| 327 | + data_dir: &Path, | ||
| 328 | + stamp: &str, | ||
| 329 | +) -> Result<Vec<String>, String> { | ||
| 330 | + let attachments = data_dir.join(ATTACHMENTS_DIR); | ||
| 331 | + let mut old: Vec<(PathBuf, PathBuf)> = Vec::new(); | ||
| 332 | + for current in [ | ||
| 333 | + db_target.to_path_buf(), | ||
| 334 | + with_suffix(db_target, "-wal"), | ||
| 335 | + with_suffix(db_target, "-shm"), | ||
| 336 | + attachments.clone(), | ||
| 337 | + ] { | ||
| 338 | + if std::fs::symlink_metadata(¤t).is_ok() { | ||
| 339 | + let aside = with_suffix(¤t, &format!(".{stamp}")); | ||
| 340 | + if std::fs::symlink_metadata(&aside).is_ok() { | ||
| 341 | + return Err(format!( | ||
| 342 | + "{} already exists; nothing was changed", | ||
| 343 | + aside.display() | ||
| 344 | + )); | ||
| 345 | + } | ||
| 346 | + old.push((current, aside)); | ||
| 347 | + } | ||
| 348 | + } | ||
| 349 | + let staged_db = staging.join(SET_DB); | ||
| 350 | + let staged_attachments = staging.join(ATTACHMENTS_DIR); | ||
| 351 | + | ||
| 352 | + let mut done: Vec<Move> = Vec::new(); | ||
| 353 | + let outcome = (|| -> std::io::Result<()> { | ||
| 354 | + for (current, aside) in &old { | ||
| 355 | + std::fs::rename(current, aside)?; | ||
| 356 | + done.push(Move::Aside(current.clone(), aside.clone())); | ||
| 357 | + } | ||
| 358 | + std::fs::rename(&staged_db, db_target)?; | ||
| 359 | + done.push(Move::Placed(staged_db.clone(), db_target.to_path_buf())); | ||
| 360 | + std::fs::rename(&staged_attachments, &attachments)?; | ||
| 361 | + done.push(Move::Placed( | ||
| 362 | + staged_attachments.clone(), | ||
| 363 | + attachments.clone(), | ||
| 364 | + )); | ||
| 365 | + std::fs::File::open(data_dir)?.sync_all() | ||
| 366 | + })(); | ||
| 367 | + | ||
| 368 | + match outcome { | ||
| 369 | + Ok(()) => Ok(old | ||
| 370 | + .iter() | ||
| 371 | + .map(|(_, aside)| aside.display().to_string()) | ||
| 372 | + .collect()), | ||
| 373 | + Err(error) => { | ||
| 374 | + // Undo in reverse. A failure to undo is reported with the paths, so the operator can finish by hand. | ||
| 375 | + let mut stuck = Vec::new(); | ||
| 376 | + for step in done.into_iter().rev() { | ||
| 377 | + // An aside file goes back to its original name; a placed file goes back to staging. | ||
| 378 | + let undone = match &step { | ||
| 379 | + Move::Aside(original, aside) => std::fs::rename(aside, original), | ||
| 380 | + Move::Placed(staged, target) => std::fs::rename(target, staged), | ||
| 381 | + }; | ||
| 382 | + if let Err(undo_error) = undone { | ||
| 383 | + stuck.push(undo_error.to_string()); | ||
| 384 | + } | ||
| 385 | + } | ||
| 386 | + if stuck.is_empty() { | ||
| 387 | + Err(format!("restore failed and was undone: {error}")) | ||
| 388 | + } else { | ||
| 389 | + Err(format!( | ||
| 390 | + "restore failed: {error}; some moves could not be undone: {}", | ||
| 391 | + stuck.join("; ") | ||
| 392 | + )) | ||
| 393 | + } | ||
| 394 | + } | ||
| 395 | + } | ||
| 396 | +} | ||
| 397 | + | ||
| 398 | +/// `path` with `suffix` appended to its file name. | ||
| 399 | +fn with_suffix(path: &Path, suffix: &str) -> PathBuf { | ||
| 400 | + let mut text = path.as_os_str().to_owned(); | ||
| 401 | + text.push(suffix); | ||
| 402 | + PathBuf::from(text) | ||
| 403 | +} | ||
| 404 | + | ||
| 405 | +#[cfg(test)] | ||
| 406 | +mod tests { | ||
| 407 | + use super::*; | ||
| 408 | + use iz_core::manifest::write_manifest; | ||
| 409 | + | ||
| 410 | + /// A set with a file that a manifest does not list, or whose bytes changed after the manifest was | ||
| 411 | + /// written, must not be restored: nothing in the data directory may change. | ||
| 412 | + #[tokio::test] | ||
| 413 | + async fn restore_refuses_a_tampered_set_and_changes_nothing() { | ||
| 414 | + let root = tempfile::tempdir().expect("temp dir"); | ||
| 415 | + let set = root.path().join("set"); | ||
| 416 | + let data = root.path().join("data"); | ||
| 417 | + std::fs::create_dir_all(&set).expect("set dir"); | ||
| 418 | + std::fs::create_dir_all(&data).expect("data dir"); | ||
| 419 | + let db = data.join("iz.db"); | ||
| 420 | + std::fs::write(&db, b"current database").expect("current db"); | ||
| 421 | + std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db"); | ||
| 422 | + write_manifest( | ||
| 423 | + &set, | ||
| 424 | + "2026-10-28T00:00:00.000000000Z", | ||
| 425 | + "test", | ||
| 426 | + &[SET_DB.to_owned()], | ||
| 427 | + ) | ||
| 428 | + .expect("manifest"); | ||
| 429 | + // Tamper after the manifest is written. | ||
| 430 | + let mut bytes = std::fs::read(set.join(SET_DB)).expect("read"); | ||
| 431 | + bytes[0] ^= 0x01; | ||
| 432 | + std::fs::write(set.join(SET_DB), bytes).expect("tamper"); | ||
| 433 | + | ||
| 434 | + let config = Config::parse(&format!( | ||
| 435 | + "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", | ||
| 436 | + db.display(), | ||
| 437 | + data.display(), | ||
| 438 | + )) | ||
| 439 | + .expect("config"); | ||
| 440 | + let error = restore(&config, &data.canonicalize().expect("canonical"), &set) | ||
| 441 | + .await | ||
| 442 | + .expect_err("tampered set must be refused"); | ||
| 443 | + assert!( | ||
| 444 | + error.contains("changed since the set was written"), | ||
| 445 | + "got: {error}" | ||
| 446 | + ); | ||
| 447 | + assert_eq!( | ||
| 448 | + std::fs::read(&db).expect("db still there"), | ||
| 449 | + b"current database" | ||
| 450 | + ); | ||
| 451 | + let entries: Vec<_> = std::fs::read_dir(&data) | ||
| 452 | + .expect("list") | ||
| 453 | + .map(|e| e.expect("entry").file_name()) | ||
| 454 | + .collect(); | ||
| 455 | + assert_eq!(entries.len(), 1, "only the database remains: {entries:?}"); | ||
| 456 | + } | ||
| 457 | +} | ||
crates/iz-web/src/family.rsadded+257 -0
| @@ -0,0 +1,257 @@ | |||
| 1 | +//! The family switcher list (contracts.md 4): `im`'s service registry, fetched with the service | ||
| 2 | +//! token every five minutes and kept in memory. Pages read the copy through [`FamilyCache`]; they | ||
| 3 | +//! never call `im` themselves. | ||
| 4 | +//! | ||
| 5 | +//! Every entry is checked before it is kept: a key of `[a-z0-9-]`, a name, and a URL that is `http` | ||
| 6 | +//! or `https` only. Entries that fail are dropped one by one, so one bad row never hides the others. | ||
| 7 | +//! A failed refresh keeps the last good list; a stale copy is fine (contracts.md 4). When OIDC is not | ||
| 8 | +//! configured, the worker is not started and the list stays empty. | ||
| 9 | + | ||
| 10 | +use std::sync::RwLock; | ||
| 11 | +use std::time::Duration; | ||
| 12 | + | ||
| 13 | +use reqwest::Url; | ||
| 14 | +use serde_json::Value; | ||
| 15 | +use tokio::sync::watch; | ||
| 16 | + | ||
| 17 | +use crate::oidc::{ImError, ImResult, OidcClient, read_limited}; | ||
| 18 | +use crate::state::AppState; | ||
| 19 | + | ||
| 20 | +/// How often the list is fetched. Reason: contracts.md 4 says apps fetch every five minutes. | ||
| 21 | +const REFRESH: Duration = Duration::from_secs(5 * 60); | ||
| 22 | +/// Largest listing read from `im`, in bytes. Reason: a family has a few dozen services, so a real | ||
| 23 | +/// listing is a few kilobytes; this bounds memory. | ||
| 24 | +const LISTING_MAX_BYTES: usize = 64 * 1024; | ||
| 25 | +/// Most services kept for the switcher. Reason: a bar with more links than this is not usable. | ||
| 26 | +pub const MAX_SERVICES: usize = 20; | ||
| 27 | +/// Longest service key, in characters. Reason: keys are short words such as `im` or `in`. | ||
| 28 | +const KEY_MAX_CHARS: usize = 32; | ||
| 29 | +/// Longest service name, in characters. Reason: the name is a link label in a narrow bar. | ||
| 30 | +const NAME_MAX_CHARS: usize = 60; | ||
| 31 | + | ||
| 32 | +/// One service of the family, as the switcher shows it. | ||
| 33 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 34 | +pub struct Service { | ||
| 35 | + /// The family key, such as `im`. Matched against the key of this app to mark the current one. | ||
| 36 | + pub key: String, | ||
| 37 | + /// The label shown in the switcher. | ||
| 38 | + pub name: String, | ||
| 39 | + /// The absolute `http` or `https` URL of the service. | ||
| 40 | + pub url: String, | ||
| 41 | + /// Whether the last health probe of `im` passed. | ||
| 42 | + pub healthy: bool, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// The last good service list. Shared between the worker, which replaces it, and the pages, which | ||
| 46 | +/// copy it out. | ||
| 47 | +#[derive(Debug, Default)] | ||
| 48 | +pub struct FamilyCache { | ||
| 49 | + services: RwLock<Vec<Service>>, | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +impl FamilyCache { | ||
| 53 | + /// A copy of the list as it stands. Empty until the first successful fetch. | ||
| 54 | + pub fn snapshot(&self) -> Vec<Service> { | ||
| 55 | + self.services | ||
| 56 | + .read() | ||
| 57 | + .unwrap_or_else(|poisoned| poisoned.into_inner()) | ||
| 58 | + .clone() | ||
| 59 | + } | ||
| 60 | + | ||
| 61 | + /// Replaces the list. Only the worker calls this. | ||
| 62 | + fn replace(&self, services: Vec<Service>) { | ||
| 63 | + *self | ||
| 64 | + .services | ||
| 65 | + .write() | ||
| 66 | + .unwrap_or_else(|poisoned| poisoned.into_inner()) = services; | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// The listing of `im` (contracts.md 4). Entries stay raw values so that one bad entry does not | ||
| 71 | +/// stop the rest. | ||
| 72 | +#[derive(serde::Deserialize)] | ||
| 73 | +struct Listing { | ||
| 74 | + services: Vec<Value>, | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +/// One entry as `im` sends it. Unknown fields are ignored. | ||
| 78 | +#[derive(serde::Deserialize)] | ||
| 79 | +struct WireService { | ||
| 80 | + key: String, | ||
| 81 | + name: String, | ||
| 82 | + url: String, | ||
| 83 | + #[serde(default)] | ||
| 84 | + healthy: bool, | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// Starts the worker. It fetches at once and then every [`REFRESH`], until the stop flag is set. | ||
| 88 | +/// Does nothing when OIDC is not configured. | ||
| 89 | +pub fn spawn(state: AppState, stop: watch::Receiver<bool>) { | ||
| 90 | + let Some(oidc) = state.oidc.clone() else { | ||
| 91 | + return; | ||
| 92 | + }; | ||
| 93 | + tokio::spawn(run(state, oidc, stop)); | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +async fn run(state: AppState, oidc: std::sync::Arc<OidcClient>, mut stop: watch::Receiver<bool>) { | ||
| 97 | + loop { | ||
| 98 | + match fetch(&oidc).await { | ||
| 99 | + Ok(services) => { | ||
| 100 | + tracing::debug!( | ||
| 101 | + count = services.len(), | ||
| 102 | + "family: the service list was refreshed" | ||
| 103 | + ); | ||
| 104 | + state.family.replace(services); | ||
| 105 | + } | ||
| 106 | + Err(error) => { | ||
| 107 | + tracing::warn!(error = %error, "family: the service list could not be refreshed; keeping the last one"); | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + if wait_or_stop(REFRESH, &mut stop).await { | ||
| 111 | + return; | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +/// One fetch of the listing with the service token. | ||
| 117 | +async fn fetch(oidc: &OidcClient) -> ImResult<Vec<Service>> { | ||
| 118 | + let token = oidc.service_token().await?; | ||
| 119 | + let url = format!("{}/api/v1/family", oidc.issuer()); | ||
| 120 | + let response = oidc | ||
| 121 | + .http() | ||
| 122 | + .get(url) | ||
| 123 | + .bearer_auth(token) | ||
| 124 | + .send() | ||
| 125 | + .await | ||
| 126 | + .map_err(|e| ImError::Unavailable(e.to_string()))?; | ||
| 127 | + if !response.status().is_success() { | ||
| 128 | + return Err(ImError::BadResponse(format!( | ||
| 129 | + "the family list answered {}", | ||
| 130 | + response.status().as_u16() | ||
| 131 | + ))); | ||
| 132 | + } | ||
| 133 | + let body = read_limited(response, LISTING_MAX_BYTES).await?; | ||
| 134 | + parse_listing(&body).map_err(ImError::BadResponse) | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// Reads a listing and keeps the entries that pass [`check_entry`], at most [`MAX_SERVICES`] of them. | ||
| 138 | +/// Entries past the limit are dropped. | ||
| 139 | +pub fn parse_listing(body: &[u8]) -> Result<Vec<Service>, String> { | ||
| 140 | + let listing: Listing = | ||
| 141 | + serde_json::from_slice(body).map_err(|e| format!("the family list: {e}"))?; | ||
| 142 | + Ok(listing | ||
| 143 | + .services | ||
| 144 | + .into_iter() | ||
| 145 | + .filter_map(check_entry) | ||
| 146 | + .take(MAX_SERVICES) | ||
| 147 | + .collect()) | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +/// Turns one raw entry into a [`Service`], or `None` when it does not parse or fails a check. | ||
| 151 | +fn check_entry(raw: Value) -> Option<Service> { | ||
| 152 | + let wire: WireService = serde_json::from_value(raw).ok()?; | ||
| 153 | + if !valid_key(&wire.key) || !valid_name(&wire.name) { | ||
| 154 | + return None; | ||
| 155 | + } | ||
| 156 | + let url = Url::parse(&wire.url).ok()?; | ||
| 157 | + if !matches!(url.scheme(), "http" | "https") { | ||
| 158 | + return None; | ||
| 159 | + } | ||
| 160 | + Some(Service { | ||
| 161 | + key: wire.key, | ||
| 162 | + name: wire.name, | ||
| 163 | + url: url.into(), | ||
| 164 | + healthy: wire.healthy, | ||
| 165 | + }) | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +/// A key is 1 to 32 characters of lowercase letters, digits and hyphens. | ||
| 169 | +fn valid_key(key: &str) -> bool { | ||
| 170 | + let length = key.chars().count(); | ||
| 171 | + (1..=KEY_MAX_CHARS).contains(&length) | ||
| 172 | + && key | ||
| 173 | + .chars() | ||
| 174 | + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +/// A name is 1 to 60 characters. | ||
| 178 | +fn valid_name(name: &str) -> bool { | ||
| 179 | + (1..=NAME_MAX_CHARS).contains(&name.chars().count()) | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// Waits for `wait`, or returns `true` early when the stop flag is set. | ||
| 183 | +async fn wait_or_stop(wait: Duration, stop: &mut watch::Receiver<bool>) -> bool { | ||
| 184 | + tokio::select! { | ||
| 185 | + _ = stop.wait_for(|stopped| *stopped) => true, | ||
| 186 | + () = tokio::time::sleep(wait) => false, | ||
| 187 | + } | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +#[cfg(test)] | ||
| 191 | +mod tests { | ||
| 192 | + use super::*; | ||
| 193 | + | ||
| 194 | + #[test] | ||
| 195 | + fn the_parser_drops_bad_entries_and_keeps_the_rest() { | ||
| 196 | + let long_key = "k".repeat(KEY_MAX_CHARS + 1); | ||
| 197 | + let long_name = "n".repeat(NAME_MAX_CHARS + 1); | ||
| 198 | + let body = format!( | ||
| 199 | + r#"{{"services":[ | ||
| 200 | + {{"key":"im","name":"Account","url":"https://im.example.com","healthy":true,"checked_at":"x"}}, | ||
| 201 | + {{"key":"ftp","name":"Files","url":"ftp://files.example.com"}}, | ||
| 202 | + {{"key":"javascript","name":"Bad","url":"javascript:alert(1)"}}, | ||
| 203 | + {{"key":"{long_key}","name":"Long key","url":"https://a.example.com"}}, | ||
| 204 | + {{"key":"Upper","name":"Case","url":"https://b.example.com"}}, | ||
| 205 | + {{"key":"in","name":"{long_name}","url":"https://c.example.com"}}, | ||
| 206 | + {{"key":"iz","name":"Board","url":"http://iz.example.com/","healthy":false}} | ||
| 207 | + ]}}"# | ||
| 208 | + ); | ||
| 209 | + let services = parse_listing(body.as_bytes()).expect("listing parses"); | ||
| 210 | + let keys: Vec<&str> = services.iter().map(|s| s.key.as_str()).collect(); | ||
| 211 | + assert_eq!(keys, ["im", "iz"]); | ||
| 212 | + assert!(services[0].healthy); | ||
| 213 | + assert!(!services[1].healthy); | ||
| 214 | + assert_eq!(services[1].url, "http://iz.example.com/"); | ||
| 215 | + } | ||
| 216 | + | ||
| 217 | + /// The switcher is left out of a page when the list is empty. The styled 404 page goes through | ||
| 218 | + /// the shell, so it shows the topbar; the list is empty here because nothing has been fetched. | ||
| 219 | + #[tokio::test] | ||
| 220 | + async fn an_empty_list_renders_no_switcher() { | ||
| 221 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 222 | + let text = format!( | ||
| 223 | + "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", | ||
| 224 | + dir.path().join("iz.db").display(), | ||
| 225 | + dir.path().display(), | ||
| 226 | + ); | ||
| 227 | + let config = iz_core::config::Config::parse(&text).expect("test config"); | ||
| 228 | + let store = iz_core::store::Store::open(&config.database) | ||
| 229 | + .await | ||
| 230 | + .expect("store"); | ||
| 231 | + let state = AppState { | ||
| 232 | + config: std::sync::Arc::new(config), | ||
| 233 | + store, | ||
| 234 | + key: std::sync::Arc::new([0u8; 32]), | ||
| 235 | + live: std::sync::Arc::default(), | ||
| 236 | + oidc: None, | ||
| 237 | + family: std::sync::Arc::default(), | ||
| 238 | + }; | ||
| 239 | + let request = http::Request::get("/no/such/page") | ||
| 240 | + .header(http::header::ACCEPT, "text/html") | ||
| 241 | + .body(topcoat::router::Body::empty()) | ||
| 242 | + .expect("request"); | ||
| 243 | + let response = crate::boot::router(state).handle(request).await; | ||
| 244 | + let body = topcoat::router::to_bytes(response.into_body(), 256 * 1024) | ||
| 245 | + .await | ||
| 246 | + .expect("body"); | ||
| 247 | + let html = String::from_utf8_lossy(&body); | ||
| 248 | + assert!( | ||
| 249 | + html.contains("Page not found"), | ||
| 250 | + "the styled 404, got: {html}" | ||
| 251 | + ); | ||
| 252 | + assert!( | ||
| 253 | + !html.contains("class=\"switcher\""), | ||
| 254 | + "no switcher, got: {html}" | ||
| 255 | + ); | ||
| 256 | + } | ||
| 257 | +} | ||
crates/iz-web/src/i18n/mod.rsmodified+1 -0
| @@ -10,6 +10,7 @@ | |||
| 10 | pub mod admin; | 10 | pub mod admin; |
| 11 | pub mod board; | 11 | pub mod board; |
| 12 | pub mod shell; | 12 | pub mod shell; |
| 13 | +pub mod structure; | ||
| 13 | pub mod task; | 14 | pub mod task; |
| 14 | 15 | ||
| 15 | use topcoat::context::Cx; | 16 | use topcoat::context::Cx; |
crates/iz-web/src/i18n/structure.rsadded+364 -0
| @@ -0,0 +1,364 @@ | |||
| 1 | +//! Strings of the structure and people pages: projects (`/tags`), columns (`/columns`), the members and | ||
| 2 | +//! limits and server sections of `/settings`, and the person card (`/people/{sub}`). One variant per | ||
| 3 | +//! phrase; `t` matches `(key, lang)` exhaustively, so a missing Turkish text does not compile. Values go | ||
| 4 | +//! into sentences through `fill`, never by concatenation. | ||
| 5 | + | ||
| 6 | +use super::Lang; | ||
| 7 | + | ||
| 8 | +/// One phrase of the structure and people pages. | ||
| 9 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 10 | +pub enum K { | ||
| 11 | + /// Navigation: the projects tab. | ||
| 12 | + NavTags, | ||
| 13 | + /// Navigation: the columns tab. | ||
| 14 | + NavColumns, | ||
| 15 | + /// Projects page heading. | ||
| 16 | + TagsTitle, | ||
| 17 | + /// Projects page help text. | ||
| 18 | + TagsHelp, | ||
| 19 | + /// Heading of the add-project form. | ||
| 20 | + TagsNew, | ||
| 21 | + /// Label of the project name field. | ||
| 22 | + TagName, | ||
| 23 | + /// Label of the colour choice. | ||
| 24 | + TagColour, | ||
| 25 | + /// The choice of no colour. | ||
| 26 | + TagNoColour, | ||
| 27 | + /// Button that adds a project. | ||
| 28 | + TagAdd, | ||
| 29 | + /// Button that renames a project. | ||
| 30 | + TagRename, | ||
| 31 | + /// Button that saves a project's colour. | ||
| 32 | + TagSaveColour, | ||
| 33 | + /// Button that deletes a project. | ||
| 34 | + TagDelete, | ||
| 35 | + /// Badge of the default project. | ||
| 36 | + TagDefault, | ||
| 37 | + /// Button that moves a project towards the start. | ||
| 38 | + TagMoveUp, | ||
| 39 | + /// Button that moves a project towards the end. | ||
| 40 | + TagMoveDown, | ||
| 41 | + /// "{} cards" note for a project in use. | ||
| 42 | + TagUsedBy, | ||
| 43 | + /// Columns page heading. | ||
| 44 | + ColumnsTitle, | ||
| 45 | + /// Columns page help text. | ||
| 46 | + ColumnsHelp, | ||
| 47 | + /// Heading of the add-column form. | ||
| 48 | + ColumnsNew, | ||
| 49 | + /// Label of the column name field. | ||
| 50 | + ColumnName, | ||
| 51 | + /// Button that adds a column. | ||
| 52 | + ColumnAdd, | ||
| 53 | + /// Button that renames a column. | ||
| 54 | + ColumnRename, | ||
| 55 | + /// Button that retires a column (a soft delete). | ||
| 56 | + ColumnRetire, | ||
| 57 | + /// Button that moves a column towards the start. | ||
| 58 | + ColumnMoveUp, | ||
| 59 | + /// Button that moves a column towards the end. | ||
| 60 | + ColumnMoveDown, | ||
| 61 | + /// "{} cards" note for a column. | ||
| 62 | + ColumnCards, | ||
| 63 | + /// Badge of the done column. | ||
| 64 | + ColumnDone, | ||
| 65 | + /// Confirmation: a project was added. | ||
| 66 | + NoticeTagAdded, | ||
| 67 | + /// Confirmation: a project was renamed. | ||
| 68 | + NoticeTagRenamed, | ||
| 69 | + /// Confirmation: a project's colour was saved. | ||
| 70 | + NoticeTagColoured, | ||
| 71 | + /// Confirmation: a project was deleted. | ||
| 72 | + NoticeTagDeleted, | ||
| 73 | + /// Confirmation: a project was moved. | ||
| 74 | + NoticeTagMoved, | ||
| 75 | + /// Confirmation: a column was added. | ||
| 76 | + NoticeColumnAdded, | ||
| 77 | + /// Confirmation: a column was renamed. | ||
| 78 | + NoticeColumnRenamed, | ||
| 79 | + /// Confirmation: a column was moved. | ||
| 80 | + NoticeColumnMoved, | ||
| 81 | + /// Confirmation: a column was retired. | ||
| 82 | + NoticeColumnRetired, | ||
| 83 | + /// Confirmation: a member's role was saved. | ||
| 84 | + NoticeRoleSet, | ||
| 85 | + /// Confirmation: the limits were saved. | ||
| 86 | + NoticeLimitsSaved, | ||
| 87 | + /// Settings section: members and roles. | ||
| 88 | + MembersHeading, | ||
| 89 | + /// Help text of the members section. | ||
| 90 | + MembersHelp, | ||
| 91 | + /// Column header: name. | ||
| 92 | + MemberName, | ||
| 93 | + /// Column header: email address. | ||
| 94 | + MemberEmail, | ||
| 95 | + /// Column header: role. | ||
| 96 | + MemberRole, | ||
| 97 | + /// Column header: flags (directory admin, disabled). | ||
| 98 | + MemberFlags, | ||
| 99 | + /// Flag: the directory marks this person as an administrator. | ||
| 100 | + MemberImAdmin, | ||
| 101 | + /// Flag: the directory has disabled this person. | ||
| 102 | + MemberDisabled, | ||
| 103 | + /// Button that saves a role. | ||
| 104 | + MemberSave, | ||
| 105 | + /// Role word: admin. | ||
| 106 | + RoleAdmin, | ||
| 107 | + /// Role word: member. | ||
| 108 | + RoleMember, | ||
| 109 | + /// Role word: viewer. | ||
| 110 | + RoleViewer, | ||
| 111 | + /// Role word: none (no access). | ||
| 112 | + RoleNone, | ||
| 113 | + /// Settings section: limits. | ||
| 114 | + LimitsHeading, | ||
| 115 | + /// Help text of the limits section. | ||
| 116 | + LimitsHelp, | ||
| 117 | + /// Label of the attachment size limit. | ||
| 118 | + LimitMib, | ||
| 119 | + /// Label of the allowed attachment extensions. | ||
| 120 | + LimitExtensions, | ||
| 121 | + /// Button that saves the limits. | ||
| 122 | + LimitsSave, | ||
| 123 | + /// Settings section: server information. | ||
| 124 | + ServerHeading, | ||
| 125 | + /// Help text of the server section. | ||
| 126 | + ServerHelp, | ||
| 127 | + /// Row: public base URL. | ||
| 128 | + ServerBase, | ||
| 129 | + /// Row: listen address. | ||
| 130 | + ServerListen, | ||
| 131 | + /// Row: data directory. | ||
| 132 | + ServerData, | ||
| 133 | + /// Row: database file. | ||
| 134 | + ServerDatabase, | ||
| 135 | + /// Row: schema version. | ||
| 136 | + ServerSchema, | ||
| 137 | + /// Row: build. | ||
| 138 | + ServerBuild, | ||
| 139 | + /// Row: sign-in through im. | ||
| 140 | + ServerSignIn, | ||
| 141 | + /// Row: where attachments are stored. | ||
| 142 | + ServerStorage, | ||
| 143 | + /// Value: on. | ||
| 144 | + On, | ||
| 145 | + /// Value: off. | ||
| 146 | + Off, | ||
| 147 | + /// Value: attachments in the family's Files service. | ||
| 148 | + StorageIn, | ||
| 149 | + /// Value: attachments on this server's disk. | ||
| 150 | + StorageLocal, | ||
| 151 | + /// Person card: the role line, "{}" is the role word. | ||
| 152 | + PersonRole, | ||
| 153 | + /// Person card: count of open tasks. | ||
| 154 | + PersonOpen, | ||
| 155 | + /// Person card: count of finished tasks. | ||
| 156 | + PersonDone, | ||
| 157 | + /// Person card: count of created tasks. | ||
| 158 | + PersonCreated, | ||
| 159 | + /// Person card: count of comments. | ||
| 160 | + PersonComments, | ||
| 161 | + /// Person card: count of files. | ||
| 162 | + PersonFiles, | ||
| 163 | + /// Person card: heading of the recent activity. | ||
| 164 | + PersonRecent, | ||
| 165 | + /// Person card: no activity yet. | ||
| 166 | + PersonNoActivity, | ||
| 167 | + /// Person card: last sign-in label. | ||
| 168 | + PersonLastSignIn, | ||
| 169 | + /// Person card: never signed in. | ||
| 170 | + PersonNeverSignedIn, | ||
| 171 | + /// Person card: time zone label. | ||
| 172 | + PersonZone, | ||
| 173 | + /// Person card: back link to the board. | ||
| 174 | + PersonBack, | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +/// The text of `key` in `lang`. | ||
| 178 | +pub fn t(lang: Lang, key: K) -> &'static str { | ||
| 179 | + use Lang::{En, Tr}; | ||
| 180 | + match (key, lang) { | ||
| 181 | + (K::NavTags, En) => "Projects", | ||
| 182 | + (K::NavTags, Tr) => "Projeler", | ||
| 183 | + (K::NavColumns, En) => "Columns", | ||
| 184 | + (K::NavColumns, Tr) => "Sütunlar", | ||
| 185 | + (K::TagsTitle, En) => "Projects", | ||
| 186 | + (K::TagsTitle, Tr) => "Projeler", | ||
| 187 | + (K::TagsHelp, En) => { | ||
| 188 | + "Projects group the cards. A project in use cannot be deleted; move its cards first." | ||
| 189 | + } | ||
| 190 | + (K::TagsHelp, Tr) => { | ||
| 191 | + "Projeler kartları gruplar. Kullanımda olan bir proje silinemez; önce kartlarını taşıyın." | ||
| 192 | + } | ||
| 193 | + (K::TagsNew, En) => "New project", | ||
| 194 | + (K::TagsNew, Tr) => "Yeni proje", | ||
| 195 | + (K::TagName, En) => "Name", | ||
| 196 | + (K::TagName, Tr) => "Ad", | ||
| 197 | + (K::TagColour, En) => "Colour", | ||
| 198 | + (K::TagColour, Tr) => "Renk", | ||
| 199 | + (K::TagNoColour, En) => "No colour", | ||
| 200 | + (K::TagNoColour, Tr) => "Renksiz", | ||
| 201 | + (K::TagAdd, En) => "Add project", | ||
| 202 | + (K::TagAdd, Tr) => "Proje ekle", | ||
| 203 | + (K::TagRename, En) => "Rename", | ||
| 204 | + (K::TagRename, Tr) => "Yeniden adlandır", | ||
| 205 | + (K::TagSaveColour, En) => "Save colour", | ||
| 206 | + (K::TagSaveColour, Tr) => "Rengi kaydet", | ||
| 207 | + (K::TagDelete, En) => "Delete", | ||
| 208 | + (K::TagDelete, Tr) => "Sil", | ||
| 209 | + (K::TagDefault, En) => "default", | ||
| 210 | + (K::TagDefault, Tr) => "varsayılan", | ||
| 211 | + (K::TagMoveUp, En) => "Earlier", | ||
| 212 | + (K::TagMoveUp, Tr) => "Yukarı", | ||
| 213 | + (K::TagMoveDown, En) => "Later", | ||
| 214 | + (K::TagMoveDown, Tr) => "Aşağı", | ||
| 215 | + (K::TagUsedBy, En) => "{} cards", | ||
| 216 | + (K::TagUsedBy, Tr) => "{} kart", | ||
| 217 | + (K::ColumnsTitle, En) => "Columns", | ||
| 218 | + (K::ColumnsTitle, Tr) => "Sütunlar", | ||
| 219 | + (K::ColumnsHelp, En) => { | ||
| 220 | + "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." | ||
| 221 | + } | ||
| 222 | + (K::ColumnsHelp, Tr) => { | ||
| 223 | + "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." | ||
| 224 | + } | ||
| 225 | + (K::ColumnsNew, En) => "New column", | ||
| 226 | + (K::ColumnsNew, Tr) => "Yeni sütun", | ||
| 227 | + (K::ColumnName, En) => "Name", | ||
| 228 | + (K::ColumnName, Tr) => "Ad", | ||
| 229 | + (K::ColumnAdd, En) => "Add column", | ||
| 230 | + (K::ColumnAdd, Tr) => "Sütun ekle", | ||
| 231 | + (K::ColumnRename, En) => "Rename", | ||
| 232 | + (K::ColumnRename, Tr) => "Yeniden adlandır", | ||
| 233 | + (K::ColumnRetire, En) => "Retire", | ||
| 234 | + (K::ColumnRetire, Tr) => "Emekliye ayır", | ||
| 235 | + (K::ColumnMoveUp, En) => "Earlier", | ||
| 236 | + (K::ColumnMoveUp, Tr) => "Yukarı", | ||
| 237 | + (K::ColumnMoveDown, En) => "Later", | ||
| 238 | + (K::ColumnMoveDown, Tr) => "Aşağı", | ||
| 239 | + (K::ColumnCards, En) => "{} cards", | ||
| 240 | + (K::ColumnCards, Tr) => "{} kart", | ||
| 241 | + (K::ColumnDone, En) => "done", | ||
| 242 | + (K::ColumnDone, Tr) => "tamamlandı", | ||
| 243 | + (K::NoticeTagAdded, En) => "The project was added.", | ||
| 244 | + (K::NoticeTagAdded, Tr) => "Proje eklendi.", | ||
| 245 | + (K::NoticeTagRenamed, En) => "The project was renamed.", | ||
| 246 | + (K::NoticeTagRenamed, Tr) => "Proje yeniden adlandırıldı.", | ||
| 247 | + (K::NoticeTagColoured, En) => "The colour was saved.", | ||
| 248 | + (K::NoticeTagColoured, Tr) => "Renk kaydedildi.", | ||
| 249 | + (K::NoticeTagDeleted, En) => "The project was deleted.", | ||
| 250 | + (K::NoticeTagDeleted, Tr) => "Proje silindi.", | ||
| 251 | + (K::NoticeTagMoved, En) => "The project was moved.", | ||
| 252 | + (K::NoticeTagMoved, Tr) => "Proje taşındı.", | ||
| 253 | + (K::NoticeColumnAdded, En) => "The column was added.", | ||
| 254 | + (K::NoticeColumnAdded, Tr) => "Sütun eklendi.", | ||
| 255 | + (K::NoticeColumnRenamed, En) => "The column was renamed.", | ||
| 256 | + (K::NoticeColumnRenamed, Tr) => "Sütun yeniden adlandırıldı.", | ||
| 257 | + (K::NoticeColumnMoved, En) => "The column was moved.", | ||
| 258 | + (K::NoticeColumnMoved, Tr) => "Sütun taşındı.", | ||
| 259 | + (K::NoticeColumnRetired, En) => "The column was retired.", | ||
| 260 | + (K::NoticeColumnRetired, Tr) => "Sütun emekliye ayrıldı.", | ||
| 261 | + (K::NoticeRoleSet, En) => "The role was saved.", | ||
| 262 | + (K::NoticeRoleSet, Tr) => "Rol kaydedildi.", | ||
| 263 | + (K::NoticeLimitsSaved, En) => "The limits were saved.", | ||
| 264 | + (K::NoticeLimitsSaved, Tr) => "Sınırlar kaydedildi.", | ||
| 265 | + (K::MembersHeading, En) => "Members and roles", | ||
| 266 | + (K::MembersHeading, Tr) => "Üyeler ve roller", | ||
| 267 | + (K::MembersHelp, En) => { | ||
| 268 | + "Admins manage the board. Members write. Viewers only read. None has no access. The last administrator cannot be demoted." | ||
| 269 | + } | ||
| 270 | + (K::MembersHelp, Tr) => { | ||
| 271 | + "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." | ||
| 272 | + } | ||
| 273 | + (K::MemberName, En) => "Name", | ||
| 274 | + (K::MemberName, Tr) => "Ad", | ||
| 275 | + (K::MemberEmail, En) => "Email", | ||
| 276 | + (K::MemberEmail, Tr) => "E-posta", | ||
| 277 | + (K::MemberRole, En) => "Role", | ||
| 278 | + (K::MemberRole, Tr) => "Rol", | ||
| 279 | + (K::MemberFlags, En) => "Flags", | ||
| 280 | + (K::MemberFlags, Tr) => "Durum", | ||
| 281 | + (K::MemberImAdmin, En) => "admin in im", | ||
| 282 | + (K::MemberImAdmin, Tr) => "im yöneticisi", | ||
| 283 | + (K::MemberDisabled, En) => "disabled", | ||
| 284 | + (K::MemberDisabled, Tr) => "devre dışı", | ||
| 285 | + (K::MemberSave, En) => "Save role", | ||
| 286 | + (K::MemberSave, Tr) => "Rolü kaydet", | ||
| 287 | + (K::RoleAdmin, En) => "admin", | ||
| 288 | + (K::RoleAdmin, Tr) => "yönetici", | ||
| 289 | + (K::RoleMember, En) => "member", | ||
| 290 | + (K::RoleMember, Tr) => "üye", | ||
| 291 | + (K::RoleViewer, En) => "viewer", | ||
| 292 | + (K::RoleViewer, Tr) => "görüntüleyici", | ||
| 293 | + (K::RoleNone, En) => "none", | ||
| 294 | + (K::RoleNone, Tr) => "yok", | ||
| 295 | + (K::LimitsHeading, En) => "Limits", | ||
| 296 | + (K::LimitsHeading, Tr) => "Sınırlar", | ||
| 297 | + (K::LimitsHelp, En) => { | ||
| 298 | + "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." | ||
| 299 | + } | ||
| 300 | + (K::LimitsHelp, Tr) => { | ||
| 301 | + "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." | ||
| 302 | + } | ||
| 303 | + (K::LimitMib, En) => "Attachment size limit (MiB)", | ||
| 304 | + (K::LimitMib, Tr) => "Ek boyutu sınırı (MiB)", | ||
| 305 | + (K::LimitExtensions, En) => "Allowed extensions", | ||
| 306 | + (K::LimitExtensions, Tr) => "İzin verilen uzantılar", | ||
| 307 | + (K::LimitsSave, En) => "Save limits", | ||
| 308 | + (K::LimitsSave, Tr) => "Sınırları kaydet", | ||
| 309 | + (K::ServerHeading, En) => "Server", | ||
| 310 | + (K::ServerHeading, Tr) => "Sunucu", | ||
| 311 | + (K::ServerHelp, En) => "Read-only. Changed in the configuration file and restarted.", | ||
| 312 | + (K::ServerHelp, Tr) => { | ||
| 313 | + "Salt okunur. Yapılandırma dosyasında değiştirilir ve yeniden başlatılır." | ||
| 314 | + } | ||
| 315 | + (K::ServerBase, En) => "Base address", | ||
| 316 | + (K::ServerBase, Tr) => "Temel adres", | ||
| 317 | + (K::ServerListen, En) => "Listen address", | ||
| 318 | + (K::ServerListen, Tr) => "Dinleme adresi", | ||
| 319 | + (K::ServerData, En) => "Data directory", | ||
| 320 | + (K::ServerData, Tr) => "Veri dizini", | ||
| 321 | + (K::ServerDatabase, En) => "Database file", | ||
| 322 | + (K::ServerDatabase, Tr) => "Veritabanı dosyası", | ||
| 323 | + (K::ServerSchema, En) => "Schema version", | ||
| 324 | + (K::ServerSchema, Tr) => "Şema sürümü", | ||
| 325 | + (K::ServerBuild, En) => "Build", | ||
| 326 | + (K::ServerBuild, Tr) => "Derleme", | ||
| 327 | + (K::ServerSignIn, En) => "Sign-in through im", | ||
| 328 | + (K::ServerSignIn, Tr) => "im ile giriş", | ||
| 329 | + (K::ServerStorage, En) => "Attachment storage", | ||
| 330 | + (K::ServerStorage, Tr) => "Ek depolama", | ||
| 331 | + (K::On, En) => "on", | ||
| 332 | + (K::On, Tr) => "açık", | ||
| 333 | + (K::Off, En) => "off", | ||
| 334 | + (K::Off, Tr) => "kapalı", | ||
| 335 | + (K::StorageIn, En) => "Files service", | ||
| 336 | + (K::StorageIn, Tr) => "Dosya hizmeti", | ||
| 337 | + (K::StorageLocal, En) => "this server", | ||
| 338 | + (K::StorageLocal, Tr) => "bu sunucu", | ||
| 339 | + (K::PersonRole, En) => "Role: {}", | ||
| 340 | + (K::PersonRole, Tr) => "Rol: {}", | ||
| 341 | + (K::PersonOpen, En) => "Open tasks", | ||
| 342 | + (K::PersonOpen, Tr) => "Açık kartlar", | ||
| 343 | + (K::PersonDone, En) => "Finished tasks", | ||
| 344 | + (K::PersonDone, Tr) => "Tamamlanan kartlar", | ||
| 345 | + (K::PersonCreated, En) => "Created", | ||
| 346 | + (K::PersonCreated, Tr) => "Oluşturulan", | ||
| 347 | + (K::PersonComments, En) => "Comments", | ||
| 348 | + (K::PersonComments, Tr) => "Yorumlar", | ||
| 349 | + (K::PersonFiles, En) => "Files", | ||
| 350 | + (K::PersonFiles, Tr) => "Dosyalar", | ||
| 351 | + (K::PersonRecent, En) => "Recent activity", | ||
| 352 | + (K::PersonRecent, Tr) => "Son etkinlik", | ||
| 353 | + (K::PersonNoActivity, En) => "No activity yet.", | ||
| 354 | + (K::PersonNoActivity, Tr) => "Henüz etkinlik yok.", | ||
| 355 | + (K::PersonLastSignIn, En) => "Last sign-in", | ||
| 356 | + (K::PersonLastSignIn, Tr) => "Son giriş", | ||
| 357 | + (K::PersonNeverSignedIn, En) => "never", | ||
| 358 | + (K::PersonNeverSignedIn, Tr) => "hiç", | ||
| 359 | + (K::PersonZone, En) => "Time zone", | ||
| 360 | + (K::PersonZone, Tr) => "Saat dilimi", | ||
| 361 | + (K::PersonBack, En) => "Back to the board", | ||
| 362 | + (K::PersonBack, Tr) => "Panoya dön", | ||
| 363 | + } | ||
| 364 | +} | ||
crates/iz-web/src/live.rsmodified+4 -0
| @@ -62,6 +62,10 @@ pub enum AdminSection { | |||
| 62 | Settings, | 62 | Settings, |
| 63 | /// The members and roles list. | 63 | /// The members and roles list. |
| 64 | Members, | 64 | Members, |
| 65 | + /// The projects and columns pages. | ||
| 66 | + Structure, | ||
| 67 | + /// The mail rules page. | ||
| 68 | + Rules, | ||
| 65 | } | 69 | } |
| 66 | 70 | ||
| 67 | /// The change counters of all open topics. Cheap to share: every clone of the app state holds the | 71 | /// The change counters of all open topics. Cheap to share: every clone of the app state holds the |
crates/iz-web/src/main.rsmodified+23 -57
| @@ -1,8 +1,8 @@ | |||
| 1 | //! The `iz` binary: the command line, logging and the process lifetime. | 1 | //! The `iz` binary: the command line, logging and the process lifetime. |
| 2 | //! | 2 | //! |
| 3 | -//! `iz [--config <path>] [serve]` runs the server; a bare `iz` does the same. `iz admin ...` is the | 3 | +//! `iz [--config <path>] [serve]` runs the server; a bare `iz` does the same. `iz export`, `iz restore` and |
| 4 | -//! operator command line, which is not built yet. The configuration file is the `--config` path, | 4 | +//! `iz fsck` are the operator commands (see `cli`). The configuration file is the `--config` path, then |
| 5 | -//! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. | 5 | +//! `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. |
| 6 | 6 | ||
| 7 | // The page handlers nest many view and store futures; the default limit is too small for their types. | 7 | // The page handlers nest many view and store futures; the default limit is too small for their types. |
| 8 | #![recursion_limit = "256"] | 8 | #![recursion_limit = "256"] |
| @@ -10,8 +10,11 @@ | |||
| 10 | mod assets; | 10 | mod assets; |
| 11 | mod attachments; | 11 | mod attachments; |
| 12 | mod auth; | 12 | mod auth; |
| 13 | +mod backup; | ||
| 13 | mod boot; | 14 | mod boot; |
| 15 | +mod cli; | ||
| 14 | mod directory; | 16 | mod directory; |
| 17 | +mod family; | ||
| 15 | mod health; | 18 | mod health; |
| 16 | mod i18n; | 19 | mod i18n; |
| 17 | mod live; | 20 | mod live; |
| @@ -21,50 +24,16 @@ mod pages; | |||
| 21 | mod security; | 24 | mod security; |
| 22 | mod serve; | 25 | mod serve; |
| 23 | mod state; | 26 | mod state; |
| 27 | +mod sweeper; | ||
| 24 | mod views; | 28 | mod views; |
| 25 | 29 | ||
| 26 | -use std::path::{Path, PathBuf}; | 30 | +use std::path::Path; |
| 27 | use std::process::ExitCode; | 31 | use std::process::ExitCode; |
| 28 | 32 | ||
| 33 | +use clap::Parser; | ||
| 34 | +use cli::{Cli, Command}; | ||
| 29 | use tracing_subscriber::EnvFilter; | 35 | use tracing_subscriber::EnvFilter; |
| 30 | 36 | ||
| 31 | -/// Printed with a usage error. | ||
| 32 | -const USAGE: &str = "usage: iz [--config <path>] [serve]"; | ||
| 33 | - | ||
| 34 | -/// The configuration file when neither `--config` nor `IZ_CONFIG` names one. | ||
| 35 | -const DEFAULT_CONFIG: &str = "config/iz.toml"; | ||
| 36 | - | ||
| 37 | -/// The environment variable that names the configuration file. | ||
| 38 | -const CONFIG_ENV: &str = "IZ_CONFIG"; | ||
| 39 | - | ||
| 40 | -/// The parsed command line: the `--config` path and the positional words. | ||
| 41 | -struct Cli { | ||
| 42 | - config: Option<PathBuf>, | ||
| 43 | - words: Vec<String>, | ||
| 44 | -} | ||
| 45 | - | ||
| 46 | -/// Splits the arguments into the `--config <path>` pair and the positional words. | ||
| 47 | -fn parse_args(args: impl Iterator<Item = String>) -> Result<Cli, String> { | ||
| 48 | - let mut config = None; | ||
| 49 | - let mut words = Vec::new(); | ||
| 50 | - let mut args = args; | ||
| 51 | - while let Some(arg) = args.next() { | ||
| 52 | - if arg == "--config" { | ||
| 53 | - let path = args.next().ok_or("--config needs a path")?; | ||
| 54 | - config = Some(PathBuf::from(path)); | ||
| 55 | - } else { | ||
| 56 | - words.push(arg); | ||
| 57 | - } | ||
| 58 | - } | ||
| 59 | - Ok(Cli { config, words }) | ||
| 60 | -} | ||
| 61 | - | ||
| 62 | -/// The configuration path: the flag, else `IZ_CONFIG`, else the default. | ||
| 63 | -fn config_path(flag: Option<PathBuf>) -> PathBuf { | ||
| 64 | - flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from)) | ||
| 65 | - .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG)) | ||
| 66 | -} | ||
| 67 | - | ||
| 68 | /// Logs to stderr. The level comes from `RUST_LOG`, and defaults to `info`. | 37 | /// Logs to stderr. The level comes from `RUST_LOG`, and defaults to `info`. |
| 69 | fn init_logging() { | 38 | fn init_logging() { |
| 70 | let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); | 39 | let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); |
| @@ -87,24 +56,21 @@ async fn serve(config: &Path) -> ExitCode { | |||
| 87 | 56 | ||
| 88 | #[tokio::main] | 57 | #[tokio::main] |
| 89 | async fn main() -> ExitCode { | 58 | async fn main() -> ExitCode { |
| 90 | - init_logging(); | 59 | + let cli = match Cli::try_parse() { |
| 91 | - let cli = match parse_args(std::env::args().skip(1)) { | ||
| 92 | Ok(cli) => cli, | 60 | Ok(cli) => cli, |
| 93 | - Err(message) => { | 61 | + Err(error) => { |
| 94 | - eprintln!("iz: {message}\n{USAGE}"); | 62 | + // Help and version are not failures; a usage error is exit 2. |
| 95 | - return ExitCode::from(2); | 63 | + let code = if error.use_stderr() { 2 } else { 0 }; |
| 64 | + let _ = error.print(); | ||
| 65 | + return ExitCode::from(code); | ||
| 96 | } | 66 | } |
| 97 | }; | 67 | }; |
| 98 | - let words: Vec<&str> = cli.words.iter().map(String::as_str).collect(); | 68 | + init_logging(); |
| 99 | - match words.as_slice() { | 69 | + let config = cli::config_path(cli.config); |
| 100 | - [] | ["serve"] => serve(&config_path(cli.config)).await, | 70 | + match cli.command.unwrap_or(Command::Serve) { |
| 101 | - ["admin", ..] => { | 71 | + Command::Serve => serve(&config).await, |
| 102 | - eprintln!("iz: admin commands are not implemented yet"); | 72 | + Command::Export { out } => cli::export::run(&config, &out).await, |
| 103 | - ExitCode::from(2) | 73 | + Command::Restore { from } => cli::restore::run(&config, &from).await, |
| 104 | - } | 74 | + Command::Fsck => cli::fsck::run(&config).await, |
| 105 | - _ => { | ||
| 106 | - eprintln!("iz: unknown command\n{USAGE}"); | ||
| 107 | - ExitCode::from(2) | ||
| 108 | - } | ||
| 109 | } | 75 | } |
| 110 | } | 76 | } |
crates/iz-web/src/pages/admin.rsmodified+102 -0
| @@ -13,8 +13,11 @@ use topcoat::router::response::Response; | |||
| 13 | use crate::auth::CurrentMember; | 13 | use crate::auth::CurrentMember; |
| 14 | use crate::i18n::Lang; | 14 | use crate::i18n::Lang; |
| 15 | use crate::i18n::admin::{K, fill, t}; | 15 | use crate::i18n::admin::{K, fill, t}; |
| 16 | +use crate::i18n::structure::{K as StructureK, t as structure_t}; | ||
| 16 | use crate::pages::task::core_err; | 17 | use crate::pages::task::core_err; |
| 18 | +use crate::state::AppState; | ||
| 17 | use crate::views::ViewerInfo; | 19 | use crate::views::ViewerInfo; |
| 20 | +use iz_core::store::audit::AuditEntry; | ||
| 18 | 21 | ||
| 19 | /// The status of a page re-rendered with a refusal. | 22 | /// The status of a page re-rendered with a refusal. |
| 20 | pub const REFUSED: topcoat::router::StatusCode = topcoat::router::StatusCode::UNPROCESSABLE_ENTITY; | 23 | 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<Strin | |||
| 50 | "rule_deleted" => t(lang, K::NoticeRuleDeleted).to_owned(), | 53 | "rule_deleted" => t(lang, K::NoticeRuleDeleted).to_owned(), |
| 51 | "rule_switched" => t(lang, K::NoticeRuleSwitched).to_owned(), | 54 | "rule_switched" => t(lang, K::NoticeRuleSwitched).to_owned(), |
| 52 | "retried" => t(lang, K::NoticeRetried).to_owned(), | 55 | "retried" => t(lang, K::NoticeRetried).to_owned(), |
| 56 | + "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(), | ||
| 57 | + "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(), | ||
| 58 | + "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => { | ||
| 59 | + return crate::pages::tags::tag_notice(lang, code); | ||
| 60 | + } | ||
| 61 | + "column_added" | "column_renamed" | "column_moved" | "column_retired" => { | ||
| 62 | + return crate::pages::columns::column_notice(lang, code); | ||
| 63 | + } | ||
| 53 | _ => return None, | 64 | _ => return None, |
| 54 | }; | 65 | }; |
| 55 | Some(text) | 66 | Some(text) |
| @@ -67,3 +78,94 @@ pub struct CsrfForm { | |||
| 67 | /// The session's CSRF token. | 78 | /// The session's CSRF token. |
| 68 | pub csrf: String, | 79 | pub csrf: String, |
| 69 | } | 80 | } |
| 81 | + | ||
| 82 | +/// Writes one audit row for an administrator's write that has committed. The caller bumps the live | ||
| 83 | +/// topic of its section; this only records who did what. Never fails the request. | ||
| 84 | +pub async fn record( | ||
| 85 | + state: &AppState, | ||
| 86 | + me: &CurrentMember, | ||
| 87 | + action: &'static str, | ||
| 88 | + target_kind: &'static str, | ||
| 89 | + target_id: Option<&str>, | ||
| 90 | + data: serde_json::Value, | ||
| 91 | +) { | ||
| 92 | + state | ||
| 93 | + .store | ||
| 94 | + .audit(AuditEntry { | ||
| 95 | + actor: Some(&me.member.sub), | ||
| 96 | + actor_kind: "admin", | ||
| 97 | + action, | ||
| 98 | + target_kind, | ||
| 99 | + target_id, | ||
| 100 | + ip: None, | ||
| 101 | + data, | ||
| 102 | + }) | ||
| 103 | + .await; | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +#[cfg(test)] | ||
| 107 | +mod tests { | ||
| 108 | + use http::header::{CONTENT_TYPE, COOKIE}; | ||
| 109 | + use iz_core::authz::Role; | ||
| 110 | + use topcoat::router::{Body, to_bytes}; | ||
| 111 | + | ||
| 112 | + use crate::boot::{router, test_state}; | ||
| 113 | + use crate::pages::board::{cookie_of, sign_in_as}; | ||
| 114 | + | ||
| 115 | + /// Sends one request and returns the status code. | ||
| 116 | + async fn status_of(state: &crate::state::AppState, request: http::Request<Body>) -> u16 { | ||
| 117 | + let response = router(state.clone()).handle(request).await; | ||
| 118 | + let status = response.status().as_u16(); | ||
| 119 | + let _ = to_bytes(response.into_body(), 64 * 1024).await; | ||
| 120 | + status | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + /// A member, an anonymous visitor and a wrong-role user all get `404` for admin pages, never `403` or | ||
| 124 | + /// a sign-in redirect that would show the page exists. | ||
| 125 | + #[tokio::test] | ||
| 126 | + async fn an_admin_page_is_a_404_for_members_and_anonymous_visitors() { | ||
| 127 | + let (_dir, state) = test_state().await; | ||
| 128 | + let (member, _) = sign_in_as(&state, "01MEMBERAAAAAAAAAAAAAAAAA", Role::Member).await; | ||
| 129 | + for path in ["/settings", "/tags", "/columns", "/logs", "/rules"] { | ||
| 130 | + let as_member = http::Request::get(path) | ||
| 131 | + .header(COOKIE, cookie_of(&member)) | ||
| 132 | + .body(Body::empty()) | ||
| 133 | + .expect("request"); | ||
| 134 | + assert_eq!(status_of(&state, as_member).await, 404, "member on {path}"); | ||
| 135 | + let anonymous = http::Request::get(path) | ||
| 136 | + .body(Body::empty()) | ||
| 137 | + .expect("request"); | ||
| 138 | + assert_eq!( | ||
| 139 | + status_of(&state, anonymous).await, | ||
| 140 | + 404, | ||
| 141 | + "anonymous on {path}" | ||
| 142 | + ); | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + /// An administrator's write without the CSRF token is refused with `403` before any side effect. | ||
| 147 | + #[tokio::test] | ||
| 148 | + async fn an_admin_post_without_csrf_is_refused() { | ||
| 149 | + let (_dir, state) = test_state().await; | ||
| 150 | + let (token, _csrf) = sign_in_as(&state, "01ADMINAAAAAAAAAAAAAAAAAA", Role::Admin).await; | ||
| 151 | + let board = state.store.ensure_board("IZ").await.expect("board"); | ||
| 152 | + let request = http::Request::post("/tags") | ||
| 153 | + .header(COOKIE, cookie_of(&token)) | ||
| 154 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| 155 | + .body(Body::from("name=Sneaky")) | ||
| 156 | + .expect("request"); | ||
| 157 | + assert_eq!(status_of(&state, request).await, 403); | ||
| 158 | + let names: Vec<String> = state | ||
| 159 | + .store | ||
| 160 | + .tags(&board.id) | ||
| 161 | + .await | ||
| 162 | + .expect("tags") | ||
| 163 | + .into_iter() | ||
| 164 | + .map(|tag| tag.name) | ||
| 165 | + .collect(); | ||
| 166 | + assert!( | ||
| 167 | + !names.iter().any(|name| name == "Sneaky"), | ||
| 168 | + "the write happened" | ||
| 169 | + ); | ||
| 170 | + } | ||
| 171 | +} | ||
crates/iz-web/src/pages/columns.rsadded+278 -0
| @@ -0,0 +1,278 @@ | |||
| 1 | +//! The columns page (`GET /columns` and its POSTs): add, rename, move one place, and retire. Columns are | ||
| 2 | +//! never deleted: retiring is a soft delete that the store records, so old activity keeps its names. The | ||
| 3 | +//! done column is kept last and cannot be retired; the store enforces both. Administrators only. Every | ||
| 4 | +//! write checks CSRF first, bumps the board and admin-structure topics after commit, and writes one audit | ||
| 5 | +//! row. | ||
| 6 | + | ||
| 7 | +use iz_core::store::audit::AuditEntry; | ||
| 8 | +use iz_core::store::board::Direction; | ||
| 9 | +use serde::Deserialize; | ||
| 10 | +use topcoat::Result; | ||
| 11 | +use topcoat::context::{Cx, app_context}; | ||
| 12 | +use topcoat::router::content::Form; | ||
| 13 | +use topcoat::router::response::Response; | ||
| 14 | +use topcoat::router::{StatusCode, path_param_segment, route}; | ||
| 15 | +use topcoat::view::view; | ||
| 16 | + | ||
| 17 | +use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; | ||
| 18 | +use crate::i18n::structure::{K, t}; | ||
| 19 | +use crate::i18n::{Lang, lang}; | ||
| 20 | +use crate::live::{AdminSection, Topic}; | ||
| 21 | +use crate::pages::admin::{REFUSED, back, user_text, viewer_of}; | ||
| 22 | +use crate::pages::board::the_board; | ||
| 23 | +use crate::pages::task::core_err; | ||
| 24 | +use crate::state::AppState; | ||
| 25 | +use crate::views::structure::{ColumnRow, ColumnsView, columns_content}; | ||
| 26 | +use crate::views::{ViewerInfo, respond, shell}; | ||
| 27 | + | ||
| 28 | +/// The add and rename forms: the name, and the CSRF token. | ||
| 29 | +#[derive(Debug, Default, Deserialize)] | ||
| 30 | +#[serde(default)] | ||
| 31 | +struct NameSubmit { | ||
| 32 | + csrf: String, | ||
| 33 | + name: String, | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +/// The move form: `up` or `down`. | ||
| 37 | +#[derive(Debug, Default, Deserialize)] | ||
| 38 | +#[serde(default)] | ||
| 39 | +struct MoveSubmit { | ||
| 40 | + csrf: String, | ||
| 41 | + direction: String, | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// The notice text of a column redirect. Unknown codes give `None`. | ||
| 45 | +pub fn column_notice(lang: Lang, code: &str) -> Option<String> { | ||
| 46 | + let text = match code { | ||
| 47 | + "column_added" => t(lang, K::NoticeColumnAdded), | ||
| 48 | + "column_renamed" => t(lang, K::NoticeColumnRenamed), | ||
| 49 | + "column_moved" => t(lang, K::NoticeColumnMoved), | ||
| 50 | + "column_retired" => t(lang, K::NoticeColumnRetired), | ||
| 51 | + _ => return None, | ||
| 52 | + }; | ||
| 53 | + Some(text.to_owned()) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +/// The page's data: the live columns in board order with their card counts. | ||
| 57 | +async fn columns_page( | ||
| 58 | + state: &AppState, | ||
| 59 | + lang: Lang, | ||
| 60 | + notice: Option<String>, | ||
| 61 | + alert: Option<String>, | ||
| 62 | +) -> Result<ColumnsView> { | ||
| 63 | + let board = the_board(&state.store).await?; | ||
| 64 | + let columns = state.store.columns(&board.id).await.map_err(core_err)?; | ||
| 65 | + let usage = state | ||
| 66 | + .store | ||
| 67 | + .column_usage(&board.id) | ||
| 68 | + .await | ||
| 69 | + .map_err(core_err)?; | ||
| 70 | + let rows = columns | ||
| 71 | + .into_iter() | ||
| 72 | + .map(|column| ColumnRow { | ||
| 73 | + cards: usage | ||
| 74 | + .iter() | ||
| 75 | + .find(|(id, _)| *id == column.id) | ||
| 76 | + .map_or(0, |(_, count)| *count), | ||
| 77 | + id: column.id, | ||
| 78 | + name: column.name, | ||
| 79 | + is_done: column.is_done, | ||
| 80 | + }) | ||
| 81 | + .collect(); | ||
| 82 | + Ok(ColumnsView { | ||
| 83 | + lang, | ||
| 84 | + columns: rows, | ||
| 85 | + notice, | ||
| 86 | + alert, | ||
| 87 | + }) | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// Renders the columns page with `status` and the session's CSRF token. | ||
| 91 | +async fn render( | ||
| 92 | + cx: &Cx, | ||
| 93 | + me: &CurrentMember, | ||
| 94 | + page: ColumnsView, | ||
| 95 | + status: StatusCode, | ||
| 96 | +) -> Result<Response> { | ||
| 97 | + let lang = page.lang; | ||
| 98 | + let viewer: ViewerInfo = viewer_of(me); | ||
| 99 | + let csrf = me.session.csrf_token.clone(); | ||
| 100 | + let document = view! { | ||
| 101 | + cx => | ||
| 102 | + (status) | ||
| 103 | + shell(title: t(lang, K::ColumnsTitle), lang: lang, | ||
| 104 | + viewer: Some(&viewer), page_script: None, | ||
| 105 | + columns_content(page: &page, csrf: csrf.as_str()) | ||
| 106 | + ) | ||
| 107 | + }; | ||
| 108 | + respond(cx, document).await | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// Bumps the board (its columns show on every card view) and the admin-structure section. | ||
| 112 | +fn bump_structure(state: &AppState, board_id: &str) { | ||
| 113 | + state.live.bump(&Topic::Board(board_id.to_owned())); | ||
| 114 | + state.live.bump(&Topic::Admin(AdminSection::Structure)); | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +/// `GET /columns`. Administrators only. | ||
| 118 | +#[route(GET "/columns")] | ||
| 119 | +async fn columns_get(cx: &Cx) -> Result<Response> { | ||
| 120 | + let state = app_context::<AppState>(cx); | ||
| 121 | + let me = require_role(cx, Need::Admin).await?; | ||
| 122 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 123 | + let notice = query_param(cx, "notice").and_then(|code| column_notice(language, &code)); | ||
| 124 | + let page = columns_page(state, language, notice, None).await?; | ||
| 125 | + render(cx, &me, page, StatusCode::OK).await | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +/// `POST /columns`: adds a column before the done column. | ||
| 129 | +#[route(POST "/columns")] | ||
| 130 | +async fn add_column(cx: &Cx, form: Option<Form<NameSubmit>>) -> Result<Response> { | ||
| 131 | + let state = app_context::<AppState>(cx); | ||
| 132 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 133 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 134 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 135 | + let board = the_board(&state.store).await?; | ||
| 136 | + match state.store.add_column(&board.id, &form.name).await { | ||
| 137 | + Ok(column) => { | ||
| 138 | + state | ||
| 139 | + .store | ||
| 140 | + .audit(AuditEntry { | ||
| 141 | + actor: Some(&me.member.sub), | ||
| 142 | + actor_kind: "admin", | ||
| 143 | + action: "column.add", | ||
| 144 | + target_kind: "column", | ||
| 145 | + target_id: Some(&column.id), | ||
| 146 | + ip: None, | ||
| 147 | + data: serde_json::json!({ "name": column.name }), | ||
| 148 | + }) | ||
| 149 | + .await; | ||
| 150 | + bump_structure(state, &board.id); | ||
| 151 | + back("/columns?notice=column_added") | ||
| 152 | + } | ||
| 153 | + Err(error) => { | ||
| 154 | + let message = user_text(error)?; | ||
| 155 | + let page = columns_page(state, language, None, Some(message)).await?; | ||
| 156 | + render(cx, &me, page, REFUSED).await | ||
| 157 | + } | ||
| 158 | + } | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +/// `POST /columns/{id}/rename`. | ||
| 162 | +#[route(POST "/columns/{id}/rename")] | ||
| 163 | +async fn rename_column(cx: &Cx, form: Option<Form<NameSubmit>>) -> Result<Response> { | ||
| 164 | + let state = app_context::<AppState>(cx); | ||
| 165 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 166 | + let column_id = path_param_segment(cx, "id").to_owned(); | ||
| 167 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 168 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 169 | + let board = the_board(&state.store).await?; | ||
| 170 | + match state | ||
| 171 | + .store | ||
| 172 | + .rename_column(&board.id, &column_id, &form.name) | ||
| 173 | + .await | ||
| 174 | + { | ||
| 175 | + Ok(()) => { | ||
| 176 | + state | ||
| 177 | + .store | ||
| 178 | + .audit(AuditEntry { | ||
| 179 | + actor: Some(&me.member.sub), | ||
| 180 | + actor_kind: "admin", | ||
| 181 | + action: "column.rename", | ||
| 182 | + target_kind: "column", | ||
| 183 | + target_id: Some(&column_id), | ||
| 184 | + ip: None, | ||
| 185 | + data: serde_json::json!({ "name": form.name.trim() }), | ||
| 186 | + }) | ||
| 187 | + .await; | ||
| 188 | + bump_structure(state, &board.id); | ||
| 189 | + back("/columns?notice=column_renamed") | ||
| 190 | + } | ||
| 191 | + Err(error) => { | ||
| 192 | + let message = user_text(error)?; | ||
| 193 | + let page = columns_page(state, language, None, Some(message)).await?; | ||
| 194 | + render(cx, &me, page, REFUSED).await | ||
| 195 | + } | ||
| 196 | + } | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +/// `POST /columns/{id}/move`: one place earlier or later. The store keeps the done column last. | ||
| 200 | +#[route(POST "/columns/{id}/move")] | ||
| 201 | +async fn move_column(cx: &Cx, form: Option<Form<MoveSubmit>>) -> Result<Response> { | ||
| 202 | + let state = app_context::<AppState>(cx); | ||
| 203 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 204 | + let column_id = path_param_segment(cx, "id").to_owned(); | ||
| 205 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 206 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 207 | + let board = the_board(&state.store).await?; | ||
| 208 | + let direction = match form.direction.as_str() { | ||
| 209 | + "up" => Direction::Up, | ||
| 210 | + "down" => Direction::Down, | ||
| 211 | + _ => { | ||
| 212 | + return Err(core_err(iz_core::Error::Invalid( | ||
| 213 | + "unknown direction".into(), | ||
| 214 | + ))); | ||
| 215 | + } | ||
| 216 | + }; | ||
| 217 | + match state | ||
| 218 | + .store | ||
| 219 | + .move_column(&board.id, &column_id, direction) | ||
| 220 | + .await | ||
| 221 | + { | ||
| 222 | + Ok(()) => { | ||
| 223 | + state | ||
| 224 | + .store | ||
| 225 | + .audit(AuditEntry { | ||
| 226 | + actor: Some(&me.member.sub), | ||
| 227 | + actor_kind: "admin", | ||
| 228 | + action: "column.move", | ||
| 229 | + target_kind: "column", | ||
| 230 | + target_id: Some(&column_id), | ||
| 231 | + ip: None, | ||
| 232 | + data: serde_json::json!({ "direction": form.direction }), | ||
| 233 | + }) | ||
| 234 | + .await; | ||
| 235 | + bump_structure(state, &board.id); | ||
| 236 | + back("/columns?notice=column_moved") | ||
| 237 | + } | ||
| 238 | + Err(error) => { | ||
| 239 | + let message = user_text(error)?; | ||
| 240 | + let page = columns_page(state, language, None, Some(message)).await?; | ||
| 241 | + render(cx, &me, page, REFUSED).await | ||
| 242 | + } | ||
| 243 | + } | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +/// `POST /columns/{id}/retire`: a soft delete, refused for the done column and for a column that holds cards. | ||
| 247 | +#[route(POST "/columns/{id}/retire")] | ||
| 248 | +async fn retire_column(cx: &Cx, form: Option<Form<MoveSubmit>>) -> Result<Response> { | ||
| 249 | + let state = app_context::<AppState>(cx); | ||
| 250 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 251 | + let column_id = path_param_segment(cx, "id").to_owned(); | ||
| 252 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 253 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 254 | + let board = the_board(&state.store).await?; | ||
| 255 | + match state.store.retire_column(&board.id, &column_id).await { | ||
| 256 | + Ok(()) => { | ||
| 257 | + state | ||
| 258 | + .store | ||
| 259 | + .audit(AuditEntry { | ||
| 260 | + actor: Some(&me.member.sub), | ||
| 261 | + actor_kind: "admin", | ||
| 262 | + action: "column.retire", | ||
| 263 | + target_kind: "column", | ||
| 264 | + target_id: Some(&column_id), | ||
| 265 | + ip: None, | ||
| 266 | + data: serde_json::json!({}), | ||
| 267 | + }) | ||
| 268 | + .await; | ||
| 269 | + bump_structure(state, &board.id); | ||
| 270 | + back("/columns?notice=column_retired") | ||
| 271 | + } | ||
| 272 | + Err(error) => { | ||
| 273 | + let message = user_text(error)?; | ||
| 274 | + let page = columns_page(state, language, None, Some(message)).await?; | ||
| 275 | + render(cx, &me, page, REFUSED).await | ||
| 276 | + } | ||
| 277 | + } | ||
| 278 | +} | ||
crates/iz-web/src/pages/logs.rsmodified+13 -1
| @@ -19,6 +19,8 @@ use topcoat::view::view; | |||
| 19 | use crate::auth::{Need, percent_encode, query_param, require_csrf, require_role}; | 19 | use crate::auth::{Need, percent_encode, query_param, require_csrf, require_role}; |
| 20 | use crate::i18n::admin::{K, t}; | 20 | use crate::i18n::admin::{K, t}; |
| 21 | use crate::i18n::{Lang, lang}; | 21 | use crate::i18n::{Lang, lang}; |
| 22 | +use crate::live::{AdminSection, Topic}; | ||
| 23 | +use crate::pages::admin::record; | ||
| 22 | use crate::pages::admin::{CsrfForm, back, notice_text, viewer_of}; | 24 | use crate::pages::admin::{CsrfForm, back, notice_text, viewer_of}; |
| 23 | use crate::pages::board::the_board; | 25 | use crate::pages::board::the_board; |
| 24 | use crate::pages::task::core_err; | 26 | use crate::pages::task::core_err; |
| @@ -159,11 +161,21 @@ async fn retry_row(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> { | |||
| 159 | let state = app_context::<AppState>(cx); | 161 | let state = app_context::<AppState>(cx); |
| 160 | let form = form.map(|Form(form)| form).unwrap_or_default(); | 162 | let form = form.map(|Form(form)| form).unwrap_or_default(); |
| 161 | let row_id = path_param_segment(cx, "id").to_owned(); | 163 | let row_id = path_param_segment(cx, "id").to_owned(); |
| 162 | - require_csrf(cx, Need::Admin, &form.csrf).await?; | 164 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; |
| 163 | state | 165 | state |
| 164 | .store | 166 | .store |
| 165 | .retry_row(&row_id, Timestamp::now()) | 167 | .retry_row(&row_id, Timestamp::now()) |
| 166 | .await | 168 | .await |
| 167 | .map_err(core_err)?; | 169 | .map_err(core_err)?; |
| 170 | + record( | ||
| 171 | + state, | ||
| 172 | + &me, | ||
| 173 | + "outbox.retry", | ||
| 174 | + "outbox", | ||
| 175 | + Some(&row_id), | ||
| 176 | + serde_json::json!({}), | ||
| 177 | + ) | ||
| 178 | + .await; | ||
| 179 | + state.live.bump(&Topic::Admin(AdminSection::Outbox)); | ||
| 168 | back("/logs?section=outbox¬ice=retried") | 180 | back("/logs?section=outbox¬ice=retried") |
| 169 | } | 181 | } |
crates/iz-web/src/pages/mod.rsmodified+3 -0
| @@ -3,12 +3,15 @@ | |||
| 3 | pub mod admin; | 3 | pub mod admin; |
| 4 | pub mod backchannel; | 4 | pub mod backchannel; |
| 5 | pub mod board; | 5 | pub mod board; |
| 6 | +pub mod columns; | ||
| 6 | pub mod files; | 7 | pub mod files; |
| 7 | pub mod logs; | 8 | pub mod logs; |
| 8 | pub mod not_found; | 9 | pub mod not_found; |
| 10 | +pub mod people; | ||
| 9 | pub mod photo; | 11 | pub mod photo; |
| 10 | pub mod rules; | 12 | pub mod rules; |
| 11 | pub mod settings; | 13 | pub mod settings; |
| 12 | pub mod sign_in; | 14 | pub mod sign_in; |
| 15 | +pub mod tags; | ||
| 13 | pub mod task; | 16 | pub mod task; |
| 14 | pub mod tasks; | 17 | pub mod tasks; |
crates/iz-web/src/pages/people.rsadded+119 -0
| @@ -0,0 +1,119 @@ | |||
| 1 | +//! The person card (`GET /people/{sub}`): a member's name, role, counts on this board, and their recent | ||
| 2 | +//! activity here. Visible to anyone who may read the board. The target must be a member of this board: a | ||
| 3 | +//! member with role `none`, a disabled member, or an unknown id gets `404`, so the page reveals nothing | ||
| 4 | +//! about people outside the board. Read-only: nothing on this page writes. | ||
| 5 | + | ||
| 6 | +use iz_core::authz::{Action, authorize}; | ||
| 7 | +use iz_core::store::activity::ActivityFilter; | ||
| 8 | +use iz_core::store::members::Member; | ||
| 9 | +use iz_core::zones::parse_zone; | ||
| 10 | +use topcoat::Result; | ||
| 11 | +use topcoat::context::{Cx, app_context}; | ||
| 12 | +use topcoat::router::error::not_found; | ||
| 13 | +use topcoat::router::response::Response; | ||
| 14 | +use topcoat::router::{path_param_segment, route}; | ||
| 15 | +use topcoat::view::view; | ||
| 16 | + | ||
| 17 | +use crate::auth::{Need, require_role}; | ||
| 18 | +use crate::i18n::structure::{K, t}; | ||
| 19 | +use crate::i18n::task::activity_kind; | ||
| 20 | +use crate::i18n::{Lang, lang}; | ||
| 21 | +use crate::pages::board::the_board; | ||
| 22 | +use crate::pages::task::{core_err, local_text}; | ||
| 23 | +use crate::state::AppState; | ||
| 24 | +use crate::views::structure::person_content; | ||
| 25 | +use crate::views::{ViewerInfo, respond, shell}; | ||
| 26 | + | ||
| 27 | +/// How many recent activity rows the card shows. | ||
| 28 | +const RECENT_ROWS: usize = 20; | ||
| 29 | + | ||
| 30 | +/// The role word of a stored role, in the viewer's language. | ||
| 31 | +fn role_word(lang: Lang, role: &str) -> &'static str { | ||
| 32 | + match role { | ||
| 33 | + "admin" => t(lang, K::RoleAdmin), | ||
| 34 | + "viewer" => t(lang, K::RoleViewer), | ||
| 35 | + "none" => t(lang, K::RoleNone), | ||
| 36 | + _ => t(lang, K::RoleMember), | ||
| 37 | + } | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +/// `GET /people/{sub}`. | ||
| 41 | +#[route(GET "/people/{sub}")] | ||
| 42 | +async fn person_page(cx: &Cx) -> Result<Response> { | ||
| 43 | + let state = app_context::<AppState>(cx); | ||
| 44 | + let me = require_role(cx, Need::Viewer).await?; | ||
| 45 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 46 | + let sub = path_param_segment(cx, "sub").to_owned(); | ||
| 47 | + let board = the_board(&state.store).await?; | ||
| 48 | + | ||
| 49 | + // The target must be a member of this board. Anything else is a plain 404. | ||
| 50 | + let target: Member = match state.store.member(&sub).await.map_err(core_err)? { | ||
| 51 | + Some(member) if member.role != iz_core::authz::Role::NoAccess && !member.disabled => member, | ||
| 52 | + _ => return Err(not_found().into()), | ||
| 53 | + }; | ||
| 54 | + if authorize(&me.actor(), &Action::ViewPerson).is_err() { | ||
| 55 | + return Err(not_found().into()); | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + let figures = state | ||
| 59 | + .store | ||
| 60 | + .person_counts(&board.id, &sub) | ||
| 61 | + .await | ||
| 62 | + .map_err(core_err)?; | ||
| 63 | + let filter = ActivityFilter { | ||
| 64 | + actor: Some(sub.clone()), | ||
| 65 | + ..ActivityFilter::default() | ||
| 66 | + }; | ||
| 67 | + let feed = state | ||
| 68 | + .store | ||
| 69 | + .list_recent(&board.id, &filter, None, RECENT_ROWS) | ||
| 70 | + .await | ||
| 71 | + .map_err(core_err)?; | ||
| 72 | + let zone = parse_zone(&me.member.zoneinfo).unwrap_or(jiff::tz::TimeZone::UTC); | ||
| 73 | + let recent: Vec<(String, String, String)> = feed | ||
| 74 | + .items | ||
| 75 | + .iter() | ||
| 76 | + .map(|item| { | ||
| 77 | + ( | ||
| 78 | + local_text(&item.at, &zone), | ||
| 79 | + activity_kind(language, &item.kind).to_owned(), | ||
| 80 | + item.subject.clone().unwrap_or_default(), | ||
| 81 | + ) | ||
| 82 | + }) | ||
| 83 | + .collect(); | ||
| 84 | + let counts: Vec<(&'static str, String)> = vec![ | ||
| 85 | + (t(language, K::PersonOpen), figures.open.to_string()), | ||
| 86 | + (t(language, K::PersonDone), figures.done.to_string()), | ||
| 87 | + (t(language, K::PersonCreated), figures.created.to_string()), | ||
| 88 | + (t(language, K::PersonComments), figures.comments.to_string()), | ||
| 89 | + (t(language, K::PersonFiles), figures.files.to_string()), | ||
| 90 | + ]; | ||
| 91 | + let last_sign_in = target | ||
| 92 | + .last_sign_in_at | ||
| 93 | + .as_deref() | ||
| 94 | + .map(|stamp| local_text(stamp, &zone)) | ||
| 95 | + .filter(|text| !text.is_empty()) | ||
| 96 | + .unwrap_or_else(|| t(language, K::PersonNeverSignedIn).to_owned()); | ||
| 97 | + let role = role_word(language, target.role.as_str()).to_owned(); | ||
| 98 | + let viewer = ViewerInfo { | ||
| 99 | + name: me.member.name.clone(), | ||
| 100 | + is_admin: authorize(&me.actor(), &Action::Administer).is_ok(), | ||
| 101 | + csrf: me.session.csrf_token.clone(), | ||
| 102 | + }; | ||
| 103 | + let document = view! { | ||
| 104 | + cx => | ||
| 105 | + shell(title: target.name.as_str(), lang: language, | ||
| 106 | + viewer: Some(&viewer), page_script: None, | ||
| 107 | + person_content( | ||
| 108 | + lang: language, | ||
| 109 | + name: target.name.as_str(), | ||
| 110 | + role: role.as_str(), | ||
| 111 | + zone: target.zoneinfo.as_str(), | ||
| 112 | + last_sign_in: last_sign_in.as_str(), | ||
| 113 | + counts: &counts, | ||
| 114 | + recent: &recent, | ||
| 115 | + ) | ||
| 116 | + ) | ||
| 117 | + }; | ||
| 118 | + respond(cx, document).await | ||
| 119 | +} | ||
crates/iz-web/src/pages/rules.rsmodified+50 -4
| @@ -22,6 +22,8 @@ use topcoat::view::view; | |||
| 22 | use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; | 22 | use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; |
| 23 | use crate::i18n::admin::{K, fill, t}; | 23 | use crate::i18n::admin::{K, fill, t}; |
| 24 | use crate::i18n::{Lang, lang}; | 24 | use crate::i18n::{Lang, lang}; |
| 25 | +use crate::live::{AdminSection, Topic}; | ||
| 26 | +use crate::pages::admin::record; | ||
| 25 | use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewer_of}; | 27 | use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewer_of}; |
| 26 | use crate::pages::board::the_board; | 28 | use crate::pages::board::the_board; |
| 27 | use crate::pages::task::core_err; | 29 | use crate::pages::task::core_err; |
| @@ -276,7 +278,19 @@ async fn create_rule(cx: &Cx, form: Option<Form<RuleSubmit>>) -> Result<Response | |||
| 276 | let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | 278 | let me = require_csrf(cx, Need::Admin, &form.csrf).await?; |
| 277 | let board = the_board(&state.store).await?; | 279 | let board = the_board(&state.store).await?; |
| 278 | match state.store.create_rule(&board.id, &input_of(&form)).await { | 280 | match state.store.create_rule(&board.id, &input_of(&form)).await { |
| 279 | - Ok(_) => back("/rules?notice=rule"), | 281 | + Ok(rule) => { |
| 282 | + record( | ||
| 283 | + state, | ||
| 284 | + &me, | ||
| 285 | + "rule.save", | ||
| 286 | + "rule", | ||
| 287 | + Some(&rule.id), | ||
| 288 | + serde_json::json!({}), | ||
| 289 | + ) | ||
| 290 | + .await; | ||
| 291 | + state.live.bump(&Topic::Admin(AdminSection::Rules)); | ||
| 292 | + back("/rules?notice=rule") | ||
| 293 | + } | ||
| 280 | Err(error) => refused(cx, state, &me, &board.id, &form, None, error).await, | 294 | Err(error) => refused(cx, state, &me, &board.id, &form, None, error).await, |
| 281 | } | 295 | } |
| 282 | } | 296 | } |
| @@ -294,7 +308,19 @@ async fn update_rule(cx: &Cx, form: Option<Form<RuleSubmit>>) -> Result<Response | |||
| 294 | .update_rule(&board.id, &rule_id, &input_of(&form)) | 308 | .update_rule(&board.id, &rule_id, &input_of(&form)) |
| 295 | .await | 309 | .await |
| 296 | { | 310 | { |
| 297 | - Ok(_) => back("/rules?notice=rule"), | 311 | + Ok(rule) => { |
| 312 | + record( | ||
| 313 | + state, | ||
| 314 | + &me, | ||
| 315 | + "rule.save", | ||
| 316 | + "rule", | ||
| 317 | + Some(&rule.id), | ||
| 318 | + serde_json::json!({}), | ||
| 319 | + ) | ||
| 320 | + .await; | ||
| 321 | + state.live.bump(&Topic::Admin(AdminSection::Rules)); | ||
| 322 | + back("/rules?notice=rule") | ||
| 323 | + } | ||
| 298 | Err(error) => refused(cx, state, &me, &board.id, &form, Some(rule_id), error).await, | 324 | Err(error) => refused(cx, state, &me, &board.id, &form, Some(rule_id), error).await, |
| 299 | } | 325 | } |
| 300 | } | 326 | } |
| @@ -305,13 +331,23 @@ async fn set_enabled(cx: &Cx, form: Option<Form<EnabledSubmit>>) -> Result<Respo | |||
| 305 | let state = app_context::<AppState>(cx); | 331 | let state = app_context::<AppState>(cx); |
| 306 | let form = form.map(|Form(form)| form).unwrap_or_default(); | 332 | let form = form.map(|Form(form)| form).unwrap_or_default(); |
| 307 | let rule_id = path_param_segment(cx, "id").to_owned(); | 333 | let rule_id = path_param_segment(cx, "id").to_owned(); |
| 308 | - require_csrf(cx, Need::Admin, &form.csrf).await?; | 334 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; |
| 309 | let board = the_board(&state.store).await?; | 335 | let board = the_board(&state.store).await?; |
| 310 | state | 336 | state |
| 311 | .store | 337 | .store |
| 312 | .set_rule_enabled(&board.id, &rule_id, form.enabled == "1") | 338 | .set_rule_enabled(&board.id, &rule_id, form.enabled == "1") |
| 313 | .await | 339 | .await |
| 314 | .map_err(core_err)?; | 340 | .map_err(core_err)?; |
| 341 | + record( | ||
| 342 | + state, | ||
| 343 | + &me, | ||
| 344 | + "rule.enabled", | ||
| 345 | + "rule", | ||
| 346 | + Some(&rule_id), | ||
| 347 | + serde_json::json!({ "enabled": form.enabled == "1" }), | ||
| 348 | + ) | ||
| 349 | + .await; | ||
| 350 | + state.live.bump(&Topic::Admin(AdminSection::Rules)); | ||
| 315 | back("/rules?notice=rule_switched") | 351 | back("/rules?notice=rule_switched") |
| 316 | } | 352 | } |
| 317 | 353 | ||
| @@ -321,12 +357,22 @@ async fn delete_rule(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> | |||
| 321 | let state = app_context::<AppState>(cx); | 357 | let state = app_context::<AppState>(cx); |
| 322 | let form = form.map(|Form(form)| form).unwrap_or_default(); | 358 | let form = form.map(|Form(form)| form).unwrap_or_default(); |
| 323 | let rule_id = path_param_segment(cx, "id").to_owned(); | 359 | let rule_id = path_param_segment(cx, "id").to_owned(); |
| 324 | - require_csrf(cx, Need::Admin, &form.csrf).await?; | 360 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; |
| 325 | let board = the_board(&state.store).await?; | 361 | let board = the_board(&state.store).await?; |
| 326 | state | 362 | state |
| 327 | .store | 363 | .store |
| 328 | .delete_rule(&board.id, &rule_id) | 364 | .delete_rule(&board.id, &rule_id) |
| 329 | .await | 365 | .await |
| 330 | .map_err(core_err)?; | 366 | .map_err(core_err)?; |
| 367 | + record( | ||
| 368 | + state, | ||
| 369 | + &me, | ||
| 370 | + "rule.delete", | ||
| 371 | + "rule", | ||
| 372 | + Some(&rule_id), | ||
| 373 | + serde_json::json!({}), | ||
| 374 | + ) | ||
| 375 | + .await; | ||
| 376 | + state.live.bump(&Topic::Admin(AdminSection::Rules)); | ||
| 331 | back("/rules?notice=rule_deleted") | 377 | back("/rules?notice=rule_deleted") |
| 332 | } | 378 | } |
crates/iz-web/src/pages/settings.rsmodified+241 -5
| @@ -23,11 +23,19 @@ use topcoat::view::view; | |||
| 23 | use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; | 23 | use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; |
| 24 | use crate::i18n::admin::{K, t}; | 24 | use crate::i18n::admin::{K, t}; |
| 25 | use crate::i18n::{Lang, lang}; | 25 | use crate::i18n::{Lang, lang}; |
| 26 | +use crate::live::{AdminSection, Topic}; | ||
| 26 | use crate::mail; | 27 | use crate::mail; |
| 27 | use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewer_of}; | 28 | use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewer_of}; |
| 29 | +use crate::pages::board::the_board; | ||
| 28 | use crate::state::AppState; | 30 | use crate::state::AppState; |
| 29 | use crate::views::admin::{SenderForm, SettingsView, settings_content}; | 31 | use crate::views::admin::{SenderForm, SettingsView, settings_content}; |
| 32 | +use crate::views::structure::{MemberRow, ServerInfo}; | ||
| 30 | use crate::views::{ViewerInfo, respond, shell}; | 33 | use crate::views::{ViewerInfo, respond, shell}; |
| 34 | +use iz_core::authz::Role; | ||
| 35 | +use iz_core::limits::{ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN}; | ||
| 36 | +use iz_core::store::attachments::{SETTING_EXTENSIONS, SETTING_LIMIT_MIB, parse_extensions}; | ||
| 37 | +use iz_core::store::audit::AuditEntry; | ||
| 38 | +use topcoat::router::path_param_segment; | ||
| 31 | 39 | ||
| 32 | /// The sender form as posted. | 40 | /// The sender form as posted. |
| 33 | #[derive(Debug, Default, Deserialize)] | 41 | #[derive(Debug, Default, Deserialize)] |
| @@ -95,6 +103,23 @@ async fn settings_view( | |||
| 95 | let reminders: ReminderSettings = state.store.reminder_settings().await?; | 103 | let reminders: ReminderSettings = state.store.reminder_settings().await?; |
| 96 | let mut sender = form.unwrap_or_else(|| sender_form(&stored)); | 104 | let mut sender = form.unwrap_or_else(|| sender_form(&stored)); |
| 97 | sender.password_set = stored.password_set; | 105 | sender.password_set = stored.password_set; |
| 106 | + let policy = state.store.policy().await?; | ||
| 107 | + let members = state | ||
| 108 | + .store | ||
| 109 | + .list_members() | ||
| 110 | + .await? | ||
| 111 | + .into_iter() | ||
| 112 | + .map(|m| MemberRow { | ||
| 113 | + sub: m.sub, | ||
| 114 | + name: m.name, | ||
| 115 | + email: m.email, | ||
| 116 | + role: m.role.as_str().to_owned(), | ||
| 117 | + im_admin: m.im_admin, | ||
| 118 | + disabled: m.disabled, | ||
| 119 | + }) | ||
| 120 | + .collect(); | ||
| 121 | + let limit_mib = (policy.limit_bytes / (1024 * 1024)).to_string(); | ||
| 122 | + let extensions = policy.extensions.join(" "); | ||
| 98 | Ok(SettingsView { | 123 | Ok(SettingsView { |
| 99 | lang, | 124 | lang, |
| 100 | configured: stored.sender.is_some(), | 125 | configured: stored.sender.is_some(), |
| @@ -103,9 +128,44 @@ async fn settings_view( | |||
| 103 | reminder_cap: reminders.hourly_cap, | 128 | reminder_cap: reminders.hourly_cap, |
| 104 | notice, | 129 | notice, |
| 105 | alert, | 130 | alert, |
| 131 | + members, | ||
| 132 | + limit_mib, | ||
| 133 | + extensions, | ||
| 134 | + server: server_info(state).await?, | ||
| 135 | + }) | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +/// The read-only server facts of the settings page. | ||
| 139 | +async fn server_info(state: &AppState) -> Result<ServerInfo> { | ||
| 140 | + Ok(ServerInfo { | ||
| 141 | + base_url: state.config.base_url.clone(), | ||
| 142 | + listen: state.config.listen.to_string(), | ||
| 143 | + data_dir: state.config.data_dir.display().to_string(), | ||
| 144 | + database: state.config.database.display().to_string(), | ||
| 145 | + schema: state.store.schema_version().await?, | ||
| 146 | + build: env!("IZ_BUILD_SHA").to_owned(), | ||
| 147 | + sign_in: state.oidc.is_some(), | ||
| 148 | + storage_in: state.config.in_store.enabled, | ||
| 106 | }) | 149 | }) |
| 107 | } | 150 | } |
| 108 | 151 | ||
| 152 | +/// The members-and-roles form: the role word of one member. | ||
| 153 | +#[derive(Debug, Default, Deserialize)] | ||
| 154 | +#[serde(default)] | ||
| 155 | +struct RoleSubmit { | ||
| 156 | + csrf: String, | ||
| 157 | + role: String, | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +/// The limits form: the attachment size in MiB and the allowed extensions. | ||
| 161 | +#[derive(Debug, Default, Deserialize)] | ||
| 162 | +#[serde(default)] | ||
| 163 | +struct LimitsSubmit { | ||
| 164 | + csrf: String, | ||
| 165 | + limit_mib: String, | ||
| 166 | + extensions: String, | ||
| 167 | +} | ||
| 168 | + | ||
| 109 | /// Renders the settings page with `status`. The CSRF token of the session goes in every form. | 169 | /// Renders the settings page with `status`. The CSRF token of the session goes in every form. |
| 110 | async fn render( | 170 | async fn render( |
| 111 | cx: &Cx, | 171 | cx: &Cx, |
| @@ -176,7 +236,22 @@ async fn save_sender(cx: &Cx, form: Option<Form<SenderSubmit>>) -> Result<Respon | |||
| 176 | } | 236 | } |
| 177 | .await; | 237 | .await; |
| 178 | match outcome { | 238 | match outcome { |
| 179 | - Ok(()) => back("/settings?notice=sender"), | 239 | + Ok(()) => { |
| 240 | + state | ||
| 241 | + .store | ||
| 242 | + .audit(AuditEntry { | ||
| 243 | + actor: Some(&me.member.sub), | ||
| 244 | + actor_kind: "admin", | ||
| 245 | + action: "sender.save", | ||
| 246 | + target_kind: "settings", | ||
| 247 | + target_id: None, | ||
| 248 | + ip: None, | ||
| 249 | + data: serde_json::json!({}), | ||
| 250 | + }) | ||
| 251 | + .await; | ||
| 252 | + state.live.bump(&Topic::Admin(AdminSection::Settings)); | ||
| 253 | + back("/settings?notice=sender") | ||
| 254 | + } | ||
| 180 | Err(error) => { | 255 | Err(error) => { |
| 181 | let message = user_text(error)?; | 256 | let message = user_text(error)?; |
| 182 | let page = settings_view(state, language, Some(typed), None, Some(message)).await?; | 257 | let page = settings_view(state, language, Some(typed), None, Some(message)).await?; |
| @@ -193,7 +268,22 @@ async fn check_sender(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> | |||
| 193 | let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | 268 | let me = require_csrf(cx, Need::Admin, &form.csrf).await?; |
| 194 | let language = lang(cx, me.member.locale_override.as_deref()); | 269 | let language = lang(cx, me.member.locale_override.as_deref()); |
| 195 | match mail::check(state).await { | 270 | match mail::check(state).await { |
| 196 | - Ok(()) => back("/settings?notice=checked"), | 271 | + Ok(()) => { |
| 272 | + state | ||
| 273 | + .store | ||
| 274 | + .audit(AuditEntry { | ||
| 275 | + actor: Some(&me.member.sub), | ||
| 276 | + actor_kind: "admin", | ||
| 277 | + action: "sender.check", | ||
| 278 | + target_kind: "settings", | ||
| 279 | + target_id: None, | ||
| 280 | + ip: None, | ||
| 281 | + data: serde_json::json!({}), | ||
| 282 | + }) | ||
| 283 | + .await; | ||
| 284 | + state.live.bump(&Topic::Admin(AdminSection::Settings)); | ||
| 285 | + back("/settings?notice=checked") | ||
| 286 | + } | ||
| 197 | Err(error) => { | 287 | Err(error) => { |
| 198 | let message = user_text(error)?; | 288 | let message = user_text(error)?; |
| 199 | let page = settings_view(state, language, None, None, Some(message)).await?; | 289 | let page = settings_view(state, language, None, None, Some(message)).await?; |
| @@ -214,7 +304,22 @@ async fn send_test(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> { | |||
| 214 | me.member.locale.as_deref(), | 304 | me.member.locale.as_deref(), |
| 215 | ); | 305 | ); |
| 216 | match mail::send_test(state, &me.member.name, &me.member.email, mail_lang).await { | 306 | match mail::send_test(state, &me.member.name, &me.member.email, mail_lang).await { |
| 217 | - Ok(()) => back("/settings?notice=test"), | 307 | + Ok(()) => { |
| 308 | + state | ||
| 309 | + .store | ||
| 310 | + .audit(AuditEntry { | ||
| 311 | + actor: Some(&me.member.sub), | ||
| 312 | + actor_kind: "admin", | ||
| 313 | + action: "sender.test", | ||
| 314 | + target_kind: "settings", | ||
| 315 | + target_id: None, | ||
| 316 | + ip: None, | ||
| 317 | + data: serde_json::json!({}), | ||
| 318 | + }) | ||
| 319 | + .await; | ||
| 320 | + state.live.bump(&Topic::Admin(AdminSection::Settings)); | ||
| 321 | + back("/settings?notice=test") | ||
| 322 | + } | ||
| 218 | Err(error) => { | 323 | Err(error) => { |
| 219 | let message = user_text(error)?; | 324 | let message = user_text(error)?; |
| 220 | let page = settings_view(state, language, None, None, Some(message)).await?; | 325 | let page = settings_view(state, language, None, None, Some(message)).await?; |
| @@ -249,7 +354,22 @@ async fn save_reminders(cx: &Cx, form: Option<Form<RemindersSubmit>>) -> Result< | |||
| 249 | } | 354 | } |
| 250 | .await; | 355 | .await; |
| 251 | match outcome { | 356 | match outcome { |
| 252 | - Ok(()) => back("/settings?notice=reminders"), | 357 | + Ok(()) => { |
| 358 | + state | ||
| 359 | + .store | ||
| 360 | + .audit(AuditEntry { | ||
| 361 | + actor: Some(&me.member.sub), | ||
| 362 | + actor_kind: "admin", | ||
| 363 | + action: "reminders.save", | ||
| 364 | + target_kind: "settings", | ||
| 365 | + target_id: None, | ||
| 366 | + ip: None, | ||
| 367 | + data: serde_json::json!({}), | ||
| 368 | + }) | ||
| 369 | + .await; | ||
| 370 | + state.live.bump(&Topic::Admin(AdminSection::Settings)); | ||
| 371 | + back("/settings?notice=reminders") | ||
| 372 | + } | ||
| 253 | Err(error) => { | 373 | Err(error) => { |
| 254 | let message = user_text(error)?; | 374 | let message = user_text(error)?; |
| 255 | let page = settings_view(state, language, None, None, Some(message)).await?; | 375 | let page = settings_view(state, language, None, None, Some(message)).await?; |
| @@ -271,7 +391,123 @@ async fn send_message(cx: &Cx, form: Option<Form<MessageSubmit>>) -> Result<Resp | |||
| 271 | .queue_message(&me.member.sub, &form.subject, &form.body, Timestamp::now()) | 391 | .queue_message(&me.member.sub, &form.subject, &form.body, Timestamp::now()) |
| 272 | .await; | 392 | .await; |
| 273 | match outcome { | 393 | match outcome { |
| 274 | - Ok(count) => back(&format!("/settings?notice=message&queued={count}")), | 394 | + Ok(count) => { |
| 395 | + state | ||
| 396 | + .store | ||
| 397 | + .audit(AuditEntry { | ||
| 398 | + actor: Some(&me.member.sub), | ||
| 399 | + actor_kind: "admin", | ||
| 400 | + action: "message.queue", | ||
| 401 | + target_kind: "settings", | ||
| 402 | + target_id: None, | ||
| 403 | + ip: None, | ||
| 404 | + data: serde_json::json!({}), | ||
| 405 | + }) | ||
| 406 | + .await; | ||
| 407 | + state.live.bump(&Topic::Admin(AdminSection::Settings)); | ||
| 408 | + back(&format!("/settings?notice=message&queued={count}")) | ||
| 409 | + } | ||
| 410 | + Err(error) => { | ||
| 411 | + let message = user_text(error)?; | ||
| 412 | + let page = settings_view(state, language, None, None, Some(message)).await?; | ||
| 413 | + render(cx, &me, page, REFUSED).await | ||
| 414 | + } | ||
| 415 | + } | ||
| 416 | +} | ||
| 417 | + | ||
| 418 | +/// `POST /settings/members/{sub}/role`: sets a member's role. The store refuses to demote the last | ||
| 419 | +/// administrator, and a viewer or none loses their assignments. | ||
| 420 | +#[route(POST "/settings/members/{sub}/role")] | ||
| 421 | +async fn save_role(cx: &Cx, form: Option<Form<RoleSubmit>>) -> Result<Response> { | ||
| 422 | + let state = app_context::<AppState>(cx); | ||
| 423 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 424 | + let target = path_param_segment(cx, "sub").to_owned(); | ||
| 425 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 426 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 427 | + let outcome: iz_core::Result<()> = async { | ||
| 428 | + let role = Role::parse(&form.role) | ||
| 429 | + .ok_or_else(|| iz_core::Error::Invalid("unknown role".into()))?; | ||
| 430 | + state.store.set_role(&target, role).await | ||
| 431 | + } | ||
| 432 | + .await; | ||
| 433 | + match outcome { | ||
| 434 | + Ok(()) => { | ||
| 435 | + state | ||
| 436 | + .store | ||
| 437 | + .audit(AuditEntry { | ||
| 438 | + actor: Some(&me.member.sub), | ||
| 439 | + actor_kind: "admin", | ||
| 440 | + action: "role.set", | ||
| 441 | + target_kind: "member", | ||
| 442 | + target_id: Some(&target), | ||
| 443 | + ip: None, | ||
| 444 | + data: serde_json::json!({ "role": form.role }), | ||
| 445 | + }) | ||
| 446 | + .await; | ||
| 447 | + state.live.bump(&Topic::Admin(AdminSection::Members)); | ||
| 448 | + state.live.bump(&Topic::Person(target.clone())); | ||
| 449 | + state | ||
| 450 | + .live | ||
| 451 | + .bump(&Topic::Board(the_board(&state.store).await?.id)); | ||
| 452 | + back("/settings?notice=role_set") | ||
| 453 | + } | ||
| 454 | + Err(error) => { | ||
| 455 | + let message = user_text(error)?; | ||
| 456 | + let page = settings_view(state, language, None, None, Some(message)).await?; | ||
| 457 | + render(cx, &me, page, REFUSED).await | ||
| 458 | + } | ||
| 459 | + } | ||
| 460 | +} | ||
| 461 | + | ||
| 462 | +/// `POST /settings/limits`: the attachment size (1 to 500 MiB) and the allowed extensions. | ||
| 463 | +#[route(POST "/settings/limits")] | ||
| 464 | +async fn save_limits(cx: &Cx, form: Option<Form<LimitsSubmit>>) -> Result<Response> { | ||
| 465 | + let state = app_context::<AppState>(cx); | ||
| 466 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 467 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 468 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 469 | + let outcome: iz_core::Result<()> = async { | ||
| 470 | + let mib = form | ||
| 471 | + .limit_mib | ||
| 472 | + .trim() | ||
| 473 | + .parse::<u32>() | ||
| 474 | + .ok() | ||
| 475 | + .filter(|mib| (ATTACHMENT_LIMIT_MIB_MIN..=ATTACHMENT_LIMIT_MIB_MAX).contains(mib)) | ||
| 476 | + .ok_or_else(|| { | ||
| 477 | + iz_core::Error::Invalid(format!( | ||
| 478 | + "the size limit must be {ATTACHMENT_LIMIT_MIB_MIN} to {ATTACHMENT_LIMIT_MIB_MAX} MiB" | ||
| 479 | + )) | ||
| 480 | + })?; | ||
| 481 | + let extensions = parse_extensions(&form.extensions); | ||
| 482 | + if extensions.is_empty() { | ||
| 483 | + return Err(iz_core::Error::Invalid( | ||
| 484 | + "at least one extension must be allowed".into(), | ||
| 485 | + )); | ||
| 486 | + } | ||
| 487 | + state.store.set_setting(SETTING_LIMIT_MIB, &mib.to_string()).await?; | ||
| 488 | + state | ||
| 489 | + .store | ||
| 490 | + .set_setting(SETTING_EXTENSIONS, &extensions.join(" ")) | ||
| 491 | + .await | ||
| 492 | + } | ||
| 493 | + .await; | ||
| 494 | + match outcome { | ||
| 495 | + Ok(()) => { | ||
| 496 | + state | ||
| 497 | + .store | ||
| 498 | + .audit(AuditEntry { | ||
| 499 | + actor: Some(&me.member.sub), | ||
| 500 | + actor_kind: "admin", | ||
| 501 | + action: "limits.save", | ||
| 502 | + target_kind: "settings", | ||
| 503 | + target_id: None, | ||
| 504 | + ip: None, | ||
| 505 | + data: serde_json::json!({}), | ||
| 506 | + }) | ||
| 507 | + .await; | ||
| 508 | + state.live.bump(&Topic::Admin(AdminSection::Settings)); | ||
| 509 | + back("/settings?notice=limits") | ||
| 510 | + } | ||
| 275 | Err(error) => { | 511 | Err(error) => { |
| 276 | let message = user_text(error)?; | 512 | let message = user_text(error)?; |
| 277 | let page = settings_view(state, language, None, None, Some(message)).await?; | 513 | let page = settings_view(state, language, None, None, Some(message)).await?; |
crates/iz-web/src/pages/tags.rsadded+323 -0
| @@ -0,0 +1,323 @@ | |||
| 1 | +//! The projects page (`GET /tags` and its POSTs): add, rename, colour from the fixed palette, move and | ||
| 2 | +//! delete. Administrators only; a non-administrator gets `404` (see `auth::require_role`). Every write | ||
| 3 | +//! checks the CSRF token before any side effect, bumps the board and admin-structure live topics after it | ||
| 4 | +//! commits, and writes one audit row. A project in use is refused by the store with a message. | ||
| 5 | + | ||
| 6 | +use iz_core::store::audit::AuditEntry; | ||
| 7 | +use iz_core::store::board::Direction; | ||
| 8 | +use iz_core::store::board::{TAG_COLOURS, Tag}; | ||
| 9 | +use serde::Deserialize; | ||
| 10 | +use topcoat::Result; | ||
| 11 | +use topcoat::context::{Cx, app_context}; | ||
| 12 | +use topcoat::router::content::Form; | ||
| 13 | +use topcoat::router::response::Response; | ||
| 14 | +use topcoat::router::{StatusCode, path_param_segment, route}; | ||
| 15 | +use topcoat::view::view; | ||
| 16 | + | ||
| 17 | +use crate::auth::{CurrentMember, Need, query_param, require_csrf, require_role}; | ||
| 18 | +use crate::i18n::structure::{K, t}; | ||
| 19 | +use crate::i18n::{Lang, lang}; | ||
| 20 | +use crate::live::{AdminSection, Topic}; | ||
| 21 | +use crate::pages::admin::{REFUSED, back, user_text, viewer_of}; | ||
| 22 | +use crate::pages::board::the_board; | ||
| 23 | +use crate::pages::task::core_err; | ||
| 24 | +use crate::state::AppState; | ||
| 25 | +use crate::views::structure::{TagRow, TagsView, tags_content}; | ||
| 26 | +use crate::views::{ViewerInfo, respond, shell}; | ||
| 27 | + | ||
| 28 | +/// The add-project form. | ||
| 29 | +#[derive(Debug, Default, Deserialize)] | ||
| 30 | +#[serde(default)] | ||
| 31 | +struct AddSubmit { | ||
| 32 | + csrf: String, | ||
| 33 | + name: String, | ||
| 34 | + colour: String, | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// The rename form. | ||
| 38 | +#[derive(Debug, Default, Deserialize)] | ||
| 39 | +#[serde(default)] | ||
| 40 | +struct RenameSubmit { | ||
| 41 | + csrf: String, | ||
| 42 | + name: String, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// The colour form. An empty value clears the colour. | ||
| 46 | +#[derive(Debug, Default, Deserialize)] | ||
| 47 | +#[serde(default)] | ||
| 48 | +struct ColourSubmit { | ||
| 49 | + csrf: String, | ||
| 50 | + colour: String, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// The move form: `up` or `down`. | ||
| 54 | +#[derive(Debug, Default, Deserialize)] | ||
| 55 | +#[serde(default)] | ||
| 56 | +struct MoveSubmit { | ||
| 57 | + csrf: String, | ||
| 58 | + direction: String, | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// The page's data: every project with its usage, and the palette. | ||
| 62 | +async fn tags_page( | ||
| 63 | + state: &AppState, | ||
| 64 | + lang: Lang, | ||
| 65 | + notice: Option<String>, | ||
| 66 | + alert: Option<String>, | ||
| 67 | +) -> Result<TagsView> { | ||
| 68 | + let board = the_board(&state.store).await?; | ||
| 69 | + let tags: Vec<Tag> = state.store.tags(&board.id).await.map_err(core_err)?; | ||
| 70 | + let usage = state.store.tag_usage(&board.id).await.map_err(core_err)?; | ||
| 71 | + let rows = tags | ||
| 72 | + .into_iter() | ||
| 73 | + .map(|tag| TagRow { | ||
| 74 | + uses: usage | ||
| 75 | + .iter() | ||
| 76 | + .find(|(id, _)| *id == tag.id) | ||
| 77 | + .map_or(0, |(_, count)| *count), | ||
| 78 | + id: tag.id, | ||
| 79 | + name: tag.name, | ||
| 80 | + colour: tag.color, | ||
| 81 | + is_default: tag.is_default, | ||
| 82 | + }) | ||
| 83 | + .collect(); | ||
| 84 | + Ok(TagsView { | ||
| 85 | + lang, | ||
| 86 | + tags: rows, | ||
| 87 | + palette: palette(), | ||
| 88 | + notice, | ||
| 89 | + alert, | ||
| 90 | + }) | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// The palette names, `c0` to `c7`. | ||
| 94 | +fn palette() -> Vec<String> { | ||
| 95 | + (0..TAG_COLOURS).map(|n| format!("c{n}")).collect() | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// The notice text of a project redirect. Unknown codes give `None`. | ||
| 99 | +pub fn tag_notice(lang: Lang, code: &str) -> Option<String> { | ||
| 100 | + let text = match code { | ||
| 101 | + "tag_added" => t(lang, K::NoticeTagAdded), | ||
| 102 | + "tag_renamed" => t(lang, K::NoticeTagRenamed), | ||
| 103 | + "tag_coloured" => t(lang, K::NoticeTagColoured), | ||
| 104 | + "tag_deleted" => t(lang, K::NoticeTagDeleted), | ||
| 105 | + "tag_moved" => t(lang, K::NoticeTagMoved), | ||
| 106 | + _ => return None, | ||
| 107 | + }; | ||
| 108 | + Some(text.to_owned()) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// Renders the projects page with `status` and the CSRF token of the session. | ||
| 112 | +async fn render( | ||
| 113 | + cx: &Cx, | ||
| 114 | + me: &CurrentMember, | ||
| 115 | + page: TagsView, | ||
| 116 | + status: StatusCode, | ||
| 117 | +) -> Result<Response> { | ||
| 118 | + let lang = page.lang; | ||
| 119 | + let viewer: ViewerInfo = viewer_of(me); | ||
| 120 | + let csrf = me.session.csrf_token.clone(); | ||
| 121 | + let document = view! { | ||
| 122 | + cx => | ||
| 123 | + (status) | ||
| 124 | + shell(title: t(lang, K::TagsTitle), lang: lang, | ||
| 125 | + viewer: Some(&viewer), page_script: None, | ||
| 126 | + tags_content(page: &page, csrf: csrf.as_str()) | ||
| 127 | + ) | ||
| 128 | + }; | ||
| 129 | + respond(cx, document).await | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +/// Bumps what a structure write changes: the board (cards show projects) and the admin section. | ||
| 133 | +fn bump_structure(state: &AppState, board_id: &str) { | ||
| 134 | + state.live.bump(&Topic::Board(board_id.to_owned())); | ||
| 135 | + state.live.bump(&Topic::Admin(AdminSection::Structure)); | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +/// `GET /tags`. Administrators only. | ||
| 139 | +#[route(GET "/tags")] | ||
| 140 | +async fn tags_get(cx: &Cx) -> Result<Response> { | ||
| 141 | + let state = app_context::<AppState>(cx); | ||
| 142 | + let me = require_role(cx, Need::Admin).await?; | ||
| 143 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 144 | + let notice = query_param(cx, "notice").and_then(|code| tag_notice(language, &code)); | ||
| 145 | + let page = tags_page(state, language, notice, None).await?; | ||
| 146 | + render(cx, &me, page, StatusCode::OK).await | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// `POST /tags`: adds a project at the end. | ||
| 150 | +#[route(POST "/tags")] | ||
| 151 | +async fn add_tag(cx: &Cx, form: Option<Form<AddSubmit>>) -> Result<Response> { | ||
| 152 | + let state = app_context::<AppState>(cx); | ||
| 153 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 154 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 155 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 156 | + let board = the_board(&state.store).await?; | ||
| 157 | + let colour = (!form.colour.is_empty()).then_some(form.colour.as_str()); | ||
| 158 | + let outcome = state.store.add_tag(&board.id, &form.name, colour).await; | ||
| 159 | + match outcome { | ||
| 160 | + Ok(tag) => { | ||
| 161 | + state | ||
| 162 | + .store | ||
| 163 | + .audit(AuditEntry { | ||
| 164 | + actor: Some(&me.member.sub), | ||
| 165 | + actor_kind: "admin", | ||
| 166 | + action: "tag.add", | ||
| 167 | + target_kind: "tag", | ||
| 168 | + target_id: Some(&tag.id), | ||
| 169 | + ip: None, | ||
| 170 | + data: serde_json::json!({ "name": tag.name }), | ||
| 171 | + }) | ||
| 172 | + .await; | ||
| 173 | + bump_structure(state, &board.id); | ||
| 174 | + back("/tags?notice=tag_added") | ||
| 175 | + } | ||
| 176 | + Err(error) => { | ||
| 177 | + let message = user_text(error)?; | ||
| 178 | + let page = tags_page(state, language, None, Some(message)).await?; | ||
| 179 | + render(cx, &me, page, REFUSED).await | ||
| 180 | + } | ||
| 181 | + } | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +/// `POST /tags/{id}/rename`. | ||
| 185 | +#[route(POST "/tags/{id}/rename")] | ||
| 186 | +async fn rename_tag(cx: &Cx, form: Option<Form<RenameSubmit>>) -> Result<Response> { | ||
| 187 | + let state = app_context::<AppState>(cx); | ||
| 188 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 189 | + let tag_id = path_param_segment(cx, "id").to_owned(); | ||
| 190 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 191 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 192 | + let board = the_board(&state.store).await?; | ||
| 193 | + match state.store.rename_tag(&board.id, &tag_id, &form.name).await { | ||
| 194 | + Ok(()) => { | ||
| 195 | + state | ||
| 196 | + .store | ||
| 197 | + .audit(AuditEntry { | ||
| 198 | + actor: Some(&me.member.sub), | ||
| 199 | + actor_kind: "admin", | ||
| 200 | + action: "tag.rename", | ||
| 201 | + target_kind: "tag", | ||
| 202 | + target_id: Some(&tag_id), | ||
| 203 | + ip: None, | ||
| 204 | + data: serde_json::json!({ "name": form.name.trim() }), | ||
| 205 | + }) | ||
| 206 | + .await; | ||
| 207 | + bump_structure(state, &board.id); | ||
| 208 | + back("/tags?notice=tag_renamed") | ||
| 209 | + } | ||
| 210 | + Err(error) => { | ||
| 211 | + let message = user_text(error)?; | ||
| 212 | + let page = tags_page(state, language, None, Some(message)).await?; | ||
| 213 | + render(cx, &me, page, REFUSED).await | ||
| 214 | + } | ||
| 215 | + } | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +/// `POST /tags/{id}/colour`: sets a colour from the palette, or clears it. | ||
| 219 | +#[route(POST "/tags/{id}/colour")] | ||
| 220 | +async fn colour_tag(cx: &Cx, form: Option<Form<ColourSubmit>>) -> Result<Response> { | ||
| 221 | + let state = app_context::<AppState>(cx); | ||
| 222 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 223 | + let tag_id = path_param_segment(cx, "id").to_owned(); | ||
| 224 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 225 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 226 | + let board = the_board(&state.store).await?; | ||
| 227 | + let colour = (!form.colour.is_empty()).then_some(form.colour.as_str()); | ||
| 228 | + match state.store.set_tag_colour(&board.id, &tag_id, colour).await { | ||
| 229 | + Ok(()) => { | ||
| 230 | + state | ||
| 231 | + .store | ||
| 232 | + .audit(AuditEntry { | ||
| 233 | + actor: Some(&me.member.sub), | ||
| 234 | + actor_kind: "admin", | ||
| 235 | + action: "tag.colour", | ||
| 236 | + target_kind: "tag", | ||
| 237 | + target_id: Some(&tag_id), | ||
| 238 | + ip: None, | ||
| 239 | + data: serde_json::json!({ "colour": colour }), | ||
| 240 | + }) | ||
| 241 | + .await; | ||
| 242 | + bump_structure(state, &board.id); | ||
| 243 | + back("/tags?notice=tag_coloured") | ||
| 244 | + } | ||
| 245 | + Err(error) => { | ||
| 246 | + let message = user_text(error)?; | ||
| 247 | + let page = tags_page(state, language, None, Some(message)).await?; | ||
| 248 | + render(cx, &me, page, REFUSED).await | ||
| 249 | + } | ||
| 250 | + } | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +/// `POST /tags/{id}/move`: one place earlier or later. | ||
| 254 | +#[route(POST "/tags/{id}/move")] | ||
| 255 | +async fn move_tag(cx: &Cx, form: Option<Form<MoveSubmit>>) -> Result<Response> { | ||
| 256 | + let state = app_context::<AppState>(cx); | ||
| 257 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 258 | + let tag_id = path_param_segment(cx, "id").to_owned(); | ||
| 259 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 260 | + let board = the_board(&state.store).await?; | ||
| 261 | + let direction = match form.direction.as_str() { | ||
| 262 | + "up" => Direction::Up, | ||
| 263 | + "down" => Direction::Down, | ||
| 264 | + _ => { | ||
| 265 | + return Err(core_err(iz_core::Error::Invalid( | ||
| 266 | + "unknown direction".into(), | ||
| 267 | + ))); | ||
| 268 | + } | ||
| 269 | + }; | ||
| 270 | + state | ||
| 271 | + .store | ||
| 272 | + .move_tag(&board.id, &tag_id, direction) | ||
| 273 | + .await | ||
| 274 | + .map_err(core_err)?; | ||
| 275 | + state | ||
| 276 | + .store | ||
| 277 | + .audit(AuditEntry { | ||
| 278 | + actor: Some(&me.member.sub), | ||
| 279 | + actor_kind: "admin", | ||
| 280 | + action: "tag.move", | ||
| 281 | + target_kind: "tag", | ||
| 282 | + target_id: Some(&tag_id), | ||
| 283 | + ip: None, | ||
| 284 | + data: serde_json::json!({ "direction": form.direction }), | ||
| 285 | + }) | ||
| 286 | + .await; | ||
| 287 | + bump_structure(state, &board.id); | ||
| 288 | + back("/tags?notice=tag_moved") | ||
| 289 | +} | ||
| 290 | + | ||
| 291 | +/// `POST /tags/{id}/delete`: refused by the store while any card is in the project. | ||
| 292 | +#[route(POST "/tags/{id}/delete")] | ||
| 293 | +async fn delete_tag(cx: &Cx, form: Option<Form<ColourSubmit>>) -> Result<Response> { | ||
| 294 | + let state = app_context::<AppState>(cx); | ||
| 295 | + let form = form.map(|Form(form)| form).unwrap_or_default(); | ||
| 296 | + let tag_id = path_param_segment(cx, "id").to_owned(); | ||
| 297 | + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; | ||
| 298 | + let language = lang(cx, me.member.locale_override.as_deref()); | ||
| 299 | + let board = the_board(&state.store).await?; | ||
| 300 | + match state.store.delete_tag(&board.id, &tag_id).await { | ||
| 301 | + Ok(()) => { | ||
| 302 | + state | ||
| 303 | + .store | ||
| 304 | + .audit(AuditEntry { | ||
| 305 | + actor: Some(&me.member.sub), | ||
| 306 | + actor_kind: "admin", | ||
| 307 | + action: "tag.delete", | ||
| 308 | + target_kind: "tag", | ||
| 309 | + target_id: Some(&tag_id), | ||
| 310 | + ip: None, | ||
| 311 | + data: serde_json::json!({}), | ||
| 312 | + }) | ||
| 313 | + .await; | ||
| 314 | + bump_structure(state, &board.id); | ||
| 315 | + back("/tags?notice=tag_deleted") | ||
| 316 | + } | ||
| 317 | + Err(error) => { | ||
| 318 | + let message = user_text(error)?; | ||
| 319 | + let page = tags_page(state, language, None, Some(message)).await?; | ||
| 320 | + render(cx, &me, page, REFUSED).await | ||
| 321 | + } | ||
| 322 | + } | ||
| 323 | +} | ||
crates/iz-web/src/pages/task.rsmodified+8 -1
| @@ -662,11 +662,17 @@ async fn assign(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> { | |||
| 662 | } | 662 | } |
| 663 | match state | 663 | match state |
| 664 | .store | 664 | .store |
| 665 | - .assign(&begun.board_id, &task_id, &[sub], &begun.me.member.sub) | 665 | + .assign( |
| 666 | + &begun.board_id, | ||
| 667 | + &task_id, | ||
| 668 | + std::slice::from_ref(&sub), | ||
| 669 | + &begun.me.member.sub, | ||
| 670 | + ) | ||
| 666 | .await | 671 | .await |
| 667 | { | 672 | { |
| 668 | Ok(()) => { | 673 | Ok(()) => { |
| 669 | bump(state, &begun.board_id, &task_id); | 674 | bump(state, &begun.board_id, &task_id); |
| 675 | + state.live.bump(&Topic::Person(sub.clone())); | ||
| 670 | back(&form.next, Some(key.as_str())) | 676 | back(&form.next, Some(key.as_str())) |
| 671 | } | 677 | } |
| 672 | Err(iz_core::Error::Invalid(_)) => { | 678 | Err(iz_core::Error::Invalid(_)) => { |
| @@ -706,6 +712,7 @@ async fn unassign(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> { | |||
| 706 | .await | 712 | .await |
| 707 | .map_err(core_err)?; | 713 | .map_err(core_err)?; |
| 708 | bump(state, &begun.board_id, &task_id); | 714 | bump(state, &begun.board_id, &task_id); |
| 715 | + state.live.bump(&Topic::Person(form.sub.trim().to_owned())); | ||
| 709 | back(&form.next, Some(key.as_str())) | 716 | back(&form.next, Some(key.as_str())) |
| 710 | } | 717 | } |
| 711 | 718 | ||
crates/iz-web/src/state.rsmodified+3 -0
| @@ -5,6 +5,7 @@ use std::sync::Arc; | |||
| 5 | use iz_core::config::Config; | 5 | use iz_core::config::Config; |
| 6 | use iz_core::store::Store; | 6 | use iz_core::store::Store; |
| 7 | 7 | ||
| 8 | +use crate::family::FamilyCache; | ||
| 8 | use crate::live::LiveHub; | 9 | use crate::live::LiveHub; |
| 9 | use crate::oidc::OidcClient; | 10 | use crate::oidc::OidcClient; |
| 10 | 11 | ||
| @@ -22,4 +23,6 @@ pub struct AppState { | |||
| 22 | pub live: Arc<LiveHub>, | 23 | pub live: Arc<LiveHub>, |
| 23 | /// The `im` client. `None` when no `[oidc]` section is configured, so sign-in is off. | 24 | /// The `im` client. `None` when no `[oidc]` section is configured, so sign-in is off. |
| 24 | pub oidc: Option<Arc<OidcClient>>, | 25 | pub oidc: Option<Arc<OidcClient>>, |
| 26 | + /// The family service list that the topbar switcher shows. Filled by the `family` worker. | ||
| 27 | + pub family: Arc<FamilyCache>, | ||
| 25 | } | 28 | } |
crates/iz-web/src/sweeper.rsadded+166 -0
| @@ -0,0 +1,166 @@ | |||
| 1 | +//! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the | ||
| 2 | +//! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the | ||
| 3 | +//! attachment bytes still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass | ||
| 4 | +//! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, and removes staged | ||
| 5 | +//! uploads left in `data_dir/tmp` by a crash. | ||
| 6 | +//! | ||
| 7 | +//! It never deletes live data: pending mail, pending deletions that are not yet due, and sessions that have | ||
| 8 | +//! not expired are left alone. A failed step is logged and the next step still runs. | ||
| 9 | + | ||
| 10 | +use std::future::Future; | ||
| 11 | +use std::path::Path; | ||
| 12 | +use std::time::{Duration, SystemTime}; | ||
| 13 | + | ||
| 14 | +use iz_core::staging::{TMP_DIR, remove_blob}; | ||
| 15 | +use iz_core::store::sweep::RETENTION_DAYS; | ||
| 16 | +use jiff::{SignedDuration, Timestamp}; | ||
| 17 | +use tokio::sync::watch; | ||
| 18 | + | ||
| 19 | +use crate::attachments::retry_delay; | ||
| 20 | +use crate::state::AppState; | ||
| 21 | + | ||
| 22 | +/// How often the sweeper runs after its first pass. Reason: none of this is urgent. | ||
| 23 | +const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60); | ||
| 24 | +/// Rows deleted per statement. Reason: keeps each write short so the writer is not held for long. | ||
| 25 | +const BATCH: i64 = 500; | ||
| 26 | +/// A staged upload older than this is an orphan. Reason: no upload stays in staging for a day. | ||
| 27 | +const TEMP_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60); | ||
| 28 | + | ||
| 29 | +/// Starts the sweeper. It runs at once, then every [`SWEEP_EVERY`], until `stop` is set. | ||
| 30 | +pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) { | ||
| 31 | + tokio::spawn(async move { | ||
| 32 | + loop { | ||
| 33 | + sweep(&state).await; | ||
| 34 | + tokio::select! { | ||
| 35 | + () = tokio::time::sleep(SWEEP_EVERY) => {} | ||
| 36 | + _ = stop.wait_for(|stopped| *stopped) => break, | ||
| 37 | + } | ||
| 38 | + } | ||
| 39 | + tracing::info!("sweeper stopped"); | ||
| 40 | + }); | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// One full run. Each step is independent: a failure is logged and the run goes on. | ||
| 44 | +async fn sweep(state: &AppState) { | ||
| 45 | + note("expired sessions", state.store.sweep_sessions().await); | ||
| 46 | + note("expired logout tokens", state.store.sweep_jti().await); | ||
| 47 | + retry_blob_deletions(state).await; | ||
| 48 | + match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * RETENTION_DAYS)) { | ||
| 49 | + Ok(cutoff) => { | ||
| 50 | + drain("activity", |batch| { | ||
| 51 | + state.store.prune_activity(cutoff, batch) | ||
| 52 | + }) | ||
| 53 | + .await; | ||
| 54 | + drain("mail decisions", |batch| { | ||
| 55 | + state.store.prune_mail_decisions(cutoff, batch) | ||
| 56 | + }) | ||
| 57 | + .await; | ||
| 58 | + drain("finished mail", |batch| { | ||
| 59 | + state.store.prune_mail_outbox(cutoff, batch) | ||
| 60 | + }) | ||
| 61 | + .await; | ||
| 62 | + } | ||
| 63 | + Err(error) => { | ||
| 64 | + tracing::warn!(error = %error, "retention cutoff is out of range; not pruned") | ||
| 65 | + } | ||
| 66 | + } | ||
| 67 | + note( | ||
| 68 | + "stale staged uploads", | ||
| 69 | + remove_stale_temp_files(&state.config.data_dir).await, | ||
| 70 | + ); | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Logs a step's count when it is not zero, and logs a failed step. Returns nothing: a sweep step has no | ||
| 74 | +/// result the caller needs. | ||
| 75 | +fn note(what: &str, result: iz_core::Result<u64>) { | ||
| 76 | + match result { | ||
| 77 | + Ok(0) => {} | ||
| 78 | + Ok(count) => tracing::info!(count, what, "sweeper removed rows"), | ||
| 79 | + Err(error) => tracing::warn!(error = %error, what, "sweeper step failed"), | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// Runs a batched delete until a batch comes back short, a batch fails, or the step runs out of rows. Logs | ||
| 84 | +/// the total when it is not zero. | ||
| 85 | +async fn drain<F, Fut>(what: &str, mut step: F) | ||
| 86 | +where | ||
| 87 | + F: FnMut(i64) -> Fut, | ||
| 88 | + Fut: Future<Output = iz_core::Result<u64>>, | ||
| 89 | +{ | ||
| 90 | + let mut total: u64 = 0; | ||
| 91 | + loop { | ||
| 92 | + match step(BATCH).await { | ||
| 93 | + Ok(deleted) => { | ||
| 94 | + total += deleted; | ||
| 95 | + if deleted < u64::try_from(BATCH).unwrap_or(0) { | ||
| 96 | + break; | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + Err(error) => { | ||
| 100 | + tracing::warn!(error = %error, what, "sweeper batch failed"); | ||
| 101 | + break; | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | + } | ||
| 105 | + note(what, Ok(total)); | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// Retries the attachment bytes that are owed and due. A removal that fails is scheduled again with the | ||
| 109 | +/// same backoff the deleter uses. Returns nothing; the deleter logs its own failures. | ||
| 110 | +async fn retry_blob_deletions(state: &AppState) { | ||
| 111 | + let due = match state.store.due_blob_deletions(BATCH).await { | ||
| 112 | + Ok(due) => due, | ||
| 113 | + Err(error) => { | ||
| 114 | + tracing::warn!(error = %error, "reading the due attachment deletions failed"); | ||
| 115 | + return; | ||
| 116 | + } | ||
| 117 | + }; | ||
| 118 | + let mut removed: u64 = 0; | ||
| 119 | + for (id, attempts) in due { | ||
| 120 | + match remove_blob(&state.config.data_dir, &id).await { | ||
| 121 | + Ok(()) => match state.store.finish_blob_deletion(&id).await { | ||
| 122 | + Ok(()) => removed += 1, | ||
| 123 | + Err(error) => { | ||
| 124 | + tracing::warn!(error = %error, "clearing a finished attachment deletion failed"); | ||
| 125 | + } | ||
| 126 | + }, | ||
| 127 | + Err(error) => { | ||
| 128 | + tracing::warn!(attempts, error = %error, "removing attachment bytes failed; retrying"); | ||
| 129 | + if let Err(error) = state | ||
| 130 | + .store | ||
| 131 | + .defer_blob_deletion(&id, attempts, retry_delay(attempts)) | ||
| 132 | + .await | ||
| 133 | + { | ||
| 134 | + tracing::warn!(error = %error, "scheduling an attachment deletion retry failed"); | ||
| 135 | + } | ||
| 136 | + } | ||
| 137 | + } | ||
| 138 | + } | ||
| 139 | + note("attachment bytes removed", Ok(removed)); | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// Removes regular files in `data_dir/tmp` that were last changed more than [`TEMP_MAX_AGE`] ago. A missing | ||
| 143 | +/// staging directory means there is nothing to remove. Links and directories are left alone. | ||
| 144 | +async fn remove_stale_temp_files(data_dir: &Path) -> iz_core::Result<u64> { | ||
| 145 | + let dir = data_dir.join(TMP_DIR); | ||
| 146 | + let mut entries = match tokio::fs::read_dir(&dir).await { | ||
| 147 | + Ok(entries) => entries, | ||
| 148 | + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0), | ||
| 149 | + Err(error) => return Err(error.into()), | ||
| 150 | + }; | ||
| 151 | + let cutoff = SystemTime::now() | ||
| 152 | + .checked_sub(TEMP_MAX_AGE) | ||
| 153 | + .unwrap_or(SystemTime::UNIX_EPOCH); | ||
| 154 | + let mut removed: u64 = 0; | ||
| 155 | + while let Some(entry) = entries.next_entry().await? { | ||
| 156 | + let meta = entry.metadata().await?; | ||
| 157 | + if !meta.is_file() { | ||
| 158 | + continue; | ||
| 159 | + } | ||
| 160 | + if meta.modified()? < cutoff { | ||
| 161 | + tokio::fs::remove_file(entry.path()).await?; | ||
| 162 | + removed += 1; | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + Ok(removed) | ||
| 166 | +} | ||
crates/iz-web/src/views/admin.rsmodified+25 -0
| @@ -10,7 +10,9 @@ use topcoat::view::{View, component, view}; | |||
| 10 | 10 | ||
| 11 | use crate::i18n::Lang; | 11 | use crate::i18n::Lang; |
| 12 | use crate::i18n::admin::{K, t}; | 12 | use crate::i18n::admin::{K, t}; |
| 13 | +use crate::i18n::structure::{K as StructureK, t as structure_t}; | ||
| 13 | use crate::views::board::flag; | 14 | use crate::views::board::flag; |
| 15 | +use crate::views::structure::{limits_section, members_section, server_section}; | ||
| 14 | use crate::views::{alert, notice}; | 16 | use crate::views::{alert, notice}; |
| 15 | 17 | ||
| 16 | /// The sender form as it is shown. The password is never here, only `password_set`. | 18 | /// The sender form as it is shown. The password is never here, only `password_set`. |
| @@ -126,6 +128,14 @@ pub struct SettingsView { | |||
| 126 | pub notice: Option<String>, | 128 | pub notice: Option<String>, |
| 127 | /// A refusal to show above the page, already translated or a store message. | 129 | /// A refusal to show above the page, already translated or a store message. |
| 128 | pub alert: Option<String>, | 130 | pub alert: Option<String>, |
| 131 | + /// Members and their roles, in name order. | ||
| 132 | + pub members: Vec<crate::views::structure::MemberRow>, | ||
| 133 | + /// The attachment size limit in MiB, as text for the form. | ||
| 134 | + pub limit_mib: String, | ||
| 135 | + /// The allowed attachment extensions, space separated, for the form. | ||
| 136 | + pub extensions: String, | ||
| 137 | + /// Read-only facts about the server. | ||
| 138 | + pub server: crate::views::structure::ServerInfo, | ||
| 129 | } | 139 | } |
| 130 | 140 | ||
| 131 | /// The rules page: the list, the form (new or editing), and the choices of the form. | 141 | /// 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<impl View> { | |||
| 169 | } else { | 179 | } else { |
| 170 | "tab" | 180 | "tab" |
| 171 | }; | 181 | }; |
| 182 | + let tags = if current == "tags" { | ||
| 183 | + "tab current" | ||
| 184 | + } else { | ||
| 185 | + "tab" | ||
| 186 | + }; | ||
| 187 | + let columns = if current == "columns" { | ||
| 188 | + "tab current" | ||
| 189 | + } else { | ||
| 190 | + "tab" | ||
| 191 | + }; | ||
| 172 | Ok(view! { | 192 | Ok(view! { |
| 173 | <nav class="tabs" aria-label=(t(lang, K::SettingsTitle))> | 193 | <nav class="tabs" aria-label=(t(lang, K::SettingsTitle))> |
| 174 | <a class=(settings) href="/settings">(t(lang, K::NavSettings))</a> | 194 | <a class=(settings) href="/settings">(t(lang, K::NavSettings))</a> |
| 195 | + <a class=(tags) href="/tags">(structure_t(lang, StructureK::NavTags))</a> | ||
| 196 | + <a class=(columns) href="/columns">(structure_t(lang, StructureK::NavColumns))</a> | ||
| 175 | <a class=(rules) href="/rules">(t(lang, K::NavRules))</a> | 197 | <a class=(rules) href="/rules">(t(lang, K::NavRules))</a> |
| 176 | <a class=(logs) href="/logs">(t(lang, K::NavLogs))</a> | 198 | <a class=(logs) href="/logs">(t(lang, K::NavLogs))</a> |
| 177 | </nav> | 199 | </nav> |
| @@ -288,6 +310,9 @@ pub async fn settings_content(page: &SettingsView, csrf: &str) -> Result<impl Vi | |||
| 288 | <button class="button" type="submit">(t(lang, K::SendMessage))</button> | 310 | <button class="button" type="submit">(t(lang, K::SendMessage))</button> |
| 289 | </form> | 311 | </form> |
| 290 | </section> | 312 | </section> |
| 313 | + members_section(lang: lang, members: &page.members, csrf: csrf) | ||
| 314 | + limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf) | ||
| 315 | + server_section(lang: lang, info: &page.server) | ||
| 291 | }) | 316 | }) |
| 292 | } | 317 | } |
| 293 | 318 | ||
crates/iz-web/src/views/mod.rsmodified+26 -4
| @@ -4,18 +4,24 @@ | |||
| 4 | //! emits an inline script, style or event handler; see `security.rs`. | 4 | //! emits an inline script, style or event handler; see `security.rs`. |
| 5 | 5 | ||
| 6 | use topcoat::Result; | 6 | use topcoat::Result; |
| 7 | -use topcoat::context::Cx; | 7 | +use topcoat::context::{Cx, app_context}; |
| 8 | use topcoat::router::response::{IntoResponse, Response}; | 8 | use topcoat::router::response::{IntoResponse, Response}; |
| 9 | use topcoat::view::{Child, View, ViewExt, component, view}; | 9 | use topcoat::view::{Child, View, ViewExt, component, view}; |
| 10 | 10 | ||
| 11 | pub mod admin; | 11 | pub mod admin; |
| 12 | pub mod board; | 12 | pub mod board; |
| 13 | pub mod files; | 13 | pub mod files; |
| 14 | +pub mod structure; | ||
| 14 | pub mod task; | 15 | pub mod task; |
| 15 | 16 | ||
| 16 | use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; | 17 | use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; |
| 18 | +use crate::family::Service; | ||
| 17 | use crate::i18n::Lang; | 19 | use crate::i18n::Lang; |
| 18 | use crate::i18n::shell::{K, t}; | 20 | use crate::i18n::shell::{K, t}; |
| 21 | +use crate::state::AppState; | ||
| 22 | + | ||
| 23 | +/// The family key of this app. The switcher marks the service with this key as the current one. | ||
| 24 | +const APP_KEY: &str = "iz"; | ||
| 19 | 25 | ||
| 20 | /// What the shell shows about the signed-in person: the name in the user menu, the administrator | 26 | /// What the shell shows about the signed-in person: the name in the user menu, the administrator |
| 21 | /// badge, and the CSRF token of the sign-out form in that menu. | 27 | /// badge, and the CSRF token of the sign-out form in that menu. |
| @@ -32,10 +38,12 @@ pub struct ViewerInfo { | |||
| 32 | /// app name. `child` is the page, placed in `<main>`. `page_script` is the one script of this page | 38 | /// app name. `child` is the page, placed in `<main>`. `page_script` is the one script of this page |
| 33 | /// (for example `board.js`), or `None`; it is loaded with `defer` and only on the page that needs it. | 39 | /// (for example `board.js`), or `None`; it is loaded with `defer` and only on the page that needs it. |
| 34 | /// | 40 | /// |
| 35 | -/// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and | 41 | +/// The topbar has the wordmark on the left, the service switcher in the middle and the viewer's name |
| 36 | -/// the viewer's name on the right. `nav.js` reads the restart text from `<body data-restart-text>`. | 42 | +/// on the right. The switcher lists the family services from the cache in `AppState`; it is left out |
| 43 | +/// when the list is empty. `nav.js` reads the restart text from `<body data-restart-text>`. | ||
| 37 | #[component] | 44 | #[component] |
| 38 | pub async fn shell( | 45 | pub async fn shell( |
| 46 | + cx: &Cx, | ||
| 39 | title: &str, | 47 | title: &str, |
| 40 | lang: Lang, | 48 | lang: Lang, |
| 41 | viewer: Option<&ViewerInfo>, | 49 | viewer: Option<&ViewerInfo>, |
| @@ -43,6 +51,7 @@ pub async fn shell( | |||
| 43 | #[default] child: Child<'_>, | 51 | #[default] child: Child<'_>, |
| 44 | ) -> Result<impl View> { | 52 | ) -> Result<impl View> { |
| 45 | let document_title = format!("{title} \u{b7} iz"); | 53 | let document_title = format!("{title} \u{b7} iz"); |
| 54 | + let services = app_context::<AppState>(cx).family.snapshot(); | ||
| 46 | Ok(view! { | 55 | Ok(view! { |
| 47 | <!DOCTYPE html> | 56 | <!DOCTYPE html> |
| 48 | <html lang=(lang.code()) data-theme="system"> | 57 | <html lang=(lang.code()) data-theme="system"> |
| @@ -61,7 +70,15 @@ pub async fn shell( | |||
| 61 | <a class="skip-link" href="#main">(t(lang, K::SkipToContent))</a> | 70 | <a class="skip-link" href="#main">(t(lang, K::SkipToContent))</a> |
| 62 | <header class="topbar"> | 71 | <header class="topbar"> |
| 63 | <a class="topbar-brand" href="/">"iz"</a> | 72 | <a class="topbar-brand" href="/">"iz"</a> |
| 64 | - <nav class="switcher" aria-label=(t(lang, K::Services))></nav> | 73 | + if !services.is_empty() { |
| 74 | + <nav class="switcher" aria-label=(t(lang, K::Services))> | ||
| 75 | + for service in services.iter() { | ||
| 76 | + <a href=(service.url.as_str()) rel="noopener" title=(service.name.as_str()) | ||
| 77 | + data-healthy=(if service.healthy { "true" } else { "false" }) | ||
| 78 | + aria-current=(service_is_current(service))>(service.name.as_str())</a> | ||
| 79 | + } | ||
| 80 | + </nav> | ||
| 81 | + } | ||
| 65 | <div class="topbar-end"> | 82 | <div class="topbar-end"> |
| 66 | if let Some(viewer) = viewer { | 83 | if let Some(viewer) = viewer { |
| 67 | <details class="user-menu"> | 84 | <details class="user-menu"> |
| @@ -83,6 +100,11 @@ pub async fn shell( | |||
| 83 | }) | 100 | }) |
| 84 | } | 101 | } |
| 85 | 102 | ||
| 103 | +/// Whether `service` is the app that renders the page, which the switcher marks with `aria-current`. | ||
| 104 | +fn service_is_current(service: &Service) -> Option<&'static str> { | ||
| 105 | + (service.key == APP_KEY).then_some("true") | ||
| 106 | +} | ||
| 107 | + | ||
| 86 | /// The body of a message page: a title, one sentence, an optional detail (escaped, in a code | 108 | /// The body of a message page: a title, one sentence, an optional detail (escaped, in a code |
| 87 | /// element) and a way back to the start. | 109 | /// element) and a way back to the start. |
| 88 | #[component] | 110 | #[component] |
crates/iz-web/src/views/structure.rsadded+413 -0
| @@ -0,0 +1,413 @@ | |||
| 1 | +//! Markup of the structure and people pages: projects (`/tags`), columns (`/columns`), the members, limits | ||
| 2 | +//! and server sections of `/settings`, and the person card (`/people/{sub}`). Plain data in, markup out. | ||
| 3 | +//! Every value is escaped by `view!`; no script or inline style is emitted. | ||
| 4 | + | ||
| 5 | +use topcoat::Result; | ||
| 6 | +use topcoat::view::{View, component, view}; | ||
| 7 | + | ||
| 8 | +use crate::i18n::Lang; | ||
| 9 | +use crate::i18n::admin::fill; | ||
| 10 | +use crate::i18n::structure::{K, t}; | ||
| 11 | +use crate::views::admin::admin_tabs; | ||
| 12 | +use crate::views::board::flag; | ||
| 13 | +use crate::views::{alert, notice}; | ||
| 14 | + | ||
| 15 | +/// One project as the tags page shows it. | ||
| 16 | +#[derive(Debug, Clone)] | ||
| 17 | +pub struct TagRow { | ||
| 18 | + /// Project id. | ||
| 19 | + pub id: String, | ||
| 20 | + /// Project name. | ||
| 21 | + pub name: String, | ||
| 22 | + /// Palette colour name (`c0` to `c7`), if set. | ||
| 23 | + pub colour: Option<String>, | ||
| 24 | + /// Whether this is the default project. | ||
| 25 | + pub is_default: bool, | ||
| 26 | + /// Live cards in the project. | ||
| 27 | + pub uses: i64, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/// The tags page: the list, the add form, and the palette. | ||
| 31 | +#[derive(Debug, Clone)] | ||
| 32 | +pub struct TagsView { | ||
| 33 | + /// The language. | ||
| 34 | + pub lang: Lang, | ||
| 35 | + /// Projects in board order. | ||
| 36 | + pub tags: Vec<TagRow>, | ||
| 37 | + /// The palette colour names, in order. | ||
| 38 | + pub palette: Vec<String>, | ||
| 39 | + /// A confirmation, already translated. | ||
| 40 | + pub notice: Option<String>, | ||
| 41 | + /// A refusal, already translated or a store message. | ||
| 42 | + pub alert: Option<String>, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// One column as the columns page shows it. | ||
| 46 | +#[derive(Debug, Clone)] | ||
| 47 | +pub struct ColumnRow { | ||
| 48 | + /// Column id. | ||
| 49 | + pub id: String, | ||
| 50 | + /// Column name. | ||
| 51 | + pub name: String, | ||
| 52 | + /// Whether this is the done column. | ||
| 53 | + pub is_done: bool, | ||
| 54 | + /// Live cards in the column. | ||
| 55 | + pub cards: i64, | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// The columns page: the list in board order and the add form. | ||
| 59 | +#[derive(Debug, Clone)] | ||
| 60 | +pub struct ColumnsView { | ||
| 61 | + /// The language. | ||
| 62 | + pub lang: Lang, | ||
| 63 | + /// Live columns in board order. | ||
| 64 | + pub columns: Vec<ColumnRow>, | ||
| 65 | + /// A confirmation, already translated. | ||
| 66 | + pub notice: Option<String>, | ||
| 67 | + /// A refusal, already translated or a store message. | ||
| 68 | + pub alert: Option<String>, | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// One member as the settings page shows them. | ||
| 72 | +#[derive(Debug, Clone)] | ||
| 73 | +pub struct MemberRow { | ||
| 74 | + /// Member id (the OIDC `sub`). | ||
| 75 | + pub sub: String, | ||
| 76 | + /// Display name. | ||
| 77 | + pub name: String, | ||
| 78 | + /// Address. | ||
| 79 | + pub email: String, | ||
| 80 | + /// Stored role: `admin`, `member`, `viewer` or `none`. | ||
| 81 | + pub role: String, | ||
| 82 | + /// The directory marks this person as an administrator. | ||
| 83 | + pub im_admin: bool, | ||
| 84 | + /// The directory has disabled this person. | ||
| 85 | + pub disabled: bool, | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// Read-only facts about the running server. | ||
| 89 | +#[derive(Debug, Clone, Default)] | ||
| 90 | +pub struct ServerInfo { | ||
| 91 | + /// The public base address. | ||
| 92 | + pub base_url: String, | ||
| 93 | + /// The listen address. | ||
| 94 | + pub listen: String, | ||
| 95 | + /// The data directory. | ||
| 96 | + pub data_dir: String, | ||
| 97 | + /// The database file. | ||
| 98 | + pub database: String, | ||
| 99 | + /// The highest applied migration. | ||
| 100 | + pub schema: i64, | ||
| 101 | + /// The build id. | ||
| 102 | + pub build: String, | ||
| 103 | + /// Whether sign-in through im is configured. | ||
| 104 | + pub sign_in: bool, | ||
| 105 | + /// Whether attachments go to the Files service. | ||
| 106 | + pub storage_in: bool, | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +/// The projects page body. | ||
| 110 | +#[component] | ||
| 111 | +pub async fn tags_content(page: &TagsView, csrf: &str) -> Result<impl View> { | ||
| 112 | + let lang = page.lang; | ||
| 113 | + Ok(view! { | ||
| 114 | + <h1>(t(lang, K::TagsTitle))</h1> | ||
| 115 | + admin_tabs(lang: lang, current: "tags") | ||
| 116 | + if let Some(message) = &page.alert { | ||
| 117 | + alert(message: message.as_str()) | ||
| 118 | + } | ||
| 119 | + if let Some(message) = &page.notice { | ||
| 120 | + notice(message: message.as_str()) | ||
| 121 | + } | ||
| 122 | + <p class="field-hint">(t(lang, K::TagsHelp))</p> | ||
| 123 | + <section class="card"> | ||
| 124 | + <table class="admin-table"> | ||
| 125 | + <tbody> | ||
| 126 | + for tag in page.tags.iter() { | ||
| 127 | + <tr> | ||
| 128 | + <td> | ||
| 129 | + <span class="tone-dot" data-colour=(tag.colour.as_deref().unwrap_or(""))></span> | ||
| 130 | + " " (tag.name.as_str()) | ||
| 131 | + if tag.is_default { | ||
| 132 | + " " <span class="badge">(t(lang, K::TagDefault))</span> | ||
| 133 | + } | ||
| 134 | + <span class="field-hint">" " (fill(t(lang, K::TagUsedBy), &[&tag.uses.to_string()]))</span> | ||
| 135 | + </td> | ||
| 136 | + <td> | ||
| 137 | + <form method="post" action=(format!("/tags/{}/rename", tag.id)) class="inline"> | ||
| 138 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 139 | + <input name="name" value=(tag.name.as_str()) maxlength="60" required=(flag(true))> | ||
| 140 | + <button class="button" type="submit">(t(lang, K::TagRename))</button> | ||
| 141 | + </form> | ||
| 142 | + </td> | ||
| 143 | + <td> | ||
| 144 | + <form method="post" action=(format!("/tags/{}/colour", tag.id)) class="inline"> | ||
| 145 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 146 | + <select name="colour"> | ||
| 147 | + <option value="" selected=(flag(tag.colour.is_none()))>(t(lang, K::TagNoColour))</option> | ||
| 148 | + for colour in page.palette.iter() { | ||
| 149 | + <option value=(colour.as_str()) selected=(flag(tag.colour.as_deref() == Some(colour.as_str())))>(colour.as_str())</option> | ||
| 150 | + } | ||
| 151 | + </select> | ||
| 152 | + <button class="button" type="submit">(t(lang, K::TagSaveColour))</button> | ||
| 153 | + </form> | ||
| 154 | + </td> | ||
| 155 | + <td> | ||
| 156 | + <form method="post" action=(format!("/tags/{}/move", tag.id)) class="inline"> | ||
| 157 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 158 | + <button class="button ghost" type="submit" name="direction" value="up">(t(lang, K::TagMoveUp))</button> | ||
| 159 | + <button class="button ghost" type="submit" name="direction" value="down">(t(lang, K::TagMoveDown))</button> | ||
| 160 | + </form> | ||
| 161 | + </td> | ||
| 162 | + <td> | ||
| 163 | + if !tag.is_default { | ||
| 164 | + <form method="post" action=(format!("/tags/{}/delete", tag.id)) class="inline"> | ||
| 165 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 166 | + <button class="button danger" type="submit">(t(lang, K::TagDelete))</button> | ||
| 167 | + </form> | ||
| 168 | + } | ||
| 169 | + </td> | ||
| 170 | + </tr> | ||
| 171 | + } | ||
| 172 | + </tbody> | ||
| 173 | + </table> | ||
| 174 | + </section> | ||
| 175 | + <section class="card"> | ||
| 176 | + <h2>(t(lang, K::TagsNew))</h2> | ||
| 177 | + <form method="post" action="/tags" class="stack"> | ||
| 178 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 179 | + <div class="field"> | ||
| 180 | + <label for="tag-name">(t(lang, K::TagName))</label> | ||
| 181 | + <input id="tag-name" name="name" maxlength="60" required=(flag(true))> | ||
| 182 | + </div> | ||
| 183 | + <div class="field"> | ||
| 184 | + <label for="tag-colour">(t(lang, K::TagColour))</label> | ||
| 185 | + <select id="tag-colour" name="colour"> | ||
| 186 | + <option value="">(t(lang, K::TagNoColour))</option> | ||
| 187 | + for colour in page.palette.iter() { | ||
| 188 | + <option value=(colour.as_str())>(colour.as_str())</option> | ||
| 189 | + } | ||
| 190 | + </select> | ||
| 191 | + </div> | ||
| 192 | + <button class="button primary" type="submit">(t(lang, K::TagAdd))</button> | ||
| 193 | + </form> | ||
| 194 | + </section> | ||
| 195 | + }) | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +/// The columns page body. | ||
| 199 | +#[component] | ||
| 200 | +pub async fn columns_content(page: &ColumnsView, csrf: &str) -> Result<impl View> { | ||
| 201 | + let lang = page.lang; | ||
| 202 | + Ok(view! { | ||
| 203 | + <h1>(t(lang, K::ColumnsTitle))</h1> | ||
| 204 | + admin_tabs(lang: lang, current: "columns") | ||
| 205 | + if let Some(message) = &page.alert { | ||
| 206 | + alert(message: message.as_str()) | ||
| 207 | + } | ||
| 208 | + if let Some(message) = &page.notice { | ||
| 209 | + notice(message: message.as_str()) | ||
| 210 | + } | ||
| 211 | + <p class="field-hint">(t(lang, K::ColumnsHelp))</p> | ||
| 212 | + <section class="card"> | ||
| 213 | + <table class="admin-table"> | ||
| 214 | + <tbody> | ||
| 215 | + for column in page.columns.iter() { | ||
| 216 | + <tr> | ||
| 217 | + <td> | ||
| 218 | + (column.name.as_str()) | ||
| 219 | + if column.is_done { | ||
| 220 | + " " <span class="badge">(t(lang, K::ColumnDone))</span> | ||
| 221 | + } | ||
| 222 | + <span class="field-hint">" " (fill(t(lang, K::ColumnCards), &[&column.cards.to_string()]))</span> | ||
| 223 | + </td> | ||
| 224 | + <td> | ||
| 225 | + <form method="post" action=(format!("/columns/{}/rename", column.id)) class="inline"> | ||
| 226 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 227 | + <input name="name" value=(column.name.as_str()) maxlength="60" required=(flag(true))> | ||
| 228 | + <button class="button" type="submit">(t(lang, K::ColumnRename))</button> | ||
| 229 | + </form> | ||
| 230 | + </td> | ||
| 231 | + <td> | ||
| 232 | + <form method="post" action=(format!("/columns/{}/move", column.id)) class="inline"> | ||
| 233 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 234 | + <button class="button ghost" type="submit" name="direction" value="up">(t(lang, K::ColumnMoveUp))</button> | ||
| 235 | + <button class="button ghost" type="submit" name="direction" value="down">(t(lang, K::ColumnMoveDown))</button> | ||
| 236 | + </form> | ||
| 237 | + </td> | ||
| 238 | + <td> | ||
| 239 | + if !column.is_done { | ||
| 240 | + <form method="post" action=(format!("/columns/{}/retire", column.id)) class="inline"> | ||
| 241 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 242 | + <button class="button danger" type="submit">(t(lang, K::ColumnRetire))</button> | ||
| 243 | + </form> | ||
| 244 | + } | ||
| 245 | + </td> | ||
| 246 | + </tr> | ||
| 247 | + } | ||
| 248 | + </tbody> | ||
| 249 | + </table> | ||
| 250 | + </section> | ||
| 251 | + <section class="card"> | ||
| 252 | + <h2>(t(lang, K::ColumnsNew))</h2> | ||
| 253 | + <form method="post" action="/columns" class="stack"> | ||
| 254 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 255 | + <div class="field"> | ||
| 256 | + <label for="column-name">(t(lang, K::ColumnName))</label> | ||
| 257 | + <input id="column-name" name="name" maxlength="60" required=(flag(true))> | ||
| 258 | + </div> | ||
| 259 | + <button class="button primary" type="submit">(t(lang, K::ColumnAdd))</button> | ||
| 260 | + </form> | ||
| 261 | + </section> | ||
| 262 | + }) | ||
| 263 | +} | ||
| 264 | + | ||
| 265 | +/// The members and roles section of `/settings`. One row per member, each with its own role form. | ||
| 266 | +#[component] | ||
| 267 | +pub async fn members_section(lang: Lang, members: &[MemberRow], csrf: &str) -> Result<impl View> { | ||
| 268 | + Ok(view! { | ||
| 269 | + <section class="card" id="members"> | ||
| 270 | + <h2>(t(lang, K::MembersHeading))</h2> | ||
| 271 | + <p class="field-hint">(t(lang, K::MembersHelp))</p> | ||
| 272 | + <table class="admin-table"> | ||
| 273 | + <thead> | ||
| 274 | + <tr> | ||
| 275 | + <th>(t(lang, K::MemberName))</th> | ||
| 276 | + <th>(t(lang, K::MemberEmail))</th> | ||
| 277 | + <th>(t(lang, K::MemberFlags))</th> | ||
| 278 | + <th>(t(lang, K::MemberRole))</th> | ||
| 279 | + </tr> | ||
| 280 | + </thead> | ||
| 281 | + <tbody> | ||
| 282 | + for member in members.iter() { | ||
| 283 | + <tr> | ||
| 284 | + <td>(member.name.as_str())</td> | ||
| 285 | + <td>(member.email.as_str())</td> | ||
| 286 | + <td> | ||
| 287 | + if member.im_admin { | ||
| 288 | + <span class="badge">(t(lang, K::MemberImAdmin))</span> | ||
| 289 | + } | ||
| 290 | + if member.disabled { | ||
| 291 | + <span class="badge">(t(lang, K::MemberDisabled))</span> | ||
| 292 | + } | ||
| 293 | + </td> | ||
| 294 | + <td> | ||
| 295 | + <form method="post" action=(format!("/settings/members/{}/role", member.sub)) class="inline"> | ||
| 296 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 297 | + <select name="role" aria-label=(t(lang, K::MemberRole))> | ||
| 298 | + <option value="admin" selected=(flag(member.role == "admin"))>(t(lang, K::RoleAdmin))</option> | ||
| 299 | + <option value="member" selected=(flag(member.role == "member"))>(t(lang, K::RoleMember))</option> | ||
| 300 | + <option value="viewer" selected=(flag(member.role == "viewer"))>(t(lang, K::RoleViewer))</option> | ||
| 301 | + <option value="none" selected=(flag(member.role == "none"))>(t(lang, K::RoleNone))</option> | ||
| 302 | + </select> | ||
| 303 | + <button class="button" type="submit">(t(lang, K::MemberSave))</button> | ||
| 304 | + </form> | ||
| 305 | + </td> | ||
| 306 | + </tr> | ||
| 307 | + } | ||
| 308 | + </tbody> | ||
| 309 | + </table> | ||
| 310 | + </section> | ||
| 311 | + }) | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +/// The limits section of `/settings`: attachment size and allowed extensions. | ||
| 315 | +#[component] | ||
| 316 | +pub async fn limits_section( | ||
| 317 | + lang: Lang, | ||
| 318 | + limit_mib: &str, | ||
| 319 | + extensions: &str, | ||
| 320 | + csrf: &str, | ||
| 321 | +) -> Result<impl View> { | ||
| 322 | + Ok(view! { | ||
| 323 | + <section class="card" id="limits"> | ||
| 324 | + <h2>(t(lang, K::LimitsHeading))</h2> | ||
| 325 | + <p class="field-hint">(t(lang, K::LimitsHelp))</p> | ||
| 326 | + <form method="post" action="/settings/limits" class="stack"> | ||
| 327 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 328 | + <div class="field"> | ||
| 329 | + <label for="limit-mib">(t(lang, K::LimitMib))</label> | ||
| 330 | + <input id="limit-mib" name="limit_mib" inputmode="numeric" value=(limit_mib) maxlength="4"> | ||
| 331 | + </div> | ||
| 332 | + <div class="field"> | ||
| 333 | + <label for="limit-ext">(t(lang, K::LimitExtensions))</label> | ||
| 334 | + <textarea id="limit-ext" name="extensions" maxlength="2000">(extensions)</textarea> | ||
| 335 | + </div> | ||
| 336 | + <button class="button" type="submit">(t(lang, K::LimitsSave))</button> | ||
| 337 | + </form> | ||
| 338 | + </section> | ||
| 339 | + }) | ||
| 340 | +} | ||
| 341 | + | ||
| 342 | +/// The server section of `/settings`: read-only facts. | ||
| 343 | +#[component] | ||
| 344 | +pub async fn server_section(lang: Lang, info: &ServerInfo) -> Result<impl View> { | ||
| 345 | + let (on_text, off_text) = (t(lang, K::On), t(lang, K::Off)); | ||
| 346 | + let storage = if info.storage_in { | ||
| 347 | + t(lang, K::StorageIn) | ||
| 348 | + } else { | ||
| 349 | + t(lang, K::StorageLocal) | ||
| 350 | + }; | ||
| 351 | + let schema = info.schema.to_string(); | ||
| 352 | + Ok(view! { | ||
| 353 | + <section class="card" id="server"> | ||
| 354 | + <h2>(t(lang, K::ServerHeading))</h2> | ||
| 355 | + <p class="field-hint">(t(lang, K::ServerHelp))</p> | ||
| 356 | + <dl class="facts"> | ||
| 357 | + <dt>(t(lang, K::ServerBase))</dt><dd>(info.base_url.as_str())</dd> | ||
| 358 | + <dt>(t(lang, K::ServerListen))</dt><dd>(info.listen.as_str())</dd> | ||
| 359 | + <dt>(t(lang, K::ServerData))</dt><dd>(info.data_dir.as_str())</dd> | ||
| 360 | + <dt>(t(lang, K::ServerDatabase))</dt><dd>(info.database.as_str())</dd> | ||
| 361 | + <dt>(t(lang, K::ServerSchema))</dt><dd>(schema.as_str())</dd> | ||
| 362 | + <dt>(t(lang, K::ServerBuild))</dt><dd>(info.build.as_str())</dd> | ||
| 363 | + <dt>(t(lang, K::ServerSignIn))</dt><dd>(if info.sign_in { on_text } else { off_text })</dd> | ||
| 364 | + <dt>(t(lang, K::ServerStorage))</dt><dd>(storage)</dd> | ||
| 365 | + </dl> | ||
| 366 | + </section> | ||
| 367 | + }) | ||
| 368 | +} | ||
| 369 | + | ||
| 370 | +/// The person card body: name, role and zone, counts, and the recent activity of this member on the board. | ||
| 371 | +#[component] | ||
| 372 | +pub async fn person_content( | ||
| 373 | + lang: Lang, | ||
| 374 | + name: &str, | ||
| 375 | + role: &str, | ||
| 376 | + zone: &str, | ||
| 377 | + last_sign_in: &str, | ||
| 378 | + counts: &[(&'static str, String)], | ||
| 379 | + recent: &[(String, String, String)], | ||
| 380 | +) -> Result<impl View> { | ||
| 381 | + let role_line = fill(t(lang, K::PersonRole), &[role]); | ||
| 382 | + Ok(view! { | ||
| 383 | + <h1>(name)</h1> | ||
| 384 | + <p class="field-hint">(role_line.as_str())</p> | ||
| 385 | + <section class="card"> | ||
| 386 | + <dl class="facts"> | ||
| 387 | + for (label, value) in counts.iter() { | ||
| 388 | + <dt>(*label)</dt><dd>(value.as_str())</dd> | ||
| 389 | + } | ||
| 390 | + <dt>(t(lang, K::PersonZone))</dt><dd>(zone)</dd> | ||
| 391 | + <dt>(t(lang, K::PersonLastSignIn))</dt><dd>(last_sign_in)</dd> | ||
| 392 | + </dl> | ||
| 393 | + </section> | ||
| 394 | + <section class="card"> | ||
| 395 | + <h2>(t(lang, K::PersonRecent))</h2> | ||
| 396 | + if recent.is_empty() { | ||
| 397 | + <p class="muted">(t(lang, K::PersonNoActivity))</p> | ||
| 398 | + } | ||
| 399 | + <ul class="activity-list"> | ||
| 400 | + for (when, sentence, task) in recent.iter() { | ||
| 401 | + <li> | ||
| 402 | + <time>(when.as_str())</time> | ||
| 403 | + " " | ||
| 404 | + (sentence.as_str()) | ||
| 405 | + " " | ||
| 406 | + <span>(task.as_str())</span> | ||
| 407 | + </li> | ||
| 408 | + } | ||
| 409 | + </ul> | ||
| 410 | + </section> | ||
| 411 | + <p><a class="button ghost" href="/">(t(lang, K::PersonBack))</a></p> | ||
| 412 | + }) | ||
| 413 | +} | ||
deploy/ferron.confadded+17 -0
| @@ -0,0 +1,17 @@ | |||
| 1 | +# Ferron reverse proxy for iz. Same format as the forge example (ferron.conf, not KDL). | ||
| 2 | +# Replace iz.example.com with the public host name (base_url in /etc/iz/iz.toml must match it). | ||
| 3 | +# A bare host block gets automatic TLS. | ||
| 4 | +# | ||
| 5 | +# The proxy sends X-Forwarded-For for the client. iz reads that header only from peers listed in | ||
| 6 | +# trusted_proxies; with Ferron on the same machine the peer is 127.0.0.1, so set | ||
| 7 | +# trusted_proxies = ["127.0.0.1/32"] in iz.toml. | ||
| 8 | +# | ||
| 9 | +# Buffering is off because the live update streams (server-sent events) must reach the browser | ||
| 10 | +# as they are written. | ||
| 11 | +iz.example.com { | ||
| 12 | + buffer_request 0 | ||
| 13 | + buffer_response 0 | ||
| 14 | + proxy { | ||
| 15 | + upstream http://127.0.0.1:7654 | ||
| 16 | + } | ||
| 17 | +} | ||
deploy/iz.serviceadded+52 -0
| @@ -0,0 +1,52 @@ | |||
| 1 | +# systemd unit for iz, the family task board. | ||
| 2 | +# | ||
| 3 | +# This file is installed by hand. Nothing enables it automatically: copy it to | ||
| 4 | +# /etc/systemd/system/iz.service, run `systemctl daemon-reload`, then enable and | ||
| 5 | +# start it yourself. See README.md, "First run". | ||
| 6 | + | ||
| 7 | +[Unit] | ||
| 8 | +Description=iz family task board | ||
| 9 | +After=network-online.target | ||
| 10 | +Wants=network-online.target | ||
| 11 | +StartLimitIntervalSec=60 | ||
| 12 | +StartLimitBurst=5 | ||
| 13 | + | ||
| 14 | +[Service] | ||
| 15 | +Type=simple | ||
| 16 | +User=iz | ||
| 17 | +Group=iz | ||
| 18 | +ExecStart=/usr/local/bin/iz --config /etc/iz/iz.toml serve | ||
| 19 | +WorkingDirectory=/var/lib/iz | ||
| 20 | +Restart=on-failure | ||
| 21 | +RestartSec=5 | ||
| 22 | +UMask=0077 | ||
| 23 | + | ||
| 24 | +# Hardening | ||
| 25 | +NoNewPrivileges=yes | ||
| 26 | +ProtectSystem=strict | ||
| 27 | +# Only the data directory is writable: database, iz.key, attachments, backups. | ||
| 28 | +ReadWritePaths=/var/lib/iz | ||
| 29 | +ProtectHome=yes | ||
| 30 | +PrivateTmp=yes | ||
| 31 | +PrivateDevices=yes | ||
| 32 | +ProtectKernelTunables=yes | ||
| 33 | +ProtectKernelModules=yes | ||
| 34 | +ProtectKernelLogs=yes | ||
| 35 | +ProtectControlGroups=yes | ||
| 36 | +ProtectClock=yes | ||
| 37 | +ProcSubset=pid | ||
| 38 | +RestrictSUIDSGID=yes | ||
| 39 | +RestrictRealtime=yes | ||
| 40 | +RestrictNamespaces=yes | ||
| 41 | +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 | ||
| 42 | +LockPersonality=yes | ||
| 43 | +MemoryDenyWriteExecute=yes | ||
| 44 | +SystemCallArchitectures=native | ||
| 45 | +SystemCallFilter=@system-service | ||
| 46 | +SystemCallErrorNumber=EPERM | ||
| 47 | +CapabilityBoundingSet= | ||
| 48 | +AmbientCapabilities= | ||
| 49 | +KeyringMode=private | ||
| 50 | + | ||
| 51 | +[Install] | ||
| 52 | +WantedBy=multi-user.target | ||
docs/architecture.mdmodified+6 -4
| @@ -213,10 +213,12 @@ Board page fingerprint is cheap (max `updated_at` + counts), so a burst of chang | |||
| 213 | 213 | ||
| 214 | ## 10. CLI | 214 | ## 10. CLI |
| 215 | 215 | ||
| 216 | -`iz admin backup --out DIR` (DB snapshot + local attachments + manifest), `iz admin backup-verify SET`, | 216 | +`iz` (or `iz serve`) runs the server. `iz export --out DIR` writes the board as JSON with its attachments and a |
| 217 | -`iz admin restore --from SET --data-dir NEW`, `iz admin export --out DIR` (JSON of the board, tasks, comments, | 217 | +manifest, and never writes outside `DIR`. `iz restore --from SET` verifies a backup set (manifest, digests, the |
| 218 | -activity, plus attachments by name), `iz admin set-role <email> <role>`, `iz admin audit-purge | 218 | +database's `integrity_check` and contiguous migrations) before it replaces the database and attachments in the |
| 219 | ---older-than-days N`. | 219 | +configured data directory, and keeps the files it replaces. `iz fsck` checks the database and the attachment bytes |
| 220 | +read-only. Every command except `export` refuses while a server holds `data_dir/iz.lock`. Backups are written by | ||
| 221 | +the `[backup]` worker (`VACUUM INTO` plus attachment copies and `manifest.json`, see `iz_core::manifest`). | ||
| 220 | 222 | ||
| 221 | --- | 223 | --- |
| 222 | 224 | ||
style/_components.scssmodified+35 -0
| @@ -313,3 +313,38 @@ textarea::placeholder { | |||
| 313 | transition: none; | 313 | transition: none; |
| 314 | } | 314 | } |
| 315 | } | 315 | } |
| 316 | + | ||
| 317 | +// Admin pages: tables of projects, columns and members; name and value lists; inline forms; the colour swatch. | ||
| 318 | +.admin-table { | ||
| 319 | + width: 100%; | ||
| 320 | + border-collapse: collapse; | ||
| 321 | + td, th { padding: 0.4rem 0.5rem; vertical-align: middle; text-align: start; } | ||
| 322 | +} | ||
| 323 | +.inline { | ||
| 324 | + display: inline-flex; | ||
| 325 | + flex-wrap: wrap; | ||
| 326 | + gap: 0.4rem; | ||
| 327 | + align-items: center; | ||
| 328 | +} | ||
| 329 | +.facts { | ||
| 330 | + display: grid; | ||
| 331 | + grid-template-columns: max-content 1fr; | ||
| 332 | + gap: 0.3rem 1rem; | ||
| 333 | + dt { color: var(--muted); } | ||
| 334 | + dd { margin: 0; } | ||
| 335 | +} | ||
| 336 | +.tone-dot { | ||
| 337 | + display: inline-block; | ||
| 338 | + width: 0.75em; | ||
| 339 | + height: 0.75em; | ||
| 340 | + border-radius: 50%; | ||
| 341 | + background: var(--muted); | ||
| 342 | + &[data-colour="c0"] { background: #c2d0ff; } | ||
| 343 | + &[data-colour="c1"] { background: #9fe0b4; } | ||
| 344 | + &[data-colour="c2"] { background: #f2c265; } | ||
| 345 | + &[data-colour="c3"] { background: #f5a3a3; } | ||
| 346 | + &[data-colour="c4"] { background: #a8d8f0; } | ||
| 347 | + &[data-colour="c5"] { background: #d7b3f0; } | ||
| 348 | + &[data-colour="c6"] { background: #ffd1a6; } | ||
| 349 | + &[data-colour="c7"] { background: #c9d6c2; } | ||
| 350 | +} | ||
style/_layout.scssmodified+1 -1
| @@ -52,7 +52,7 @@ | |||
| 52 | white-space: nowrap; | 52 | white-space: nowrap; |
| 53 | } | 53 | } |
| 54 | 54 | ||
| 55 | -.switcher a[aria-current="page"], | 55 | +.switcher a[aria-current="true"], |
| 56 | .switcher a:hover { | 56 | .switcher a:hover { |
| 57 | background: var(--surface-2); | 57 | background: var(--surface-2); |
| 58 | color: var(--text); | 58 | color: var(--text); |