Admin area (users, invites, services, mail, message, policy, keys, audit, health), backups, backup/restore/fsck/keys CLI, systemd unit, Ferron example, README
Browse files at this commit52864eb43e66ba88cf357623305653eb805d800cParent: 50b7e2f- feat
- admin area (users, invites, services, mail, message, policy, keys, audit, health), backups, backup/restore/fsck/keys CLI, systemd unit, Ferron example, README
42 changed files +5763 -246
- README.md +173 -0
- crates/im-core/src/backup.rs +482 -0
- crates/im-core/src/config.rs +86 -29
- crates/im-core/src/lib.rs +1 -0
- crates/im-core/src/model.rs +60 -0
- crates/im-core/src/store/admin.rs +542 -0
- crates/im-core/src/store/clients.rs +2 -2
- crates/im-core/src/store/invites.rs +1 -1
- crates/im-core/src/store/mod.rs +1 -0
- crates/im-core/src/store/sessions.rs +2 -1
- crates/im-core/src/store/users.rs +5 -2
- crates/im-web/src/auth.rs +15 -7
- crates/im-web/src/backups.rs +131 -0
- crates/im-web/src/boot.rs +30 -3
- crates/im-web/src/cli.rs +121 -2
- crates/im-web/src/i18n/admin.rs +672 -0
- crates/im-web/src/i18n/flows.rs +0 -22
- crates/im-web/src/i18n/mod.rs +1 -0
- crates/im-web/src/live.rs +45 -9
- crates/im-web/src/mail/mod.rs +17 -0
- crates/im-web/src/mail/templates.rs +12 -0
- crates/im-web/src/main.rs +6 -5
- crates/im-web/src/oidc/authorize.rs +1 -4
- crates/im-web/src/oidc/signing.rs +17 -0
- crates/im-web/src/pages/admin/audit.rs +211 -0
- crates/im-web/src/pages/admin/clients.rs +646 -0
- crates/im-web/src/pages/admin/health.rs +149 -0
- crates/im-web/src/pages/admin/invites.rs +281 -0
- crates/im-web/src/pages/admin/keys.rs +222 -0
- crates/im-web/src/pages/admin/mail.rs +299 -0
- crates/im-web/src/pages/admin/message.rs +150 -0
- crates/im-web/src/pages/admin/mod.rs +226 -0
- crates/im-web/src/pages/admin/settings.rs +348 -0
- crates/im-web/src/pages/admin/tests.rs +211 -0
- crates/im-web/src/pages/admin/users.rs +511 -0
- crates/im-web/src/pages/email.rs +1 -1
- crates/im-web/src/pages/invite.rs +6 -155
- crates/im-web/src/pages/mod.rs +1 -0
- crates/im-web/src/pages/reset.rs +1 -1
- crates/im-web/src/state.rs +24 -2
- deploy/ferron.kdl +6 -0
- deploy/im.service +47 -0
README.mdadded+173 -0
| @@ -0,0 +1,173 @@ | ||
| 1 | +# im | |
| 2 | + | |
| 3 | +`im` is the family's sign-in provider. It is an OpenID Connect provider (authorization code with PKCE, | |
| 4 | +EdDSA-signed ID tokens, back-channel logout), and it keeps the people directory, the photos, and the list of | |
| 5 | +family services. The family's apps (`in`, `iz`) sign people in through `im` and never see a password. | |
| 6 | + | |
| 7 | +It is one Rust binary, `im`, with a SQLite-format database (Turso), no external services, and no runtime | |
| 8 | +dependencies beyond an SMTP server if you want mail to be sent. | |
| 9 | + | |
| 10 | +## Build | |
| 11 | + | |
| 12 | +```sh | |
| 13 | +cargo build --release --workspace | |
| 14 | +install -m 0755 target/release/im /usr/local/bin/im | |
| 15 | +``` | |
| 16 | + | |
| 17 | +Run the checks the same way the project does: | |
| 18 | + | |
| 19 | +```sh | |
| 20 | +cargo fmt --all --check | |
| 21 | +cargo clippy --workspace --all-targets -- -D warnings | |
| 22 | +cargo test --workspace | |
| 23 | +``` | |
| 24 | + | |
| 25 | +## Configuration | |
| 26 | + | |
| 27 | +The configuration is a TOML file. The default path is `config/im.toml`; set `--config <path>` or the | |
| 28 | +`IM_CONFIG` variable to use another. When the default file is missing, `im` creates it from | |
| 29 | +`config/im.example.toml`. | |
| 30 | + | |
| 31 | +The settings that matter first: | |
| 32 | + | |
| 33 | +| Setting | Meaning | | |
| 34 | +| --- | --- | | |
| 35 | +| `database` | The database file. Keep it inside `data_dir`. | | |
| 36 | +| `data_dir` | Holds the instance key `im.key`, the photos, and the backups. Created with mode 0700. | | |
| 37 | +| `listen` | The loopback address `im` binds to, for example `127.0.0.1:7650`. | | |
| 38 | +| `base_url` | The public origin, with no trailing slash. This is the OpenID issuer and the origin of every link in mail. | | |
| 39 | +| `trusted_proxies` | The proxies whose `X-Forwarded-For` is believed. Leave empty when nothing is in front of `im`. | | |
| 40 | + | |
| 41 | +Secrets never go in the file. Client secrets are shown once and stored as hashes. The SMTP password is read | |
| 42 | +from a file named in the configuration, and the instance key is created on first run. | |
| 43 | + | |
| 44 | +The `[policy]` section sets the sign-in policy. The admin UI can change these values at run time; a value | |
| 45 | +saved there overrides the file, and the settings page shows where each value comes from. | |
| 46 | + | |
| 47 | +## First run | |
| 48 | + | |
| 49 | +1. Start the server: `im --config /etc/im/im.toml serve`, or run the systemd unit (below). | |
| 50 | +2. Open `base_url` in a browser. With no account yet, `im` shows the setup page. Create the first | |
| 51 | + administrator there. Setup is closed once an account exists. | |
| 52 | +3. Sign in and turn on two-factor sign-in for the administrator account. The policy requires it for | |
| 53 | + administrators by default. | |
| 54 | + | |
| 55 | +## Registering the family services | |
| 56 | + | |
| 57 | +Each service that signs people in is an OpenID client. Register it from the shell on the server: | |
| 58 | + | |
| 59 | +```sh | |
| 60 | +im --config /etc/im/im.toml client add --name "in" \ | |
| 61 | + --redirect-uri https://in.example.com/auth/callback \ | |
| 62 | + --post-logout-uri https://in.example.com/ \ | |
| 63 | + --backchannel-uri https://in.example.com/auth/backchannel-logout \ | |
| 64 | + --family-key in --public-url https://in.example.com \ | |
| 65 | + --scopes "openid profile email" | |
| 66 | + | |
| 67 | +im --config /etc/im/im.toml client add --name "iz" \ | |
| 68 | + --redirect-uri https://iz.example.com/auth/callback \ | |
| 69 | + --post-logout-uri https://iz.example.com/ \ | |
| 70 | + --backchannel-uri https://iz.example.com/auth/backchannel-logout \ | |
| 71 | + --family-key iz --public-url https://iz.example.com \ | |
| 72 | + --scopes "openid profile email" | |
| 73 | +``` | |
| 74 | + | |
| 75 | +- The redirect URI is `{base}/auth/callback` of the service. | |
| 76 | +- The post-logout URI is `{base}/`. | |
| 77 | +- The back-channel logout URI is `{base}/auth/backchannel-logout`. | |
| 78 | +- The family key (`in`, `iz`) names the service in the switcher. A family key needs `--public-url`, the | |
| 79 | + origin the switcher links to. The key `im` is reserved. | |
| 80 | +- The command prints the `client_id` and the `client_secret`. The secret is shown once; store it in the | |
| 81 | + service's configuration now. | |
| 82 | + | |
| 83 | +The same clients can be managed in the admin UI under Services, where the secret is also shown once, and | |
| 84 | +where a secret can be rotated (the old one stops working at once) or a client disabled. | |
| 85 | + | |
| 86 | +Clients are listed with `im client list`, and disabled with `im client disable <client_id>`. | |
| 87 | + | |
| 88 | ||
| 89 | + | |
| 90 | +Mail is always queued in the outbox and sent through `[smtp]`. With `host` empty no attempt is made, and mail | |
| 91 | +waits in the outbox. Set `host`, `port`, `tls` (`implicit` for port 465, `starttls` for 587), `from`, | |
| 92 | +`from_name`, and, when the relay needs a login, `username` and `password_file` (first line only, not readable | |
| 93 | +by group or others). | |
| 94 | + | |
| 95 | +The admin pages show the SMTP settings (without the password), the outbox by state, and let an administrator | |
| 96 | +retry a failed mail, give up on one that is not yet sent, and send a test mail to their own address. | |
| 97 | + | |
| 98 | +## Backups and restore | |
| 99 | + | |
| 100 | +Set `[backup] dir` to a directory to turn scheduled backups on. Each run writes a set named `set-<stamp>`: | |
| 101 | +a consistent snapshot of the database (`VACUUM INTO`), the photos, and a `manifest.json` with the SHA-256 of | |
| 102 | +every file. `interval_hours` sets the schedule and `keep` how many sets are kept; older sets are removed | |
| 103 | +only when they are real sets with a manifest. An optional `healthcheck_url` is pinged after each run, with | |
| 104 | +the failure URL on error (a dead-man check). | |
| 105 | + | |
| 106 | +```sh | |
| 107 | +im --config /etc/im/im.toml backup now # write a set now | |
| 108 | +im --config /etc/im/im.toml fsck # check the database and the signing keys | |
| 109 | +im --config /etc/im/im.toml restore --from <set> # verify, then restore | |
| 110 | +``` | |
| 111 | + | |
| 112 | +`restore` verifies the set before it changes anything: every file's hash, the manifest's list of files, and | |
| 113 | +the snapshot's integrity and schema. A tampered set is refused. A verified set replaces the database and the | |
| 114 | +photos; the previous database and photos are moved into a `restore-<stamp>` directory inside `data_dir`, so | |
| 115 | +nothing is lost. `restore` refuses to run while the server (or another `im` command) holds the data directory, | |
| 116 | +so stop the service first. | |
| 117 | + | |
| 118 | +## Signing keys | |
| 119 | + | |
| 120 | +`im` signs tokens with Ed25519 keys. A key signs for 90 days; its successor is created and published a day | |
| 121 | +before it signs, and a retired key stays published for seven days so that tokens it signed still verify. | |
| 122 | +Keys are maintained automatically. | |
| 123 | + | |
| 124 | +To rotate now (for example after a suspected leak of a key file): | |
| 125 | + | |
| 126 | +```sh | |
| 127 | +im --config /etc/im/im.toml keys rotate | |
| 128 | +``` | |
| 129 | + | |
| 130 | +The new key signs at once and the previous key stops signing at once; it stays published for the overlap. | |
| 131 | +The admin Keys page shows every key, its state, and the same rotation. | |
| 132 | + | |
| 133 | +## Command line | |
| 134 | + | |
| 135 | +```text | |
| 136 | +im [--config <path>] [serve] | |
| 137 | +im [--config <path>] client add --name <name> [--redirect-uri <uri>]... [--post-logout-uri <uri>]... | |
| 138 | + [--backchannel-uri <uri>] [--family-key <key> --public-url <origin>] [--scopes "<scope ...>"] | |
| 139 | +im [--config <path>] client list | |
| 140 | +im [--config <path>] client disable <client_id> | |
| 141 | +im [--config <path>] backup now | |
| 142 | +im [--config <path>] restore --from <set> | |
| 143 | +im [--config <path>] fsck | |
| 144 | +im [--config <path>] keys rotate | |
| 145 | +``` | |
| 146 | + | |
| 147 | +The commands that open the database hold the data directory's lock, so they refuse to run beside a running | |
| 148 | +server. | |
| 149 | + | |
| 150 | +## Running as a service | |
| 151 | + | |
| 152 | +`deploy/im.service` is a hardened systemd unit. It runs as the `im` user with `/etc/im/im.toml` and writes | |
| 153 | +only to `/var/lib/im`. Create the user and the directories, copy the binary and the configuration, then: | |
| 154 | + | |
| 155 | +```sh | |
| 156 | +useradd --system --home /var/lib/im --shell /usr/sbin/nologin im | |
| 157 | +install -d -o im -g im -m 0700 /var/lib/im | |
| 158 | +install -d -m 0750 /etc/im | |
| 159 | +install -m 0640 config/im.toml /etc/im/im.toml | |
| 160 | +install -m 0644 deploy/im.service /etc/systemd/system/im.service | |
| 161 | +systemctl daemon-reload | |
| 162 | +systemctl enable --now im | |
| 163 | +``` | |
| 164 | + | |
| 165 | +Put a TLS-terminating reverse proxy in front of it. `deploy/ferron.kdl` is an example Ferron site that | |
| 166 | +forwards to `127.0.0.1:7650`; `base_url` must be the same public origin. | |
| 167 | + | |
| 168 | +## Layout | |
| 169 | + | |
| 170 | +- `crates/im-core`: the domain, the store and its migrations, the configuration, keys, secrets, backups. | |
| 171 | +- `crates/im-web`: the `im` binary: pages, OpenID Connect endpoints, the admin area, live updates, the mail | |
| 172 | + and back-channel workers, and the command line. | |
| 173 | +- `docs/`: the architecture, the contracts with the family's apps, the conventions, and the attack plan. |
crates/im-core/src/backup.rsadded+482 -0
| @@ -0,0 +1,482 @@ | ||
| 1 | +//! Backup sets, verification, pruning and restore. | |
| 2 | +//! | |
| 3 | +//! A set is a directory `set-<stamp>` under the backup root. It holds `im.db` (a consistent snapshot of the | |
| 4 | +//! database, see `store/snapshot.rs`), a `photos/` directory with a copy of every profile photo, and | |
| 5 | +//! `manifest.json`. The manifest names every file with its size and SHA-256. A set is written under a | |
| 6 | +//! temporary name and renamed into place only when its manifest is complete, so a half-written set is | |
| 7 | +//! never mistaken for a good one. | |
| 8 | +//! | |
| 9 | +//! Verification checks every hash, refuses a file the manifest does not list (in the set or in `photos/`), | |
| 10 | +//! refuses a name that is not a plain file name, and runs `PRAGMA integrity_check` and the migration | |
| 11 | +//! check on a scratch copy, so the set itself is never written to. Restore verifies first and changes | |
| 12 | +//! nothing when verification fails. It only replaces a database and a photo directory that lie inside the | |
| 13 | +//! data directory, and it moves what it replaces into `data_dir/restore-<stamp>/` rather than deleting it. | |
| 14 | +//! The caller must hold the data-directory lock: a running server is never restored under. | |
| 15 | + | |
| 16 | +use std::fs::OpenOptions; | |
| 17 | +use std::io::{Read, Write}; | |
| 18 | +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; | |
| 19 | +use std::path::{Path, PathBuf}; | |
| 20 | + | |
| 21 | +use serde::{Deserialize, Serialize}; | |
| 22 | +use sha2::{Digest, Sha256}; | |
| 23 | +use turso::Builder; | |
| 24 | + | |
| 25 | +use crate::error::{Error, Result}; | |
| 26 | +use crate::store::migrate::MIGRATIONS; | |
| 27 | +use crate::store::{Store, col_int, col_text, db_err, fetch_all}; | |
| 28 | + | |
| 29 | +/// The only manifest format this build reads and writes. | |
| 30 | +pub const FORMAT: u32 = 1; | |
| 31 | +/// Name of the snapshot inside a set. | |
| 32 | +pub const DB_FILE: &str = "im.db"; | |
| 33 | +/// Name of the manifest inside a set. | |
| 34 | +pub const MANIFEST_FILE: &str = "manifest.json"; | |
| 35 | +/// Name of the photo directory inside a set, and beside the database in the data directory. | |
| 36 | +pub const PHOTOS_DIR: &str = "photos"; | |
| 37 | +/// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix. | |
| 38 | +pub const SET_PREFIX: &str = "set-"; | |
| 39 | + | |
| 40 | +/// One file of a set: its name relative to the set, its size and its SHA-256 in lower-case hex. | |
| 41 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 42 | +pub struct FileEntry { | |
| 43 | + /// `im.db`, or `photos/<user id>`. | |
| 44 | + pub name: String, | |
| 45 | + /// Size in bytes. | |
| 46 | + pub size: u64, | |
| 47 | + /// Lower-case hex SHA-256 of the bytes. | |
| 48 | + pub sha256: String, | |
| 49 | +} | |
| 50 | + | |
| 51 | +/// The manifest of a set. | |
| 52 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 53 | +pub struct Manifest { | |
| 54 | + /// Format number; see [`FORMAT`]. | |
| 55 | + pub format: u32, | |
| 56 | + /// When the set was written, UTC. | |
| 57 | + pub created_at: String, | |
| 58 | + /// The snapshot. | |
| 59 | + pub database: FileEntry, | |
| 60 | + /// Every photo that existed when the set was written. | |
| 61 | + pub photos: Vec<FileEntry>, | |
| 62 | +} | |
| 63 | + | |
| 64 | +/// What a restore did. | |
| 65 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 66 | +pub struct RestoreOutcome { | |
| 67 | + /// Photos put back. | |
| 68 | + pub photos: usize, | |
| 69 | + /// The directory that holds the database and photos that were replaced. | |
| 70 | + pub previous: PathBuf, | |
| 71 | +} | |
| 72 | + | |
| 73 | +/// Creates a directory that only this user may enter. | |
| 74 | +fn private_dir(path: &Path) -> Result<()> { | |
| 75 | + std::fs::DirBuilder::new() | |
| 76 | + .mode(0o700) | |
| 77 | + .create(path) | |
| 78 | + .map_err(Error::from) | |
| 79 | +} | |
| 80 | + | |
| 81 | +/// Creates a file that only this user may read, failing if it exists. | |
| 82 | +fn private_file(path: &Path) -> Result<std::fs::File> { | |
| 83 | + OpenOptions::new() | |
| 84 | + .write(true) | |
| 85 | + .create_new(true) | |
| 86 | + .mode(0o600) | |
| 87 | + .open(path) | |
| 88 | + .map_err(Error::from) | |
| 89 | +} | |
| 90 | + | |
| 91 | +/// Writes a complete set under `root` and returns its directory. `stamp` names it and must be safe in a | |
| 92 | +/// file name: callers replace `:` and `.` in the time stamp. | |
| 93 | +pub async fn write_set( | |
| 94 | + store: &Store, | |
| 95 | + data_dir: &Path, | |
| 96 | + root: &Path, | |
| 97 | + stamp: &str, | |
| 98 | +) -> Result<PathBuf> { | |
| 99 | + std::fs::create_dir_all(root)?; | |
| 100 | + let tmp = root.join(format!(".tmp-{stamp}")); | |
| 101 | + let final_dir = root.join(format!("{SET_PREFIX}{stamp}")); | |
| 102 | + if std::fs::symlink_metadata(&final_dir).is_ok() { | |
| 103 | + return Err(Error::Conflict(format!("set {stamp} already exists"))); | |
| 104 | + } | |
| 105 | + private_dir(&tmp)?; | |
| 106 | + match write_into(store, data_dir, &tmp).await { | |
| 107 | + Ok(()) => { | |
| 108 | + std::fs::rename(&tmp, &final_dir)?; | |
| 109 | + Ok(final_dir) | |
| 110 | + } | |
| 111 | + Err(error) => { | |
| 112 | + // A failed set was never complete. It is ours, so it is removed whole. | |
| 113 | + let _ = std::fs::remove_dir_all(&tmp); | |
| 114 | + Err(error) | |
| 115 | + } | |
| 116 | + } | |
| 117 | +} | |
| 118 | + | |
| 119 | +/// Fills `dir` with the snapshot, the photos and the manifest, then fsyncs the directory. | |
| 120 | +async fn write_into(store: &Store, data_dir: &Path, dir: &Path) -> Result<()> { | |
| 121 | + let db_path = dir.join(DB_FILE); | |
| 122 | + store.snapshot_to(&db_path).await?; | |
| 123 | + let database = file_entry(DB_FILE, &db_path)?; | |
| 124 | + | |
| 125 | + let photos_out = dir.join(PHOTOS_DIR); | |
| 126 | + private_dir(&photos_out)?; | |
| 127 | + let mut photos = Vec::new(); | |
| 128 | + let photos_in = data_dir.join(PHOTOS_DIR); | |
| 129 | + if std::fs::symlink_metadata(&photos_in).is_ok() { | |
| 130 | + for name in plain_names(&photos_in)? { | |
| 131 | + let source = photos_in.join(&name); | |
| 132 | + let target = photos_out.join(&name); | |
| 133 | + let mut out = private_file(&target)?; | |
| 134 | + let mut input = std::fs::File::open(&source)?; | |
| 135 | + std::io::copy(&mut input, &mut out)?; | |
| 136 | + out.sync_all()?; | |
| 137 | + photos.push(file_entry(&format!("{PHOTOS_DIR}/{name}"), &target)?); | |
| 138 | + } | |
| 139 | + } | |
| 140 | + | |
| 141 | + let manifest = Manifest { | |
| 142 | + format: FORMAT, | |
| 143 | + created_at: crate::time::now_stamp(), | |
| 144 | + database, | |
| 145 | + photos, | |
| 146 | + }; | |
| 147 | + let text = serde_json::to_string_pretty(&manifest) | |
| 148 | + .map_err(|e| Error::Invalid(format!("manifest: {e}")))?; | |
| 149 | + let mut file = private_file(&dir.join(MANIFEST_FILE))?; | |
| 150 | + file.write_all(text.as_bytes())?; | |
| 151 | + file.sync_all()?; | |
| 152 | + std::fs::File::open(&photos_out)?.sync_all()?; | |
| 153 | + std::fs::File::open(dir)?.sync_all()?; | |
| 154 | + Ok(()) | |
| 155 | +} | |
| 156 | + | |
| 157 | +/// The names of the regular files directly in `dir`. Links and sub-directories are skipped. | |
| 158 | +fn plain_names(dir: &Path) -> Result<Vec<String>> { | |
| 159 | + let mut names = Vec::new(); | |
| 160 | + for entry in std::fs::read_dir(dir)? { | |
| 161 | + let entry = entry?; | |
| 162 | + let meta = std::fs::symlink_metadata(entry.path())?; | |
| 163 | + if meta.file_type().is_file() | |
| 164 | + && let Some(name) = entry.file_name().to_str() | |
| 165 | + && is_plain_name(name) | |
| 166 | + { | |
| 167 | + names.push(name.to_owned()); | |
| 168 | + } | |
| 169 | + } | |
| 170 | + names.sort(); | |
| 171 | + Ok(names) | |
| 172 | +} | |
| 173 | + | |
| 174 | +/// True for a name that is one ordinary path component: letters, digits, `-` and `_`, no dots, no | |
| 175 | +/// separators. Photo files are named by ULID, so anything else is refused. | |
| 176 | +pub fn is_plain_name(name: &str) -> bool { | |
| 177 | + !name.is_empty() | |
| 178 | + && name.len() <= 128 | |
| 179 | + && name | |
| 180 | + .bytes() | |
| 181 | + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') | |
| 182 | +} | |
| 183 | + | |
| 184 | +/// Size and SHA-256 of a file, read in chunks. | |
| 185 | +fn file_entry(name: &str, path: &Path) -> Result<FileEntry> { | |
| 186 | + let (size, sha256) = file_digest(path)?; | |
| 187 | + Ok(FileEntry { | |
| 188 | + name: name.to_owned(), | |
| 189 | + size, | |
| 190 | + sha256, | |
| 191 | + }) | |
| 192 | +} | |
| 193 | + | |
| 194 | +/// Size and SHA-256 of a file, read in chunks. | |
| 195 | +fn file_digest(path: &Path) -> Result<(u64, String)> { | |
| 196 | + let mut file = std::fs::File::open(path)?; | |
| 197 | + let mut hasher = Sha256::new(); | |
| 198 | + let mut size = 0u64; | |
| 199 | + let mut buf = vec![0u8; 1 << 20]; | |
| 200 | + loop { | |
| 201 | + let n = file.read(&mut buf)?; | |
| 202 | + if n == 0 { | |
| 203 | + break; | |
| 204 | + } | |
| 205 | + size += n as u64; | |
| 206 | + hasher.update(&buf[..n]); | |
| 207 | + } | |
| 208 | + Ok((size, hex::encode(hasher.finalize()))) | |
| 209 | +} | |
| 210 | + | |
| 211 | +/// Removes the oldest sets under `root` until `keep` remain. Only real directories (not links) named | |
| 212 | +/// `set-*` that hold a manifest file are touched, so a wrong `root` cannot cost unrelated data. Returns | |
| 213 | +/// how many were removed. | |
| 214 | +pub fn prune(root: &Path, keep: usize) -> Result<usize> { | |
| 215 | + let is_set = |p: &Path| { | |
| 216 | + let named = p | |
| 217 | + .file_name() | |
| 218 | + .and_then(|n| n.to_str()) | |
| 219 | + .is_some_and(|n| n.starts_with(SET_PREFIX)); | |
| 220 | + let real_dir = std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_dir()); | |
| 221 | + let manifest = | |
| 222 | + std::fs::symlink_metadata(p.join(MANIFEST_FILE)).is_ok_and(|m| m.file_type().is_file()); | |
| 223 | + named && real_dir && manifest | |
| 224 | + }; | |
| 225 | + let mut sets: Vec<PathBuf> = match std::fs::read_dir(root) { | |
| 226 | + Ok(entries) => entries | |
| 227 | + .filter_map(|e| e.ok().map(|e| e.path())) | |
| 228 | + .filter(|p| is_set(p)) | |
| 229 | + .collect(), | |
| 230 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0), | |
| 231 | + Err(e) => return Err(e.into()), | |
| 232 | + }; | |
| 233 | + // Names carry fixed-width UTC stamps, so name order is time order. | |
| 234 | + sets.sort(); | |
| 235 | + let excess = sets.len().saturating_sub(keep); | |
| 236 | + for old in sets.iter().take(excess) { | |
| 237 | + std::fs::remove_dir_all(old)?; | |
| 238 | + } | |
| 239 | + Ok(excess) | |
| 240 | +} | |
| 241 | + | |
| 242 | +/// Reads and checks the shape of a manifest: it must parse, be the known format, and name the snapshot | |
| 243 | +/// `im.db`. | |
| 244 | +pub fn read_manifest(set: &Path) -> Result<Manifest> { | |
| 245 | + let text = std::fs::read_to_string(set.join(MANIFEST_FILE)) | |
| 246 | + .map_err(|_| Error::Invalid("backup manifest is missing".into()))?; | |
| 247 | + let manifest: Manifest = serde_json::from_str(&text) | |
| 248 | + .map_err(|_| Error::Invalid("backup manifest is not valid".into()))?; | |
| 249 | + if manifest.format != FORMAT || manifest.database.name != DB_FILE { | |
| 250 | + return Err(Error::Invalid("backup manifest is not valid".into())); | |
| 251 | + } | |
| 252 | + Ok(manifest) | |
| 253 | +} | |
| 254 | + | |
| 255 | +/// Checks a set without changing it: every listed file matches its hash, no file is missing or unlisted, | |
| 256 | +/// and the snapshot passes `PRAGMA integrity_check` with contiguous migrations. The snapshot is checked | |
| 257 | +/// on a copy in `scratch`, so opening it cannot write WAL files into the set. | |
| 258 | +pub async fn verify_set(set: &Path, scratch: &Path) -> Result<Manifest> { | |
| 259 | + let manifest = read_manifest(set)?; | |
| 260 | + check_entry(set, &manifest.database)?; | |
| 261 | + let mut listed = Vec::new(); | |
| 262 | + for photo in &manifest.photos { | |
| 263 | + let Some(id) = photo.name.strip_prefix("photos/") else { | |
| 264 | + return Err(Error::Invalid( | |
| 265 | + "backup manifest names a file outside photos".into(), | |
| 266 | + )); | |
| 267 | + }; | |
| 268 | + if !is_plain_name(id) { | |
| 269 | + return Err(Error::Invalid("backup manifest names an odd file".into())); | |
| 270 | + } | |
| 271 | + check_entry(set, photo)?; | |
| 272 | + listed.push(id.to_owned()); | |
| 273 | + } | |
| 274 | + // Nothing may be in the set that the manifest does not name. | |
| 275 | + let photos_dir = set.join(PHOTOS_DIR); | |
| 276 | + if std::fs::symlink_metadata(&photos_dir).is_ok() { | |
| 277 | + let mut found = plain_names(&photos_dir)?; | |
| 278 | + listed.sort(); | |
| 279 | + found.sort(); | |
| 280 | + if found != listed { | |
| 281 | + return Err(Error::Invalid( | |
| 282 | + "backup photos do not match its manifest".into(), | |
| 283 | + )); | |
| 284 | + } | |
| 285 | + } | |
| 286 | + let on_disk = std::fs::read_dir(set)?.count(); | |
| 287 | + let expected = 2 + usize::from(std::fs::symlink_metadata(&photos_dir).is_ok()); | |
| 288 | + if on_disk != expected { | |
| 289 | + return Err(Error::Invalid( | |
| 290 | + "backup set holds files its manifest does not list".into(), | |
| 291 | + )); | |
| 292 | + } | |
| 293 | + std::fs::create_dir_all(scratch)?; | |
| 294 | + let copy = scratch.join("verify.db"); | |
| 295 | + std::fs::copy(set.join(DB_FILE), ©)?; | |
| 296 | + let checked = check_database(©).await; | |
| 297 | + for suffix in ["", "-wal", "-shm"] { | |
| 298 | + let _ = std::fs::remove_file(format!("{}{suffix}", copy.display())); | |
| 299 | + } | |
| 300 | + checked?; | |
| 301 | + Ok(manifest) | |
| 302 | +} | |
| 303 | + | |
| 304 | +/// Checks one listed file against its size and hash. | |
| 305 | +fn check_entry(set: &Path, entry: &FileEntry) -> Result<()> { | |
| 306 | + let path = set.join(&entry.name); | |
| 307 | + let meta = std::fs::symlink_metadata(&path) | |
| 308 | + .map_err(|_| Error::Invalid(format!("backup file {} is missing", entry.name)))?; | |
| 309 | + if !meta.file_type().is_file() { | |
| 310 | + return Err(Error::Invalid(format!( | |
| 311 | + "backup file {} is not a file", | |
| 312 | + entry.name | |
| 313 | + ))); | |
| 314 | + } | |
| 315 | + let (size, sha256) = file_digest(&path)?; | |
| 316 | + if size != entry.size || sha256 != entry.sha256 { | |
| 317 | + return Err(Error::Invalid(format!( | |
| 318 | + "backup file {} does not match its manifest", | |
| 319 | + entry.name | |
| 320 | + ))); | |
| 321 | + } | |
| 322 | + Ok(()) | |
| 323 | +} | |
| 324 | + | |
| 325 | +/// Runs `PRAGMA integrity_check` on the database at `path` and checks that the recorded migrations are | |
| 326 | +/// exactly `1..=N` for the N this build knows. | |
| 327 | +pub async fn check_database(path: &Path) -> Result<()> { | |
| 328 | + let text = path | |
| 329 | + .to_str() | |
| 330 | + .ok_or_else(|| Error::Config("database path is not UTF-8".into()))?; | |
| 331 | + let db = Builder::new_local(text).build().await.map_err(db_err)?; | |
| 332 | + let conn = db.connect().map_err(db_err)?; | |
| 333 | + let checks = fetch_all(&conn, "PRAGMA integrity_check", (), |row| col_text(row, 0)).await?; | |
| 334 | + if checks != ["ok"] { | |
| 335 | + return Err(Error::Invalid(format!( | |
| 336 | + "database integrity check failed: {checks:?}" | |
| 337 | + ))); | |
| 338 | + } | |
| 339 | + let versions = fetch_all( | |
| 340 | + &conn, | |
| 341 | + "SELECT version FROM schema_migrations ORDER BY version", | |
| 342 | + (), | |
| 343 | + |row| col_int(row, 0), | |
| 344 | + ) | |
| 345 | + .await?; | |
| 346 | + let expected: Vec<i64> = MIGRATIONS.iter().map(|(v, _)| i64::from(*v)).collect(); | |
| 347 | + if versions != expected { | |
| 348 | + return Err(Error::Invalid(format!( | |
| 349 | + "database migrations are {versions:?}, expected {expected:?}" | |
| 350 | + ))); | |
| 351 | + } | |
| 352 | + Ok(()) | |
| 353 | +} | |
| 354 | + | |
| 355 | +/// Restores the database and photos from `set`. Verifies the whole set first, then moves the current | |
| 356 | +/// database (with its sidecar files) and photo directory into `data_dir/restore-<stamp>/`, and puts the | |
| 357 | +/// set's copies in their place. `database` must lie inside `data_dir`. | |
| 358 | +pub async fn restore( | |
| 359 | + data_dir: &Path, | |
| 360 | + database: &Path, | |
| 361 | + set: &Path, | |
| 362 | + stamp: &str, | |
| 363 | +) -> Result<RestoreOutcome> { | |
| 364 | + let data_dir = std::fs::canonicalize(data_dir)?; | |
| 365 | + let parent = database | |
| 366 | + .parent() | |
| 367 | + .filter(|p| !p.as_os_str().is_empty()) | |
| 368 | + .unwrap_or(Path::new(".")); | |
| 369 | + if !std::fs::canonicalize(parent)?.starts_with(&data_dir) { | |
| 370 | + return Err(Error::Config( | |
| 371 | + "restore only replaces a database inside data_dir".into(), | |
| 372 | + )); | |
| 373 | + } | |
| 374 | + let previous = data_dir.join(format!("restore-{stamp}")); | |
| 375 | + if std::fs::symlink_metadata(&previous).is_ok() { | |
| 376 | + return Err(Error::Conflict(format!( | |
| 377 | + "{} already exists", | |
| 378 | + previous.display() | |
| 379 | + ))); | |
| 380 | + } | |
| 381 | + let scratch = data_dir.join(format!(".verify-{stamp}")); | |
| 382 | + let manifest = verify_set(set, &scratch).await; | |
| 383 | + let _ = std::fs::remove_dir_all(&scratch); | |
| 384 | + let manifest = manifest?; | |
| 385 | + | |
| 386 | + private_dir(&previous)?; | |
| 387 | + // The database moves aside with its sidecars; the set's copy is staged and then renamed in. | |
| 388 | + let staged = previous.join("incoming.db"); | |
| 389 | + std::fs::copy(set.join(DB_FILE), &staged)?; | |
| 390 | + std::fs::File::open(&staged)?.sync_all()?; | |
| 391 | + for suffix in ["", "-wal", "-shm"] { | |
| 392 | + let mut from = database.as_os_str().to_owned(); | |
| 393 | + from.push(suffix); | |
| 394 | + let from = PathBuf::from(from); | |
| 395 | + if std::fs::symlink_metadata(&from).is_ok() { | |
| 396 | + let mut to = previous.join("database"); | |
| 397 | + to.as_mut_os_string().push(suffix); | |
| 398 | + std::fs::rename(&from, &to)?; | |
| 399 | + } | |
| 400 | + } | |
| 401 | + std::fs::rename(&staged, database)?; | |
| 402 | + | |
| 403 | + let photos = data_dir.join(PHOTOS_DIR); | |
| 404 | + if std::fs::symlink_metadata(&photos).is_ok() { | |
| 405 | + std::fs::rename(&photos, previous.join(PHOTOS_DIR))?; | |
| 406 | + } | |
| 407 | + private_dir(&photos)?; | |
| 408 | + for photo in &manifest.photos { | |
| 409 | + let id = photo.name.trim_start_matches("photos/"); | |
| 410 | + let target = photos.join(id); | |
| 411 | + std::fs::copy(set.join(&photo.name), &target)?; | |
| 412 | + std::fs::File::open(&target)?.sync_all()?; | |
| 413 | + } | |
| 414 | + std::fs::File::open(&data_dir)?.sync_all()?; | |
| 415 | + Ok(RestoreOutcome { | |
| 416 | + photos: manifest.photos.len(), | |
| 417 | + previous, | |
| 418 | + }) | |
| 419 | +} | |
| 420 | + | |
| 421 | +#[cfg(test)] | |
| 422 | +mod tests { | |
| 423 | + use super::*; | |
| 424 | + | |
| 425 | + /// A store with one user and one photo, written as a set under `dir`. | |
| 426 | + async fn sample_set(dir: &Path) -> (Store, PathBuf) { | |
| 427 | + let store = Store::open(&dir.join("im.db")).await.unwrap(); | |
| 428 | + store | |
| 429 | + .create_first_admin("ada@example.com", "Ada", "h") | |
| 430 | + .await | |
| 431 | + .unwrap(); | |
| 432 | + std::fs::create_dir_all(dir.join(PHOTOS_DIR)).unwrap(); | |
| 433 | + std::fs::write(dir.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO"), b"png-bytes").unwrap(); | |
| 434 | + let set = write_set(&store, dir, &dir.join("backups"), "2026-10-28T10-00-00") | |
| 435 | + .await | |
| 436 | + .unwrap(); | |
| 437 | + (store, set) | |
| 438 | + } | |
| 439 | + | |
| 440 | + #[tokio::test] | |
| 441 | + async fn a_good_set_restores_and_a_tampered_one_is_refused() { | |
| 442 | + let dir = tempfile::tempdir().unwrap(); | |
| 443 | + let data = dir.path().join("data"); | |
| 444 | + std::fs::create_dir_all(&data).unwrap(); | |
| 445 | + let (_store, set) = sample_set(&data).await; | |
| 446 | + let scratch = data.join("scratch"); | |
| 447 | + | |
| 448 | + // A changed photo in the set makes the whole set refuse, and nothing is replaced. | |
| 449 | + let photo = set.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO"); | |
| 450 | + std::fs::write(&photo, b"evil-bytes").unwrap(); | |
| 451 | + assert!(verify_set(&set, &scratch).await.is_err()); | |
| 452 | + let refused = restore(&data, &data.join("im.db"), &set, "t1").await; | |
| 453 | + assert!(refused.is_err()); | |
| 454 | + assert!(!data.join("restore-t1").exists()); | |
| 455 | + | |
| 456 | + // Put the original bytes back: the set verifies and restores. | |
| 457 | + std::fs::write(&photo, b"png-bytes").unwrap(); | |
| 458 | + let outcome = restore(&data, &data.join("im.db"), &set, "t2") | |
| 459 | + .await | |
| 460 | + .unwrap(); | |
| 461 | + assert_eq!(outcome.photos, 1); | |
| 462 | + assert_eq!( | |
| 463 | + std::fs::read(data.join(PHOTOS_DIR).join("01HZXAMPLEPHOTO")).unwrap(), | |
| 464 | + b"png-bytes" | |
| 465 | + ); | |
| 466 | + } | |
| 467 | + | |
| 468 | + #[tokio::test] | |
| 469 | + async fn prune_touches_only_real_sets_with_a_manifest() { | |
| 470 | + let dir = tempfile::tempdir().unwrap(); | |
| 471 | + let root = dir.path(); | |
| 472 | + for name in ["set-1", "set-2", "set-3"] { | |
| 473 | + std::fs::create_dir_all(root.join(name)).unwrap(); | |
| 474 | + std::fs::write(root.join(name).join(MANIFEST_FILE), b"{}").unwrap(); | |
| 475 | + } | |
| 476 | + std::fs::create_dir_all(root.join("notes")).unwrap(); | |
| 477 | + assert_eq!(prune(root, 2).unwrap(), 1); | |
| 478 | + assert!(!root.join("set-1").exists()); | |
| 479 | + assert!(root.join("set-2").exists() && root.join("set-3").exists()); | |
| 480 | + assert!(root.join("notes").exists()); | |
| 481 | + } | |
| 482 | +} |
crates/im-core/src/config.rsmodified+86 -29
| @@ -137,9 +137,10 @@ impl BackupConfig { | ||
| 137 | 137 | } |
| 138 | 138 | } |
| 139 | 139 | |
| 140 | -/// Sign-in policy. These are the file values; a value saved in the admin UI wins over them once that | |
| 141 | -/// UI exists (`docs/architecture.md` section 7). | |
| 142 | -#[derive(Debug, Clone, Deserialize)] | |
| 140 | +/// Sign-in policy. These are the file values. A value saved in the admin UI is stored in `settings` | |
| 141 | +/// under `policy.<name>` and wins over them (`docs/architecture.md` section 7); see | |
| 142 | +/// [`PolicyConfig::set`] and [`Config::explicit_policy`]. | |
| 143 | +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] | |
| 143 | 144 | #[serde(deny_unknown_fields, default)] |
| 144 | 145 | pub struct PolicyConfig { |
| 145 | 146 | /// An administrator without two-factor sign-in is sent to enrol it after signing in, and cannot |
| @@ -159,6 +160,16 @@ pub struct PolicyConfig { | ||
| 159 | 160 | pub email_change_hours: u32, |
| 160 | 161 | } |
| 161 | 162 | |
| 163 | +/// The policy keys, in the order the admin page shows them. Each is stored as `policy.<key>`. | |
| 164 | +pub const POLICY_KEYS: [&str; 6] = [ | |
| 165 | + "require_2fa_for_admins", | |
| 166 | + "max_sessions", | |
| 167 | + "session_max_days", | |
| 168 | + "invite_days", | |
| 169 | + "reset_minutes", | |
| 170 | + "email_change_hours", | |
| 171 | +]; | |
| 172 | + | |
| 162 | 173 | impl Default for PolicyConfig { |
| 163 | 174 | fn default() -> Self { |
| 164 | 175 | Self { |
| @@ -172,6 +183,66 @@ impl Default for PolicyConfig { | ||
| 172 | 183 | } |
| 173 | 184 | } |
| 174 | 185 | |
| 186 | +impl PolicyConfig { | |
| 187 | + /// The ranges of the policy values. Used for the file and for every value saved in the UI. | |
| 188 | + pub fn validate(&self) -> Result<()> { | |
| 189 | + if self.max_sessions == 0 { | |
| 190 | + return Err(Error::Config( | |
| 191 | + "[policy] max_sessions must be at least 1".into(), | |
| 192 | + )); | |
| 193 | + } | |
| 194 | + if !(1..=365).contains(&self.session_max_days) { | |
| 195 | + return Err(Error::Config( | |
| 196 | + "[policy] session_max_days must be between 1 and 365".into(), | |
| 197 | + )); | |
| 198 | + } | |
| 199 | + if !(1..=30).contains(&self.invite_days) { | |
| 200 | + return Err(Error::Config( | |
| 201 | + "[policy] invite_days must be between 1 and 30".into(), | |
| 202 | + )); | |
| 203 | + } | |
| 204 | + if !(5..=1440).contains(&self.reset_minutes) { | |
| 205 | + return Err(Error::Config( | |
| 206 | + "[policy] reset_minutes must be between 5 and 1440".into(), | |
| 207 | + )); | |
| 208 | + } | |
| 209 | + if !(1..=168).contains(&self.email_change_hours) { | |
| 210 | + return Err(Error::Config( | |
| 211 | + "[policy] email_change_hours must be between 1 and 168".into(), | |
| 212 | + )); | |
| 213 | + } | |
| 214 | + Ok(()) | |
| 215 | + } | |
| 216 | + | |
| 217 | + /// Returns a copy with `key` set to `value`, checked. A key outside [`POLICY_KEYS`] or a value | |
| 218 | + /// that does not parse or is out of range is an error that names the key. | |
| 219 | + pub fn set(&self, key: &str, value: &str) -> Result<PolicyConfig> { | |
| 220 | + let mut next = self.clone(); | |
| 221 | + let number = |text: &str| -> Result<u32> { | |
| 222 | + text.trim() | |
| 223 | + .parse::<u32>() | |
| 224 | + .map_err(|_| Error::Invalid(format!("{key} must be a whole number"))) | |
| 225 | + }; | |
| 226 | + match key { | |
| 227 | + "require_2fa_for_admins" => { | |
| 228 | + next.require_2fa_for_admins = match value.trim() { | |
| 229 | + "true" | "on" | "1" => true, | |
| 230 | + "false" | "off" | "0" | "" => false, | |
| 231 | + _ => return Err(Error::Invalid(format!("{key} must be true or false"))), | |
| 232 | + }; | |
| 233 | + } | |
| 234 | + "max_sessions" => next.max_sessions = number(value)?, | |
| 235 | + "session_max_days" => next.session_max_days = number(value)?, | |
| 236 | + "invite_days" => next.invite_days = number(value)?, | |
| 237 | + "reset_minutes" => next.reset_minutes = number(value)?, | |
| 238 | + "email_change_hours" => next.email_change_hours = number(value)?, | |
| 239 | + other => return Err(Error::Invalid(format!("{other} is not a policy setting"))), | |
| 240 | + } | |
| 241 | + next.validate().map_err(|e| Error::Invalid(e.to_string()))?; | |
| 242 | + Ok(next) | |
| 243 | + } | |
| 244 | +} | |
| 245 | + | |
| 175 | 246 | /// The whole file. Field names are the TOML keys. |
| 176 | 247 | #[derive(Debug, Clone, Deserialize)] |
| 177 | 248 | #[serde(deny_unknown_fields)] |
| @@ -201,6 +272,10 @@ pub struct Config { | ||
| 201 | 272 | /// Sign-in policy. |
| 202 | 273 | #[serde(default)] |
| 203 | 274 | pub policy: PolicyConfig, |
| 275 | + /// The policy keys that the file sets explicitly, so the admin page can say "file" rather than | |
| 276 | + /// "default". Not read from TOML: [`Config::parse`] fills it. | |
| 277 | + #[serde(skip)] | |
| 278 | + pub explicit_policy: Vec<String>, | |
| 204 | 279 | } |
| 205 | 280 | |
| 206 | 281 | impl Config { |
| @@ -225,8 +300,14 @@ impl Config { | ||
| 225 | 300 | |
| 226 | 301 | /// Parses and validates TOML text. Used by [`Config::load`] and by tests. |
| 227 | 302 | pub fn parse(text: &str) -> Result<Config> { |
| 228 | - let config: Config = toml::from_str(text).map_err(|e| Error::Config(format!("{e}")))?; | |
| 303 | + let mut config: Config = toml::from_str(text).map_err(|e| Error::Config(format!("{e}")))?; | |
| 229 | 304 | config.validate()?; |
| 305 | + // A second, loose read of the same text: which [policy] keys the file names. | |
| 306 | + if let Ok(table) = text.parse::<toml::Table>() | |
| 307 | + && let Some(toml::Value::Table(policy)) = table.get("policy") | |
| 308 | + { | |
| 309 | + config.explicit_policy = policy.keys().cloned().collect(); | |
| 310 | + } | |
| 230 | 311 | Ok(config) |
| 231 | 312 | } |
| 232 | 313 | |
| @@ -249,31 +330,7 @@ impl Config { | ||
| 249 | 330 | return Err(Error::Config("[backup] keep must be at least 1".into())); |
| 250 | 331 | } |
| 251 | 332 | } |
| 252 | - if self.policy.max_sessions == 0 { | |
| 253 | - return Err(Error::Config( | |
| 254 | - "[policy] max_sessions must be at least 1".into(), | |
| 255 | - )); | |
| 256 | - } | |
| 257 | - if !(1..=365).contains(&self.policy.session_max_days) { | |
| 258 | - return Err(Error::Config( | |
| 259 | - "[policy] session_max_days must be between 1 and 365".into(), | |
| 260 | - )); | |
| 261 | - } | |
| 262 | - if !(1..=30).contains(&self.policy.invite_days) { | |
| 263 | - return Err(Error::Config( | |
| 264 | - "[policy] invite_days must be between 1 and 30".into(), | |
| 265 | - )); | |
| 266 | - } | |
| 267 | - if !(5..=1440).contains(&self.policy.reset_minutes) { | |
| 268 | - return Err(Error::Config( | |
| 269 | - "[policy] reset_minutes must be between 5 and 1440".into(), | |
| 270 | - )); | |
| 271 | - } | |
| 272 | - if !(1..=168).contains(&self.policy.email_change_hours) { | |
| 273 | - return Err(Error::Config( | |
| 274 | - "[policy] email_change_hours must be between 1 and 168".into(), | |
| 275 | - )); | |
| 276 | - } | |
| 333 | + self.policy.validate()?; | |
| 277 | 334 | self.validate_smtp()?; |
| 278 | 335 | let hc = &self.backup.healthcheck_url; |
| 279 | 336 | if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) { |
crates/im-core/src/lib.rsmodified+1 -0
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | //! This crate has no HTTP code. It holds the pieces every other part of `im` depends on, so that |
| 4 | 4 | //! the web binary cannot get a security primitive or a database rule wrong by re-implementing it. |
| 5 | 5 | |
| 6 | +pub mod backup; | |
| 6 | 7 | pub mod config; |
| 7 | 8 | pub mod error; |
| 8 | 9 | pub mod jwt; |
crates/im-core/src/model.rsmodified+60 -0
| @@ -158,6 +158,46 @@ pub enum AuditAction { | ||
| 158 | 158 | EmailChangeCancelled, |
| 159 | 159 | /// The address of an account was changed. |
| 160 | 160 | EmailChanged, |
| 161 | + /// An administrator disabled an account. | |
| 162 | + UserDisabled, | |
| 163 | + /// An administrator enabled an account again. | |
| 164 | + UserEnabled, | |
| 165 | + /// An administrator made an account an administrator. | |
| 166 | + AdminGranted, | |
| 167 | + /// An administrator removed the administrator flag of an account. | |
| 168 | + AdminRemoved, | |
| 169 | + /// An administrator reset the two-factor sign-in of an account. | |
| 170 | + AdminTwoFactorReset, | |
| 171 | + /// An administrator ended every session of an account. | |
| 172 | + AdminSessionsRevoked, | |
| 173 | + /// An administrator deleted an account. | |
| 174 | + UserDeleted, | |
| 175 | + /// An administrator revoked an invitation. | |
| 176 | + InviteRevoked, | |
| 177 | + /// An administrator registered an OpenID client. | |
| 178 | + ClientCreated, | |
| 179 | + /// An administrator changed a client's settings. | |
| 180 | + ClientUpdated, | |
| 181 | + /// An administrator issued a new client secret. | |
| 182 | + ClientSecretRotated, | |
| 183 | + /// An administrator disabled a client. | |
| 184 | + ClientDisabled, | |
| 185 | + /// An administrator sent a failed mail again. | |
| 186 | + MailRetried, | |
| 187 | + /// An administrator gave up on a mail. | |
| 188 | + MailAbandoned, | |
| 189 | + /// An administrator queued a test mail. | |
| 190 | + MailTestQueued, | |
| 191 | + /// An administrator queued a message to everyone or to one address. | |
| 192 | + MessageSent, | |
| 193 | + /// An administrator saved policy settings. | |
| 194 | + SettingsChanged, | |
| 195 | + /// An administrator rotated the signing key. | |
| 196 | + KeyRotated, | |
| 197 | + /// An administrator retired a signing key. | |
| 198 | + KeyRetired, | |
| 199 | + /// A backup set was written (scheduled, or by `im backup now`). | |
| 200 | + BackupWritten, | |
| 161 | 201 | } |
| 162 | 202 | |
| 163 | 203 | impl AuditAction { |
| @@ -187,6 +227,26 @@ impl AuditAction { | ||
| 187 | 227 | AuditAction::EmailChangeConfirmed => "email_change.confirmed", |
| 188 | 228 | AuditAction::EmailChangeCancelled => "email_change.cancelled", |
| 189 | 229 | AuditAction::EmailChanged => "email.changed", |
| 230 | + AuditAction::UserDisabled => "user.disabled", | |
| 231 | + AuditAction::UserEnabled => "user.enabled", | |
| 232 | + AuditAction::AdminGranted => "admin.granted", | |
| 233 | + AuditAction::AdminRemoved => "admin.removed", | |
| 234 | + AuditAction::AdminTwoFactorReset => "admin.2fa_reset", | |
| 235 | + AuditAction::AdminSessionsRevoked => "admin.sessions_revoked", | |
| 236 | + AuditAction::UserDeleted => "user.deleted", | |
| 237 | + AuditAction::InviteRevoked => "invite.revoked", | |
| 238 | + AuditAction::ClientCreated => "client.created", | |
| 239 | + AuditAction::ClientUpdated => "client.updated", | |
| 240 | + AuditAction::ClientSecretRotated => "client.secret_rotated", | |
| 241 | + AuditAction::ClientDisabled => "client.disabled", | |
| 242 | + AuditAction::MailRetried => "mail.retried", | |
| 243 | + AuditAction::MailAbandoned => "mail.abandoned", | |
| 244 | + AuditAction::MailTestQueued => "mail.test", | |
| 245 | + AuditAction::MessageSent => "message.sent", | |
| 246 | + AuditAction::SettingsChanged => "settings.changed", | |
| 247 | + AuditAction::KeyRotated => "keys.rotated", | |
| 248 | + AuditAction::KeyRetired => "keys.retired", | |
| 249 | + AuditAction::BackupWritten => "backup.written", | |
| 190 | 250 | } |
| 191 | 251 | } |
| 192 | 252 | } |
crates/im-core/src/store/admin.rsadded+542 -0
| @@ -0,0 +1,542 @@ | ||
| 1 | +//! Writes and listings that only the administrator pages make: admin rights, enabling and deleting | |
| 2 | +//! accounts, the user search, clients and their services, the mail outbox, signing keys and the policy | |
| 3 | +//! overrides. | |
| 4 | +//! | |
| 5 | +//! The rules that must hold under concurrency are single conditional statements, so two requests cannot | |
| 6 | +//! both succeed: | |
| 7 | +//! | |
| 8 | +//! - the last enabled administrator cannot be demoted, disabled or deleted (`set_admin`, `delete_user`, | |
| 9 | +//! and the same guard in `users::disable_user`); | |
| 10 | +//! - the signing key that is current cannot be retired (`retire_signing_key`); | |
| 11 | +//! - a mail row is retried or abandoned only in the states that allow it (`retry_mail`, `abandon_mail`). | |
| 12 | +//! | |
| 13 | +//! Who may call these is decided by the web layer. Nothing here knows about the session. | |
| 14 | + | |
| 15 | +use turso::Row; | |
| 16 | + | |
| 17 | +use crate::error::{Error, Result}; | |
| 18 | +use crate::model::User; | |
| 19 | +use crate::store::backchannel::{self, EndReason}; | |
| 20 | +use crate::store::clients::{CLIENT_COLS, map_client}; | |
| 21 | +use crate::store::directory::{ChangeKind, record_change}; | |
| 22 | +use crate::store::invites::{Invite, map_invite}; | |
| 23 | +use crate::store::users::{USER_COLS, map_user}; | |
| 24 | +use crate::store::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish}; | |
| 25 | +use crate::time::now_stamp; | |
| 26 | + | |
| 27 | +/// The result of [`Store::set_admin`]. | |
| 28 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 29 | +pub enum AdminChange { | |
| 30 | + /// The flag was changed. | |
| 31 | + Changed, | |
| 32 | + /// The account already had that flag. | |
| 33 | + Unchanged, | |
| 34 | + /// The change would leave no enabled administrator, so it was refused. | |
| 35 | + LastAdmin, | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// One row of the mail outbox, as the administrator sees it. The body is never included. | |
| 39 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 40 | +pub struct OutboxRow { | |
| 41 | + /// ULID. Newer rows have larger ids. | |
| 42 | + pub id: String, | |
| 43 | + /// The mail kind. | |
| 44 | + pub kind: String, | |
| 45 | + /// The recipient address. | |
| 46 | + pub to_addr: String, | |
| 47 | + /// The subject. | |
| 48 | + pub subject: String, | |
| 49 | + /// `pending`, `sent`, `failed` or `abandoned`. | |
| 50 | + pub state: String, | |
| 51 | + /// Attempts made so far. | |
| 52 | + pub attempts: i64, | |
| 53 | + /// When the row is next due. | |
| 54 | + pub next_attempt_at: String, | |
| 55 | + /// The last failure, without secrets. | |
| 56 | + pub last_error: Option<String>, | |
| 57 | + /// When the row was queued. | |
| 58 | + pub created_at: String, | |
| 59 | +} | |
| 60 | + | |
| 61 | +/// The fields of a client that an administrator can edit. The URIs must already be checked. | |
| 62 | +#[derive(Debug, Clone)] | |
| 63 | +pub struct ClientEdit<'a> { | |
| 64 | + /// Display name. | |
| 65 | + pub name: &'a str, | |
| 66 | + /// Exact redirect URIs. | |
| 67 | + pub redirect_uris: &'a [String], | |
| 68 | + /// Exact post-logout redirect URIs. | |
| 69 | + pub post_logout_redirect_uris: &'a [String], | |
| 70 | + /// Back-channel logout endpoint, if any. | |
| 71 | + pub backchannel_logout_uri: Option<&'a str>, | |
| 72 | + /// Space-separated scopes. | |
| 73 | + pub allowed_scopes: &'a str, | |
| 74 | + /// Family key, if the client is a family service. Unique. | |
| 75 | + pub service_key: Option<&'a str>, | |
| 76 | +} | |
| 77 | + | |
| 78 | +impl Store { | |
| 79 | + /// Grants or removes instance administration. Removing it from the last enabled administrator is | |
| 80 | + /// refused by the same statement that would do it, so two parallel demotions cannot both succeed. | |
| 81 | + pub async fn set_admin(&self, user_id: &str, is_admin: bool) -> Result<AdminChange> { | |
| 82 | + let flag = i64::from(is_admin); | |
| 83 | + let conn = self.inner.conn.lock().await; | |
| 84 | + let changed = conn | |
| 85 | + .execute( | |
| 86 | + "UPDATE users SET is_admin = ?2, updated_at = ?3 \ | |
| 87 | + WHERE id = ?1 AND is_admin <> ?2 \ | |
| 88 | + AND (?2 = 1 OR disabled_at IS NOT NULL \ | |
| 89 | + OR (SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", | |
| 90 | + (user_id.to_string(), flag, now_stamp()), | |
| 91 | + ) | |
| 92 | + .await | |
| 93 | + .map_err(db_err)?; | |
| 94 | + if changed == 1 { | |
| 95 | + return Ok(AdminChange::Changed); | |
| 96 | + } | |
| 97 | + let current = fetch_opt( | |
| 98 | + &conn, | |
| 99 | + "SELECT is_admin FROM users WHERE id = ?1", | |
| 100 | + (user_id.to_string(),), | |
| 101 | + |row| col_int(row, 0), | |
| 102 | + ) | |
| 103 | + .await?; | |
| 104 | + match current { | |
| 105 | + None => Err(Error::NotFound), | |
| 106 | + Some(value) if value == flag => Ok(AdminChange::Unchanged), | |
| 107 | + Some(_) => Ok(AdminChange::LastAdmin), | |
| 108 | + } | |
| 109 | + } | |
| 110 | + | |
| 111 | + /// Number of enabled administrators. The admin pages show it and refuse to leave none. | |
| 112 | + pub async fn enabled_admin_count(&self) -> Result<u64> { | |
| 113 | + let conn = self.read_conn().await; | |
| 114 | + let count = fetch_opt( | |
| 115 | + &conn, | |
| 116 | + "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL", | |
| 117 | + (), | |
| 118 | + |row| col_int(row, 0), | |
| 119 | + ) | |
| 120 | + .await? | |
| 121 | + .unwrap_or(0); | |
| 122 | + u64::try_from(count).map_err(|_| Error::Database("negative count".into())) | |
| 123 | + } | |
| 124 | + | |
| 125 | + /// Clears the disabled mark of an account. The directory feed records the change. Returns false when | |
| 126 | + /// the account is missing or was not disabled. | |
| 127 | + pub async fn enable_user(&self, user_id: &str) -> Result<bool> { | |
| 128 | + let now = now_stamp(); | |
| 129 | + let conn = self.inner.conn.lock().await; | |
| 130 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 131 | + let outcome: Result<bool> = async { | |
| 132 | + let changed = tx | |
| 133 | + .execute( | |
| 134 | + "UPDATE users SET disabled_at = NULL, updated_at = ?2 \ | |
| 135 | + WHERE id = ?1 AND disabled_at IS NOT NULL", | |
| 136 | + (user_id.to_string(), now), | |
| 137 | + ) | |
| 138 | + .await | |
| 139 | + .map_err(db_err)?; | |
| 140 | + if changed != 1 { | |
| 141 | + return Ok(false); | |
| 142 | + } | |
| 143 | + record_change(&tx, user_id, ChangeKind::Member).await?; | |
| 144 | + Ok(true) | |
| 145 | + } | |
| 146 | + .await; | |
| 147 | + let result = finish(tx, outcome).await; | |
| 148 | + if matches!(result, Ok(true)) { | |
| 149 | + self.announce_directory(); | |
| 150 | + } | |
| 151 | + result | |
| 152 | + } | |
| 153 | + | |
| 154 | + /// Deletes an account and everything that belonged to it: sessions and their client links, recovery | |
| 155 | + /// codes, reset and email-change links, and a pending two-factor enrolment. The rows that remain | |
| 156 | + /// name the person only by id (audit entries and invitations that person sent). Back-channel logouts | |
| 157 | + /// are queued first, and the directory feed records a `deleted` change. The last enabled | |
| 158 | + /// administrator cannot be deleted. Returns false when there was no such account. | |
| 159 | + /// | |
| 160 | + /// The caller removes the profile photo file after this returns. | |
| 161 | + pub async fn delete_user(&self, user_id: &str) -> Result<bool> { | |
| 162 | + let now = now_stamp(); | |
| 163 | + let conn = self.inner.conn.lock().await; | |
| 164 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 165 | + let outcome: Result<bool> = async { | |
| 166 | + let exists = fetch_opt( | |
| 167 | + &tx, | |
| 168 | + "SELECT id FROM users WHERE id = ?1", | |
| 169 | + (user_id.to_string(),), | |
| 170 | + |row| col_text(row, 0), | |
| 171 | + ) | |
| 172 | + .await?; | |
| 173 | + if exists.is_none() { | |
| 174 | + return Ok(false); | |
| 175 | + } | |
| 176 | + // Queued before the sessions go, because the client links are read from them. | |
| 177 | + backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; | |
| 178 | + let removed = tx | |
| 179 | + .execute( | |
| 180 | + "DELETE FROM users WHERE id = ?1 \ | |
| 181 | + AND (is_admin = 0 OR disabled_at IS NOT NULL \ | |
| 182 | + OR (SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", | |
| 183 | + (user_id.to_string(),), | |
| 184 | + ) | |
| 185 | + .await | |
| 186 | + .map_err(db_err)?; | |
| 187 | + if removed != 1 { | |
| 188 | + // Returned as an error so the transaction, with its queued logouts, is rolled back. | |
| 189 | + return Err(Error::Conflict( | |
| 190 | + "the last enabled administrator cannot be deleted".into(), | |
| 191 | + )); | |
| 192 | + } | |
| 193 | + tx.execute( | |
| 194 | + "DELETE FROM settings WHERE key = ?1", | |
| 195 | + (format!("totp_pending:{user_id}"),), | |
| 196 | + ) | |
| 197 | + .await | |
| 198 | + .map_err(db_err)?; | |
| 199 | + record_change(&tx, user_id, ChangeKind::Deleted).await?; | |
| 200 | + Ok(true) | |
| 201 | + } | |
| 202 | + .await; | |
| 203 | + let result = finish(tx, outcome).await; | |
| 204 | + if matches!(result, Ok(true)) { | |
| 205 | + self.announce_directory(); | |
| 206 | + } | |
| 207 | + result | |
| 208 | + } | |
| 209 | + | |
| 210 | + /// A page of accounts, newest first. `search` matches a part of the address or the name, in any | |
| 211 | + /// case. `after` is the `(created_at, id)` of the last account of the previous page. Returns up to | |
| 212 | + /// `limit` accounts. | |
| 213 | + pub async fn list_users( | |
| 214 | + &self, | |
| 215 | + search: Option<&str>, | |
| 216 | + after: Option<(&str, &str)>, | |
| 217 | + limit: u32, | |
| 218 | + ) -> Result<Vec<User>> { | |
| 219 | + let term = search | |
| 220 | + .map(|s| s.trim().to_lowercase()) | |
| 221 | + .filter(|s| !s.is_empty()); | |
| 222 | + let (after_at, after_id) = match after { | |
| 223 | + Some((at, id)) => (Some(at.to_owned()), Some(id.to_owned())), | |
| 224 | + None => (None, None), | |
| 225 | + }; | |
| 226 | + let conn = self.read_conn().await; | |
| 227 | + fetch_all( | |
| 228 | + &conn, | |
| 229 | + &format!( | |
| 230 | + "SELECT {USER_COLS} FROM users \ | |
| 231 | + WHERE (?1 IS NULL OR instr(email_folded, ?1) > 0 OR instr(lower(name), ?1) > 0) \ | |
| 232 | + AND (?2 IS NULL OR created_at < ?2 OR (created_at = ?2 AND id < ?3)) \ | |
| 233 | + ORDER BY created_at DESC, id DESC LIMIT ?4" | |
| 234 | + ), | |
| 235 | + (term, after_at, after_id, i64::from(limit)), | |
| 236 | + map_user, | |
| 237 | + ) | |
| 238 | + .await | |
| 239 | + } | |
| 240 | + | |
| 241 | + /// Invitations that can still be used, newest first. | |
| 242 | + pub async fn pending_invites(&self) -> Result<Vec<Invite>> { | |
| 243 | + let conn = self.read_conn().await; | |
| 244 | + fetch_all( | |
| 245 | + &conn, | |
| 246 | + "SELECT token_hash, email_folded, is_admin, expires_at, accepted_at FROM invites \ | |
| 247 | + WHERE accepted_at IS NULL AND expires_at > ?1 ORDER BY created_at DESC, token_hash", | |
| 248 | + (now_stamp(),), | |
| 249 | + map_invite, | |
| 250 | + ) | |
| 251 | + .await | |
| 252 | + } | |
| 253 | + | |
| 254 | + /// The invitation with this token hash, while it can still be used. | |
| 255 | + pub async fn pending_invite(&self, token_hash: &str) -> Result<Option<Invite>> { | |
| 256 | + let conn = self.read_conn().await; | |
| 257 | + fetch_opt( | |
| 258 | + &conn, | |
| 259 | + "SELECT token_hash, email_folded, is_admin, expires_at, accepted_at FROM invites \ | |
| 260 | + WHERE token_hash = ?1 AND accepted_at IS NULL AND expires_at > ?2", | |
| 261 | + (token_hash.to_string(), now_stamp()), | |
| 262 | + map_invite, | |
| 263 | + ) | |
| 264 | + .await | |
| 265 | + } | |
| 266 | + | |
| 267 | + /// Deletes an invitation that was not used. Returns false when it was used or is unknown. | |
| 268 | + pub async fn revoke_invite(&self, token_hash: &str) -> Result<bool> { | |
| 269 | + let conn = self.inner.conn.lock().await; | |
| 270 | + let changed = conn | |
| 271 | + .execute( | |
| 272 | + "DELETE FROM invites WHERE token_hash = ?1 AND accepted_at IS NULL", | |
| 273 | + (token_hash.to_string(),), | |
| 274 | + ) | |
| 275 | + .await | |
| 276 | + .map_err(db_err)?; | |
| 277 | + Ok(changed == 1) | |
| 278 | + } | |
| 279 | + | |
| 280 | + /// Ends every live session of a person, with their back-channel logouts. Returns the ids ended. | |
| 281 | + pub async fn end_all_sessions(&self, user_id: &str, reason: EndReason) -> Result<Vec<String>> { | |
| 282 | + self.end_matching(user_id, None, reason).await | |
| 283 | + } | |
| 284 | + | |
| 285 | + /// Updates the editable fields of a client. A family key that another client holds is a conflict. | |
| 286 | + /// Services that pointed to this client under another key are unlinked in the same transaction. | |
| 287 | + /// Returns false when there is no such client. | |
| 288 | + pub async fn update_client(&self, id: &str, edit: &ClientEdit<'_>) -> Result<bool> { | |
| 289 | + let redirect_uris = | |
| 290 | + serde_json::to_string(edit.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?; | |
| 291 | + let post_logout = serde_json::to_string(edit.post_logout_redirect_uris) | |
| 292 | + .map_err(|e| Error::Invalid(e.to_string()))?; | |
| 293 | + let conn = self.inner.conn.lock().await; | |
| 294 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 295 | + let outcome: Result<bool> = async { | |
| 296 | + let changed = tx | |
| 297 | + .execute( | |
| 298 | + "UPDATE clients SET name = ?2, redirect_uris = ?3, post_logout_redirect_uris = ?4, \ | |
| 299 | + backchannel_logout_uri = ?5, allowed_scopes = ?6, service_key = ?7 \ | |
| 300 | + WHERE id = ?1", | |
| 301 | + ( | |
| 302 | + id.to_string(), | |
| 303 | + edit.name.to_string(), | |
| 304 | + redirect_uris, | |
| 305 | + post_logout, | |
| 306 | + edit.backchannel_logout_uri.map(str::to_owned), | |
| 307 | + edit.allowed_scopes.to_string(), | |
| 308 | + edit.service_key.map(str::to_owned), | |
| 309 | + ), | |
| 310 | + ) | |
| 311 | + .await | |
| 312 | + .map_err(|e| { | |
| 313 | + if e.to_string().contains("UNIQUE") { | |
| 314 | + Error::Conflict("that family key is already used by another client".into()) | |
| 315 | + } else { | |
| 316 | + db_err(e) | |
| 317 | + } | |
| 318 | + })?; | |
| 319 | + if changed != 1 { | |
| 320 | + return Ok(false); | |
| 321 | + } | |
| 322 | + tx.execute( | |
| 323 | + "UPDATE services SET client_id = NULL WHERE client_id = ?1 AND key IS NOT ?2", | |
| 324 | + (id.to_string(), edit.service_key.map(str::to_owned)), | |
| 325 | + ) | |
| 326 | + .await | |
| 327 | + .map_err(db_err)?; | |
| 328 | + Ok(true) | |
| 329 | + } | |
| 330 | + .await; | |
| 331 | + finish(tx, outcome).await | |
| 332 | + } | |
| 333 | + | |
| 334 | + /// Replaces the secret hash of a client. The old secret stops working at once. | |
| 335 | + pub async fn rotate_client_secret(&self, id: &str, secret_hash: &str) -> Result<bool> { | |
| 336 | + let conn = self.inner.conn.lock().await; | |
| 337 | + let changed = conn | |
| 338 | + .execute( | |
| 339 | + "UPDATE clients SET secret_hash = ?2, secret_rotated_at = ?3 WHERE id = ?1", | |
| 340 | + (id.to_string(), secret_hash.to_string(), now_stamp()), | |
| 341 | + ) | |
| 342 | + .await | |
| 343 | + .map_err(db_err)?; | |
| 344 | + Ok(changed == 1) | |
| 345 | + } | |
| 346 | + | |
| 347 | + /// Creates or updates the switcher row of a family service and links it to its client. | |
| 348 | + pub async fn link_service( | |
| 349 | + &self, | |
| 350 | + key: &str, | |
| 351 | + name: &str, | |
| 352 | + url: &str, | |
| 353 | + client_id: &str, | |
| 354 | + ) -> Result<()> { | |
| 355 | + let conn = self.inner.conn.lock().await; | |
| 356 | + conn.execute( | |
| 357 | + "INSERT INTO services (key, name, url, position, client_id) \ | |
| 358 | + VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), 0) + 1 FROM services), ?4) \ | |
| 359 | + ON CONFLICT(key) DO UPDATE SET name = excluded.name, url = excluded.url, \ | |
| 360 | + client_id = excluded.client_id", | |
| 361 | + ( | |
| 362 | + key.to_string(), | |
| 363 | + name.to_string(), | |
| 364 | + url.to_string(), | |
| 365 | + client_id.to_string(), | |
| 366 | + ), | |
| 367 | + ) | |
| 368 | + .await | |
| 369 | + .map_err(db_err)?; | |
| 370 | + Ok(()) | |
| 371 | + } | |
| 372 | + | |
| 373 | + /// The client with this id, enabled or not. Used by the admin client pages. | |
| 374 | + pub async fn client_row(&self, id: &str) -> Result<Option<crate::model::Client>> { | |
| 375 | + let conn = self.read_conn().await; | |
| 376 | + fetch_opt( | |
| 377 | + &conn, | |
| 378 | + &format!("SELECT {} FROM clients WHERE id = ?1", CLIENT_COLS), | |
| 379 | + (id.to_string(),), | |
| 380 | + map_client, | |
| 381 | + ) | |
| 382 | + .await | |
| 383 | + } | |
| 384 | + | |
| 385 | + /// One page of the mail outbox, newest first, optionally only one state. `after` is the id of the | |
| 386 | + /// last row of the previous page. | |
| 387 | + pub async fn outbox_page( | |
| 388 | + &self, | |
| 389 | + state: Option<&str>, | |
| 390 | + after: Option<&str>, | |
| 391 | + limit: u32, | |
| 392 | + ) -> Result<Vec<OutboxRow>> { | |
| 393 | + let conn = self.read_conn().await; | |
| 394 | + fetch_all( | |
| 395 | + &conn, | |
| 396 | + "SELECT id, kind, to_addr, subject, state, attempts, next_attempt_at, last_error, created_at \ | |
| 397 | + FROM mail_outbox \ | |
| 398 | + WHERE (?1 IS NULL OR state = ?1) AND (?2 IS NULL OR id < ?2) \ | |
| 399 | + ORDER BY id DESC LIMIT ?3", | |
| 400 | + ( | |
| 401 | + state.map(str::to_owned), | |
| 402 | + after.map(str::to_owned), | |
| 403 | + i64::from(limit), | |
| 404 | + ), | |
| 405 | + map_outbox, | |
| 406 | + ) | |
| 407 | + .await | |
| 408 | + } | |
| 409 | + | |
| 410 | + /// How many rows the outbox holds in each state. | |
| 411 | + pub async fn outbox_counts(&self) -> Result<Vec<(String, i64)>> { | |
| 412 | + let conn = self.read_conn().await; | |
| 413 | + fetch_all( | |
| 414 | + &conn, | |
| 415 | + "SELECT state, COUNT(*) FROM mail_outbox GROUP BY state ORDER BY state", | |
| 416 | + (), | |
| 417 | + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), | |
| 418 | + ) | |
| 419 | + .await | |
| 420 | + } | |
| 421 | + | |
| 422 | + /// Sends a failed row again now. Only a `failed` row whose body is still held can be retried. | |
| 423 | + pub async fn retry_mail(&self, id: &str) -> Result<bool> { | |
| 424 | + let conn = self.inner.conn.lock().await; | |
| 425 | + let changed = conn | |
| 426 | + .execute( | |
| 427 | + "UPDATE mail_outbox SET state = 'pending', next_attempt_at = ?2 \ | |
| 428 | + WHERE id = ?1 AND state = 'failed' AND body_text <> ''", | |
| 429 | + (id.to_string(), now_stamp()), | |
| 430 | + ) | |
| 431 | + .await | |
| 432 | + .map_err(db_err)?; | |
| 433 | + Ok(changed == 1) | |
| 434 | + } | |
| 435 | + | |
| 436 | + /// Gives up on a row that is not yet sent: its body is blanked, as the worker does on abandonment. | |
| 437 | + pub async fn abandon_mail(&self, id: &str) -> Result<bool> { | |
| 438 | + let conn = self.inner.conn.lock().await; | |
| 439 | + let changed = conn | |
| 440 | + .execute( | |
| 441 | + "UPDATE mail_outbox SET state = 'abandoned', body_text = '', \ | |
| 442 | + last_error = 'abandoned by an administrator' \ | |
| 443 | + WHERE id = ?1 AND state IN ('pending', 'failed')", | |
| 444 | + (id.to_string(),), | |
| 445 | + ) | |
| 446 | + .await | |
| 447 | + .map_err(db_err)?; | |
| 448 | + Ok(changed == 1) | |
| 449 | + } | |
| 450 | + | |
| 451 | + /// Retires a published signing key that is not the current one. Its public key stays published for | |
| 452 | + /// the usual overlap, so tokens it signed still verify. The current key cannot be retired: the | |
| 453 | + /// statement excludes it, so a token can always be signed. | |
| 454 | + pub async fn retire_signing_key(&self, kid: &str) -> Result<bool> { | |
| 455 | + let now = now_stamp(); | |
| 456 | + let conn = self.inner.conn.lock().await; | |
| 457 | + let changed = conn | |
| 458 | + .execute( | |
| 459 | + "UPDATE signing_keys SET retires_at = ?2 \ | |
| 460 | + WHERE kid = ?1 AND retires_at IS NULL AND activates_at <= ?2 \ | |
| 461 | + AND kid <> (SELECT kid FROM signing_keys WHERE retires_at IS NULL AND activates_at <= ?2 \ | |
| 462 | + ORDER BY activates_at DESC, kid DESC LIMIT 1)", | |
| 463 | + (kid.to_string(), now), | |
| 464 | + ) | |
| 465 | + .await | |
| 466 | + .map_err(db_err)?; | |
| 467 | + Ok(changed == 1) | |
| 468 | + } | |
| 469 | + | |
| 470 | + /// Removes a setting. Returns false when there was no such setting. | |
| 471 | + pub async fn delete_setting(&self, key: &str) -> Result<bool> { | |
| 472 | + let conn = self.inner.conn.lock().await; | |
| 473 | + let changed = conn | |
| 474 | + .execute("DELETE FROM settings WHERE key = ?1", (key.to_string(),)) | |
| 475 | + .await | |
| 476 | + .map_err(db_err)?; | |
| 477 | + Ok(changed == 1) | |
| 478 | + } | |
| 479 | + | |
| 480 | + /// The settings whose key starts with `prefix`, in key order. | |
| 481 | + pub async fn settings_with_prefix(&self, prefix: &str) -> Result<Vec<(String, String)>> { | |
| 482 | + let conn = self.read_conn().await; | |
| 483 | + fetch_all( | |
| 484 | + &conn, | |
| 485 | + "SELECT key, value FROM settings WHERE substr(key, 1, length(?1)) = ?1 ORDER BY key", | |
| 486 | + (prefix.to_string(),), | |
| 487 | + |row: &Row| Ok((col_text(row, 0)?, col_text(row, 1)?)), | |
| 488 | + ) | |
| 489 | + .await | |
| 490 | + } | |
| 491 | +} | |
| 492 | + | |
| 493 | +/// Maps a row selected as `id, kind, to_addr, subject, state, attempts, next_attempt_at, last_error, | |
| 494 | +/// created_at`. | |
| 495 | +fn map_outbox(row: &Row) -> Result<OutboxRow> { | |
| 496 | + Ok(OutboxRow { | |
| 497 | + id: col_text(row, 0)?, | |
| 498 | + kind: col_text(row, 1)?, | |
| 499 | + to_addr: col_text(row, 2)?, | |
| 500 | + subject: col_text(row, 3)?, | |
| 501 | + state: col_text(row, 4)?, | |
| 502 | + attempts: col_int(row, 5)?, | |
| 503 | + next_attempt_at: col_text(row, 6)?, | |
| 504 | + last_error: crate::store::col_opt_text(row, 7)?, | |
| 505 | + created_at: col_text(row, 8)?, | |
| 506 | + }) | |
| 507 | +} | |
| 508 | + | |
| 509 | +#[cfg(test)] | |
| 510 | +mod tests { | |
| 511 | + use super::*; | |
| 512 | + | |
| 513 | + async fn store_with_users() -> (tempfile::TempDir, Store, String, String) { | |
| 514 | + let dir = tempfile::tempdir().unwrap(); | |
| 515 | + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); | |
| 516 | + let first = store | |
| 517 | + .create_first_admin("ada@example.com", "Ada", "h") | |
| 518 | + .await | |
| 519 | + .unwrap(); | |
| 520 | + let second = store | |
| 521 | + .create_user("bob@example.com", "Bob", "h", true) | |
| 522 | + .await | |
| 523 | + .unwrap(); | |
| 524 | + (dir, store, first.id, second.id) | |
| 525 | + } | |
| 526 | + | |
| 527 | + #[tokio::test] | |
| 528 | + async fn the_last_enabled_admin_cannot_be_demoted_disabled_or_deleted() { | |
| 529 | + let (_dir, store, first, second) = store_with_users().await; | |
| 530 | + // Two admins: one may go. | |
| 531 | + assert!(store.disable_user(&second).await.unwrap()); | |
| 532 | + // `second` is disabled now, so `first` is the last enabled admin. | |
| 533 | + assert_eq!( | |
| 534 | + store.set_admin(&first, false).await.unwrap(), | |
| 535 | + AdminChange::LastAdmin | |
| 536 | + ); | |
| 537 | + assert!(!store.disable_user(&first).await.unwrap()); | |
| 538 | + assert!(store.delete_user(&first).await.is_err()); | |
| 539 | + assert_eq!(store.enabled_admin_count().await.unwrap(), 1); | |
| 540 | + assert!(store.user_by_id(&first).await.unwrap().is_some()); | |
| 541 | + } | |
| 542 | +} |
crates/im-core/src/store/clients.rsmodified+2 -2
| @@ -12,7 +12,7 @@ use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, | ||
| 12 | 12 | use crate::time::now_stamp; |
| 13 | 13 | |
| 14 | 14 | /// The columns of a client row, in the order [`map_client`] reads them. |
| 15 | -const CLIENT_COLS: &str = "id, name, secret_hash, secret_rotated_at, redirect_uris, \ | |
| 15 | +pub(crate) const CLIENT_COLS: &str = "id, name, secret_hash, secret_rotated_at, redirect_uris, \ | |
| 16 | 16 | post_logout_redirect_uris, backchannel_logout_uri, allowed_scopes, service_key, created_at, \ |
| 17 | 17 | disabled_at"; |
| 18 | 18 | |
| @@ -22,7 +22,7 @@ fn uri_list(row: &Row, i: usize) -> Result<Vec<String>> { | ||
| 22 | 22 | } |
| 23 | 23 | |
| 24 | 24 | /// Maps a row selected with [`CLIENT_COLS`]. |
| 25 | -fn map_client(row: &Row) -> Result<Client> { | |
| 25 | +pub(crate) fn map_client(row: &Row) -> Result<Client> { | |
| 26 | 26 | Ok(Client { |
| 27 | 27 | id: col_text(row, 0)?, |
| 28 | 28 | name: col_text(row, 1)?, |
crates/im-core/src/store/invites.rsmodified+1 -1
| @@ -43,7 +43,7 @@ pub enum AcceptOutcome { | ||
| 43 | 43 | Refused, |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | -fn map_invite(row: &turso::Row) -> Result<Invite> { | |
| 46 | +pub(crate) fn map_invite(row: &turso::Row) -> Result<Invite> { | |
| 47 | 47 | Ok(Invite { |
| 48 | 48 | token_hash: col_text(row, 0)?, |
| 49 | 49 | email_folded: col_text(row, 1)?, |
crates/im-core/src/store/mod.rsmodified+1 -0
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | //! connection gets WAL, `synchronous = FULL`, `foreign_keys = ON` and a busy timeout, and the values |
| 7 | 7 | //! in effect are logged at boot. |
| 8 | 8 | |
| 9 | +pub mod admin; | |
| 9 | 10 | pub mod audit; |
| 10 | 11 | pub mod backchannel; |
| 11 | 12 | pub mod clients; |
crates/im-core/src/store/sessions.rsmodified+2 -1
| @@ -365,7 +365,8 @@ impl Store { | ||
| 365 | 365 | .await |
| 366 | 366 | } |
| 367 | 367 | |
| 368 | - async fn end_matching( | |
| 368 | + /// Ends every live session of `user_id`, with their back-channel logouts. Returns the ids ended. | |
| 369 | + pub(crate) async fn end_matching( | |
| 369 | 370 | &self, |
| 370 | 371 | user_id: &str, |
| 371 | 372 | keep: Option<&str>, |
crates/im-core/src/store/users.rsmodified+5 -2
| @@ -334,7 +334,8 @@ impl Store { | ||
| 334 | 334 | Ok(()) |
| 335 | 335 | } |
| 336 | 336 | |
| 337 | - /// Disables an account. In one transaction: the account is marked disabled, the directory feed | |
| 337 | + /// Disables an account. The last enabled administrator cannot be disabled: that is part of the | |
| 338 | + /// same conditional `UPDATE`, so two parallel requests cannot both disable the last two. In one transaction: the account is marked disabled, the directory feed | |
| 338 | 339 | /// records the change, one `sub`-only back-channel logout is queued for every client the person |
| 339 | 340 | /// used (contracts.md 2.5), the refresh tokens are revoked and every session is deleted. Returns |
| 340 | 341 | /// false, with nothing changed, when the account is missing or already disabled. |
| @@ -346,7 +347,9 @@ impl Store { | ||
| 346 | 347 | let changed = tx |
| 347 | 348 | .execute( |
| 348 | 349 | "UPDATE users SET disabled_at = ?2, updated_at = ?2 \ |
| 349 | - WHERE id = ?1 AND disabled_at IS NULL", | |
| 350 | + WHERE id = ?1 AND disabled_at IS NULL \ | |
| 351 | + AND (is_admin = 0 OR (SELECT COUNT(*) FROM users \ | |
| 352 | + WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", | |
| 350 | 353 | (user_id.to_string(), now.clone()), |
| 351 | 354 | ) |
| 352 | 355 | .await |
crates/im-web/src/auth.rsmodified+15 -7
| @@ -105,16 +105,13 @@ pub async fn require_user(cx: &Cx) -> Result<Viewer> { | ||
| 105 | 105 | /// The signed-in administrator. A person who is not an administrator gets 404, the same answer as a |
| 106 | 106 | /// page that does not exist. An administrator without two-factor sign-in, while the policy requires |
| 107 | 107 | /// it, is sent to the security page instead. |
| 108 | -/// | |
| 109 | -/// Not every handler needs it yet; the admin pages that use it come after the account pages. | |
| 110 | -#[allow(dead_code)] | |
| 111 | 108 | pub async fn require_admin(cx: &Cx) -> Result<Viewer> { |
| 112 | 109 | let viewer = require_user(cx).await?; |
| 113 | 110 | if !viewer.user.is_admin { |
| 114 | 111 | return Err(not_found().into()); |
| 115 | 112 | } |
| 116 | 113 | let state = app_context::<AppState>(cx); |
| 117 | - if state.config.policy.require_2fa_for_admins && !viewer.user.totp_enabled() { | |
| 114 | + if state.policy().require_2fa_for_admins && !viewer.user.totp_enabled() { | |
| 118 | 115 | return Err(see_other("/account/security?notice=enrol").into()); |
| 119 | 116 | } |
| 120 | 117 | Ok(viewer) |
| @@ -131,6 +128,17 @@ pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> { | ||
| 131 | 128 | } |
| 132 | 129 | } |
| 133 | 130 | |
| 131 | +/// The signed-in administrator, when the submitted `csrf` field matches their session. A member gets 404 | |
| 132 | +/// first, before the token is looked at, so a form of the admin area gives no hint to a member. | |
| 133 | +pub async fn require_admin_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> { | |
| 134 | + let viewer = require_admin(cx).await?; | |
| 135 | + if check_csrf(&viewer.session, submitted) { | |
| 136 | + Ok(viewer) | |
| 137 | + } else { | |
| 138 | + Err(forbidden().into()) | |
| 139 | + } | |
| 140 | +} | |
| 141 | + | |
| 134 | 142 | /// True only when `submitted` is the session's CSRF token, compared in constant time. An empty |
| 135 | 143 | /// stored token never matches, not even an empty submission. |
| 136 | 144 | pub fn check_csrf(session: &Session, submitted: &str) -> bool { |
| @@ -146,7 +154,7 @@ pub fn check_csrf(session: &Session, submitted: &str) -> bool { | ||
| 146 | 154 | /// applied inside the store, in the same write. |
| 147 | 155 | pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { |
| 148 | 156 | let state = app_context::<AppState>(cx); |
| 149 | - let max_age = Duration::from_secs(u64::from(state.config.policy.session_max_days) * DAY); | |
| 157 | + let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY); | |
| 150 | 158 | if let Some(old) = presented_session(cx) |
| 151 | 159 | .await? |
| 152 | 160 | .filter(|old| old.user_id == user.id) |
| @@ -173,7 +181,7 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | ||
| 173 | 181 | idle: SESSION_IDLE, |
| 174 | 182 | max_age, |
| 175 | 183 | }, |
| 176 | - state.config.policy.max_sessions, | |
| 184 | + state.policy().max_sessions, | |
| 177 | 185 | ) |
| 178 | 186 | .await?; |
| 179 | 187 | // Sessions ended by the cap were queued for back-channel logout in the store's transaction. |
| @@ -346,7 +354,7 @@ pub async fn check_second_factor( | ||
| 346 | 354 | /// Where a person goes after signing in. An administrator without two-factor sign-in goes to the |
| 347 | 355 | /// security page to enrol it, while the policy requires that. Anyone else goes to `next`. |
| 348 | 356 | pub fn after_sign_in(state: &AppState, user: &User, next: &str) -> String { |
| 349 | - if user.is_admin && state.config.policy.require_2fa_for_admins && !user.totp_enabled() { | |
| 357 | + if user.is_admin && state.policy().require_2fa_for_admins && !user.totp_enabled() { | |
| 350 | 358 | "/account/security?notice=enrol".to_owned() |
| 351 | 359 | } else { |
| 352 | 360 | safe_next(Some(next)).to_owned() |
crates/im-web/src/backups.rsadded+131 -0
| @@ -0,0 +1,131 @@ | ||
| 1 | +//! Scheduled backups: when a run is due, the set is written, older sets are pruned, and the outcome is | |
| 2 | +//! recorded and sent to the dead-man URL. | |
| 3 | +//! | |
| 4 | +//! The worker runs only when `[backup] dir` is set. A run is due when none was attempted yet, or when the | |
| 5 | +//! last attempt is at least `interval_hours` old. The attempt time is recorded before the run, so a failing | |
| 6 | +//! run is retried at the interval and not every minute. The same [`run_and_record`] serves `im backup now`. | |
| 7 | +//! | |
| 8 | +//! The dead-man URL gets `<url>/start` before a run, `<url>` after a good run and `<url>/fail` after a bad | |
| 9 | +//! one. A ping that fails is logged and never fails the backup. | |
| 10 | + | |
| 11 | +use std::time::Duration; | |
| 12 | + | |
| 13 | +use im_core::backup; | |
| 14 | +use im_core::config::Config; | |
| 15 | +use im_core::store::Store; | |
| 16 | +use im_core::time::{now_stamp, unix_now, unix_seconds}; | |
| 17 | +use tokio::task::JoinHandle; | |
| 18 | + | |
| 19 | +use crate::backchannel::http_client; | |
| 20 | +use crate::live::stopped; | |
| 21 | +use crate::state::AppState; | |
| 22 | + | |
| 23 | +/// How often the worker checks whether a run is due. | |
| 24 | +const TICK: Duration = Duration::from_secs(60); | |
| 25 | + | |
| 26 | +/// Settings key: when a run was last attempted (a stamp). | |
| 27 | +pub const LAST_ATTEMPT: &str = "backup.last_attempt"; | |
| 28 | +/// Settings key: when a run last succeeded (a stamp). | |
| 29 | +pub const LAST_SUCCESS: &str = "backup.last_success"; | |
| 30 | +/// Settings key: the reason the last run failed, when it did. Never a path to a secret. | |
| 31 | +pub const LAST_ERROR: &str = "backup.last_error"; | |
| 32 | + | |
| 33 | +/// Starts the worker when backups are configured. Returns `None` when they are off. The task ends when | |
| 34 | +/// the stop flag is set. | |
| 35 | +pub fn spawn(state: AppState) -> Option<JoinHandle<()>> { | |
| 36 | + if !state.config.backup.enabled() { | |
| 37 | + return None; | |
| 38 | + } | |
| 39 | + let mut stop = state.stop.clone(); | |
| 40 | + Some(tokio::spawn(async move { | |
| 41 | + loop { | |
| 42 | + tokio::select! { | |
| 43 | + () = tokio::time::sleep(TICK) => {} | |
| 44 | + () = stopped(&mut stop) => break, | |
| 45 | + } | |
| 46 | + if due(&state.store, &state.config).await | |
| 47 | + && let Err(error) = run_and_record(&state.config, &state.store).await | |
| 48 | + { | |
| 49 | + tracing::error!(error = %error, "scheduled backup failed"); | |
| 50 | + } | |
| 51 | + } | |
| 52 | + })) | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// True when no run was attempted yet, or the last attempt is at least `interval_hours` old. | |
| 56 | +async fn due(store: &Store, config: &Config) -> bool { | |
| 57 | + let Ok(last) = store.setting(LAST_ATTEMPT).await else { | |
| 58 | + return false; | |
| 59 | + }; | |
| 60 | + let Some(last) = last.and_then(|stamp| unix_seconds(&stamp)) else { | |
| 61 | + return true; | |
| 62 | + }; | |
| 63 | + let interval = | |
| 64 | + i64::try_from(config.backup.interval_hours.saturating_mul(3600)).unwrap_or(i64::MAX); | |
| 65 | + unix_now().saturating_sub(last) >= interval | |
| 66 | +} | |
| 67 | + | |
| 68 | +/// Writes one set, prunes the old ones and records the outcome. Returns the set's directory on success. | |
| 69 | +/// | |
| 70 | +/// The outcome is recorded in `settings`, so the health page can show it. A failure is returned to the | |
| 71 | +/// caller as well, so `im backup now` can exit with status 1. | |
| 72 | +pub async fn run_and_record(config: &Config, store: &Store) -> im_core::Result<std::path::PathBuf> { | |
| 73 | + let http = http_client(); | |
| 74 | + let base = config | |
| 75 | + .backup | |
| 76 | + .healthcheck_url | |
| 77 | + .trim_end_matches('/') | |
| 78 | + .to_owned(); | |
| 79 | + let has_ping = !base.is_empty(); | |
| 80 | + let stamp = now_stamp().replace([':', '.'], "-"); | |
| 81 | + if let Err(error) = store.set_setting(LAST_ATTEMPT, &now_stamp()).await { | |
| 82 | + tracing::error!(error = %error, "backup attempt not recorded"); | |
| 83 | + } | |
| 84 | + if has_ping { | |
| 85 | + ping(&http, &format!("{base}/start")).await; | |
| 86 | + } | |
| 87 | + let outcome = write_and_prune(config, store, &stamp).await; | |
| 88 | + match &outcome { | |
| 89 | + Ok(set) => { | |
| 90 | + tracing::info!(set = %set.display(), "backup written"); | |
| 91 | + let _ = store.set_setting(LAST_SUCCESS, &now_stamp()).await; | |
| 92 | + let _ = store.set_setting(LAST_ERROR, "").await; | |
| 93 | + if has_ping { | |
| 94 | + ping(&http, &base).await; | |
| 95 | + } | |
| 96 | + } | |
| 97 | + Err(error) => { | |
| 98 | + tracing::error!(error = %error, "backup failed"); | |
| 99 | + let _ = store.set_setting(LAST_ERROR, &error.to_string()).await; | |
| 100 | + if has_ping { | |
| 101 | + ping(&http, &format!("{base}/fail")).await; | |
| 102 | + } | |
| 103 | + } | |
| 104 | + } | |
| 105 | + outcome | |
| 106 | +} | |
| 107 | + | |
| 108 | +/// Writes the set and removes the sets beyond `keep`. | |
| 109 | +async fn write_and_prune( | |
| 110 | + config: &Config, | |
| 111 | + store: &Store, | |
| 112 | + stamp: &str, | |
| 113 | +) -> im_core::Result<std::path::PathBuf> { | |
| 114 | + let set = backup::write_set(store, &config.data_dir, &config.backup.dir, stamp).await?; | |
| 115 | + let removed = backup::prune(&config.backup.dir, config.backup.keep as usize)?; | |
| 116 | + if removed > 0 { | |
| 117 | + tracing::info!(removed, "old backup sets removed"); | |
| 118 | + } | |
| 119 | + Ok(set) | |
| 120 | +} | |
| 121 | + | |
| 122 | +/// Sends one dead-man ping. Failures are logged; they never fail the backup. | |
| 123 | +async fn ping(http: &reqwest::Client, url: &str) { | |
| 124 | + match http.get(url).send().await { | |
| 125 | + Ok(response) if response.status().is_success() => {} | |
| 126 | + Ok(response) => { | |
| 127 | + tracing::warn!(status = %response.status(), "dead-man ping answered with an error"); | |
| 128 | + } | |
| 129 | + Err(error) => tracing::warn!(error = %error, "dead-man ping failed"), | |
| 130 | + } | |
| 131 | +} |
crates/im-web/src/boot.rsmodified+30 -3
| @@ -3,14 +3,14 @@ | ||
| 3 | 3 | //! The order follows `docs/conventions.md` section 2: load the configuration, create the data |
| 4 | 4 | //! directory with mode 0700, load or create the instance key, open the database (which applies |
| 5 | 5 | //! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or |
| 6 | -//! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them. | |
| 6 | +//! Ctrl-C. Stored UI overrides of the policy are layered on the file values here, once, at boot. | |
| 7 | 7 | |
| 8 | 8 | use std::fs::{File, OpenOptions, TryLockError}; |
| 9 | 9 | use std::os::unix::fs::PermissionsExt; |
| 10 | 10 | use std::path::Path; |
| 11 | -use std::sync::Arc; | |
| 11 | +use std::sync::{Arc, RwLock}; | |
| 12 | 12 | |
| 13 | -use im_core::config::Config; | |
| 13 | +use im_core::config::{Config, PolicyConfig}; | |
| 14 | 14 | use im_core::photo::MAX_UPLOAD_BYTES; |
| 15 | 15 | use im_core::secret; |
| 16 | 16 | use im_core::store::Store; |
| @@ -83,6 +83,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { | ||
| 83 | 83 | stop: stop_rx.clone(), |
| 84 | 84 | ..state |
| 85 | 85 | }; |
| 86 | + let backup_task = crate::backups::spawn(state.clone()); | |
| 86 | 87 | tokio::spawn(async move { |
| 87 | 88 | shutdown_signal().await; |
| 88 | 89 | tracing::info!("shutdown signal received"); |
| @@ -113,6 +114,9 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { | ||
| 113 | 114 | let _ = backchannel_worker.await; |
| 114 | 115 | let _ = sweeper_task.await; |
| 115 | 116 | let _ = mail_worker.await; |
| 117 | + if let Some(task) = backup_task { | |
| 118 | + let _ = task.await; | |
| 119 | + } | |
| 116 | 120 | tracing::info!("im stopped"); |
| 117 | 121 | Ok(()) |
| 118 | 122 | } |
| @@ -134,6 +138,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> { | ||
| 134 | 138 | } |
| 135 | 139 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; |
| 136 | 140 | let store = Store::open(&config.database).await?; |
| 141 | + let policy = effective_policy(&config, &store).await?; | |
| 137 | 142 | signing::maintain(&store, &key).await?; |
| 138 | 143 | // im is in its own switcher list. The row follows the configured origin at every boot. |
| 139 | 144 | store |
| @@ -141,6 +146,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> { | ||
| 141 | 146 | .await?; |
| 142 | 147 | Ok(AppState { |
| 143 | 148 | config: Arc::new(config), |
| 149 | + policy_live: Arc::new(RwLock::new(policy)), | |
| 144 | 150 | store, |
| 145 | 151 | key: Arc::new(key), |
| 146 | 152 | live: Arc::new(LiveHub::default()), |
| @@ -151,6 +157,26 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> { | ||
| 151 | 157 | }) |
| 152 | 158 | } |
| 153 | 159 | |
| 160 | +/// The policy in effect at boot: the file values, with each `policy.<key>` setting saved in the admin UI | |
| 161 | +/// layered on top. A stored value that no longer validates is logged and ignored, so a bad row cannot stop | |
| 162 | +/// the server from starting; the file value applies instead. | |
| 163 | +pub(crate) async fn effective_policy( | |
| 164 | + config: &im_core::config::Config, | |
| 165 | + store: &Store, | |
| 166 | +) -> im_core::Result<PolicyConfig> { | |
| 167 | + let mut policy = config.policy.clone(); | |
| 168 | + for (key, value) in store.settings_with_prefix("policy.").await? { | |
| 169 | + let name = key.trim_start_matches("policy."); | |
| 170 | + match policy.set(name, &value) { | |
| 171 | + Ok(next) => policy = next, | |
| 172 | + Err(error) => { | |
| 173 | + tracing::warn!(setting = %key, error = %error, "stored policy setting ignored"); | |
| 174 | + } | |
| 175 | + } | |
| 176 | + } | |
| 177 | + Ok(policy) | |
| 178 | +} | |
| 179 | + | |
| 154 | 180 | /// The request body limit of the photo upload: the picture plus room for the multipart framing and |
| 155 | 181 | /// the CSRF field. The handler enforces the picture limit itself while streaming. |
| 156 | 182 | const PHOTO_BODY_LIMIT: usize = MAX_UPLOAD_BYTES + 64 * 1024; |
| @@ -223,6 +249,7 @@ mod tests { | ||
| 223 | 249 | let key = secret::load_or_create_key(&dir.path().join(KEY_FILE)).expect("key"); |
| 224 | 250 | let store = Store::open(&config.database).await.expect("store"); |
| 225 | 251 | let state = AppState { |
| 252 | + policy_live: Arc::new(RwLock::new(config.policy.clone())), | |
| 226 | 253 | config: Arc::new(config), |
| 227 | 254 | store, |
| 228 | 255 | key: Arc::new(key), |
crates/im-web/src/cli.rsmodified+121 -2
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | //! is stored. The redirect, logout and back-channel URIs are checked by the same rules the endpoints use. |
| 7 | 7 | |
| 8 | 8 | use std::fmt::Display; |
| 9 | -use std::path::Path; | |
| 9 | +use std::path::{Path, PathBuf}; | |
| 10 | 10 | use std::process::ExitCode; |
| 11 | 11 | |
| 12 | 12 | use im_core::config::Config; |
| @@ -18,12 +18,13 @@ use im_core::store::clients::NewClient; | ||
| 18 | 18 | use im_core::token::{generate_token, hash_token}; |
| 19 | 19 | |
| 20 | 20 | use crate::boot::{lock_data_dir, open_state}; |
| 21 | +use crate::pages::admin::clients::is_origin; | |
| 21 | 22 | use crate::state::AppState; |
| 22 | 23 | |
| 23 | 24 | /// Printed with a usage error. |
| 24 | 25 | const USAGE: &str = "usage: |
| 25 | 26 | im client add --name <name> [--redirect-uri <uri>]... [--post-logout-uri <uri>]... |
| 26 | - [--backchannel-uri <uri>] [--family-key <key>] [--scopes <scope ...>] | |
| 27 | + [--backchannel-uri <uri>] [--family-key <key> --public-url <origin>] [--scopes <scope ...>] | |
| 27 | 28 | im client list |
| 28 | 29 | im client disable <client_id>"; |
| 29 | 30 | |
| @@ -93,6 +94,7 @@ struct AddArgs { | ||
| 93 | 94 | post_logout_uris: Vec<String>, |
| 94 | 95 | backchannel_uri: Option<String>, |
| 95 | 96 | family_key: Option<String>, |
| 97 | + public_url: Option<String>, | |
| 96 | 98 | scopes: Option<String>, |
| 97 | 99 | } |
| 98 | 100 | |
| @@ -118,6 +120,7 @@ fn parse_add(words: &[String]) -> std::result::Result<AddArgs, String> { | ||
| 118 | 120 | "--post-logout-uri" => args.post_logout_uris.push(value), |
| 119 | 121 | "--backchannel-uri" => once(&mut args.backchannel_uri)?, |
| 120 | 122 | "--family-key" => once(&mut args.family_key)?, |
| 123 | + "--public-url" => once(&mut args.public_url)?, | |
| 121 | 124 | "--scopes" => once(&mut args.scopes)?, |
| 122 | 125 | other => return Err(format!("unknown option {other}")), |
| 123 | 126 | } |
| @@ -148,6 +151,16 @@ async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> | ||
| 148 | 151 | "family key {key} must be lowercase letters, digits and hyphens" |
| 149 | 152 | )); |
| 150 | 153 | } |
| 154 | + match (&args.family_key, &args.public_url) { | |
| 155 | + (Some(_), None) => { | |
| 156 | + return Err("a family key needs --public-url, the origin of its service".into()); | |
| 157 | + } | |
| 158 | + (None, Some(_)) => return Err("--public-url is only for a family key".into()), | |
| 159 | + (Some(_), Some(url)) if !is_origin(url) => { | |
| 160 | + return Err(format!("{url} is not an origin (scheme and host, no path)")); | |
| 161 | + } | |
| 162 | + _ => {} | |
| 163 | + } | |
| 151 | 164 | let scopes = scope_list(args.scopes.as_deref().unwrap_or(DEFAULT_SCOPES))?; |
| 152 | 165 | |
| 153 | 166 | let secret = generate_token(); |
| @@ -164,6 +177,13 @@ async fn add(state: AppState, args: AddArgs) -> std::result::Result<(), String> | ||
| 164 | 177 | }) |
| 165 | 178 | .await |
| 166 | 179 | .map_err(|e| e.to_string())?; |
| 180 | + if let (Some(key), Some(url)) = (&args.family_key, &args.public_url) { | |
| 181 | + state | |
| 182 | + .store | |
| 183 | + .link_service(key, &name, url, &client.id) | |
| 184 | + .await | |
| 185 | + .map_err(|e| e.to_string())?; | |
| 186 | + } | |
| 167 | 187 | println!("client_id: {}", client.id); |
| 168 | 188 | println!("client_secret: {secret}"); |
| 169 | 189 | eprintln!("im: the client secret is shown once; store it now"); |
| @@ -229,6 +249,105 @@ async fn disable(state: AppState, id: &str) -> std::result::Result<(), String> { | ||
| 229 | 249 | } |
| 230 | 250 | } |
| 231 | 251 | |
| 252 | +/// Runs `im backup now`: writes a snapshot set now, and waits for it. The outcome is recorded in the | |
| 253 | +/// settings, so the health page shows it too. | |
| 254 | +pub async fn backup(config: &Path, words: &[String]) -> ExitCode { | |
| 255 | + match words { | |
| 256 | + [verb] if verb == "now" => { | |
| 257 | + with_state(config, |state| async move { | |
| 258 | + let set = crate::backups::run_and_record(&state.config, &state.store) | |
| 259 | + .await | |
| 260 | + .map_err(|e| e.to_string())?; | |
| 261 | + println!("im: backup written to {}", set.display()); | |
| 262 | + Ok(()) | |
| 263 | + }) | |
| 264 | + .await | |
| 265 | + } | |
| 266 | + _ => { | |
| 267 | + eprintln!("im: usage: im backup now"); | |
| 268 | + ExitCode::from(2) | |
| 269 | + } | |
| 270 | + } | |
| 271 | +} | |
| 272 | + | |
| 273 | +/// Runs `im restore --from <set>`. The set is verified first (every file's hash, and the database's | |
| 274 | +/// integrity and schema); a tampered set is refused and nothing is replaced. The current database and | |
| 275 | +/// photos move into a `restore-<stamp>` directory inside the data directory. Refused while the server or | |
| 276 | +/// another command holds the data directory. | |
| 277 | +pub async fn restore(config: &Path, words: &[String]) -> ExitCode { | |
| 278 | + let set = match words { | |
| 279 | + [flag, set] if flag == "--from" => PathBuf::from(set), | |
| 280 | + _ => { | |
| 281 | + eprintln!("im: usage: im restore --from <set>"); | |
| 282 | + return ExitCode::from(2); | |
| 283 | + } | |
| 284 | + }; | |
| 285 | + let outcome = async { | |
| 286 | + let config = Config::load(config).map_err(|e| e.to_string())?; | |
| 287 | + let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?; | |
| 288 | + let stamp = im_core::time::now_stamp().replace([':', '.'], "-"); | |
| 289 | + im_core::backup::restore(&config.data_dir, &config.database, &set, &stamp) | |
| 290 | + .await | |
| 291 | + .map_err(|e| e.to_string()) | |
| 292 | + } | |
| 293 | + .await; | |
| 294 | + match outcome { | |
| 295 | + Ok(outcome) => { | |
| 296 | + println!( | |
| 297 | + "im: restored {} photo(s); the previous database and photos are in {}", | |
| 298 | + outcome.photos, | |
| 299 | + outcome.previous.display() | |
| 300 | + ); | |
| 301 | + ExitCode::SUCCESS | |
| 302 | + } | |
| 303 | + Err(message) => fail(message), | |
| 304 | + } | |
| 305 | +} | |
| 306 | + | |
| 307 | +/// Runs `im fsck`: checks the database's integrity and schema, and that every signing key can be opened | |
| 308 | +/// with the instance key. Refused while the server runs. | |
| 309 | +pub async fn fsck(config: &Path) -> ExitCode { | |
| 310 | + with_state(config, |state| async move { | |
| 311 | + im_core::backup::check_database(&state.config.database) | |
| 312 | + .await | |
| 313 | + .map_err(|e| e.to_string())?; | |
| 314 | + for key in state | |
| 315 | + .store | |
| 316 | + .signing_keys() | |
| 317 | + .await | |
| 318 | + .map_err(|e| e.to_string())? | |
| 319 | + { | |
| 320 | + im_core::secret::open(&state.key, &key.private_sealed) | |
| 321 | + .map_err(|e| format!("signing key {} cannot be opened: {e}", key.kid))?; | |
| 322 | + } | |
| 323 | + println!("im: database and signing keys ok"); | |
| 324 | + Ok(()) | |
| 325 | + }) | |
| 326 | + .await | |
| 327 | +} | |
| 328 | + | |
| 329 | +/// Runs `im keys rotate`: makes a new key the signing key now. | |
| 330 | +pub async fn keys(config: &Path, words: &[String]) -> ExitCode { | |
| 331 | + match words { | |
| 332 | + [verb] if verb == "rotate" => { | |
| 333 | + with_state(config, |state| async move { | |
| 334 | + let kid = crate::oidc::signing::rotate_now(&state.store, &state.key) | |
| 335 | + .await | |
| 336 | + .map_err(|e| e.to_string())?; | |
| 337 | + println!( | |
| 338 | + "im: new signing key {kid}; the previous key stays published for the overlap" | |
| 339 | + ); | |
| 340 | + Ok(()) | |
| 341 | + }) | |
| 342 | + .await | |
| 343 | + } | |
| 344 | + _ => { | |
| 345 | + eprintln!("im: usage: im keys rotate"); | |
| 346 | + ExitCode::from(2) | |
| 347 | + } | |
| 348 | + } | |
| 349 | +} | |
| 350 | + | |
| 232 | 351 | #[cfg(test)] |
| 233 | 352 | mod tests { |
| 234 | 353 | use super::*; |
crates/im-web/src/i18n/admin.rsadded+672 -0
| @@ -0,0 +1,672 @@ | ||
| 1 | +//! Strings of the administrator area: the navigation, the user, invitation, client, mail, message, settings, | |
| 2 | +//! key, audit and health pages. | |
| 3 | +//! | |
| 4 | +//! Each key has its English and its Turkish text in one match arm of [`pair`], so a key without a Turkish | |
| 5 | +//! text does not compile. Sentences with values use the helpers at the end of the file. | |
| 6 | + | |
| 7 | +use super::Lang; | |
| 8 | + | |
| 9 | +/// One variant per phrase of the administrator area. | |
| 10 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 11 | +pub enum A { | |
| 12 | + StatePending, | |
| 13 | + StateSent, | |
| 14 | + StateFailed, | |
| 15 | + StateAbandoned, | |
| 16 | + NoticeMessageSent, | |
| 17 | + NavUsers, | |
| 18 | + NavInvites, | |
| 19 | + NavServices, | |
| 20 | + NavMail, | |
| 21 | + NavMessage, | |
| 22 | + NavSettings, | |
| 23 | + NavKeys, | |
| 24 | + NavAudit, | |
| 25 | + NavHealth, | |
| 26 | + Save, | |
| 27 | + Create, | |
| 28 | + Search, | |
| 29 | + Apply, | |
| 30 | + NextPage, | |
| 31 | + Open, | |
| 32 | + Retry, | |
| 33 | + Abandon, | |
| 34 | + Yes, | |
| 35 | + No, | |
| 36 | + UsersTitle, | |
| 37 | + UsersIntro, | |
| 38 | + SearchLabel, | |
| 39 | + NoUsers, | |
| 40 | + Name, | |
| 41 | + Email, | |
| 42 | + Status, | |
| 43 | + Active, | |
| 44 | + Disabled, | |
| 45 | + Administrator, | |
| 46 | + Created, | |
| 47 | + SessionsLabel, | |
| 48 | + TwoFactor, | |
| 49 | + UserTitle, | |
| 50 | + YouLabel, | |
| 51 | + DisableAccount, | |
| 52 | + EnableAccount, | |
| 53 | + MakeAdmin, | |
| 54 | + RemoveAdmin, | |
| 55 | + ResetTwoFactor, | |
| 56 | + TwoFactorOn, | |
| 57 | + TwoFactorOff, | |
| 58 | + RevokeSessions, | |
| 59 | + DeleteAccount, | |
| 60 | + DeleteWarning, | |
| 61 | + ConfirmEmail, | |
| 62 | + NoOwnAccountHere, | |
| 63 | + ErrLastAdmin, | |
| 64 | + ErrSelfDisable, | |
| 65 | + ErrSelfAdmin, | |
| 66 | + ErrSelfDelete, | |
| 67 | + ErrConfirmEmail, | |
| 68 | + NoticeDisabled, | |
| 69 | + NoticeEnabled, | |
| 70 | + NoticeAdminGranted, | |
| 71 | + NoticeAdminRemoved, | |
| 72 | + NoticeTwoFactorReset, | |
| 73 | + NoticeSessionsRevoked, | |
| 74 | + NoticeDeleted, | |
| 75 | + InvitesTitle, | |
| 76 | + InvitesIntro, | |
| 77 | + InviteNew, | |
| 78 | + InviteEmailLabel, | |
| 79 | + InviteAsAdmin, | |
| 80 | + InviteSendButton, | |
| 81 | + InviteQueued, | |
| 82 | + PendingInvites, | |
| 83 | + NoInvites, | |
| 84 | + Expires, | |
| 85 | + RevokeInvite, | |
| 86 | + ResendInvite, | |
| 87 | + NoticeInviteRevoked, | |
| 88 | + NoticeInviteResent, | |
| 89 | + ErrInviteGone, | |
| 90 | + ErrInviteTaken, | |
| 91 | + ErrInviteAddress, | |
| 92 | + ServicesTitle, | |
| 93 | + ServicesIntro, | |
| 94 | + ServicesList, | |
| 95 | + NoServices, | |
| 96 | + ClientsList, | |
| 97 | + NoClients, | |
| 98 | + ClientCreateTitle, | |
| 99 | + ClientName, | |
| 100 | + RedirectUris, | |
| 101 | + PostLogoutUris, | |
| 102 | + BackchannelUri, | |
| 103 | + ScopesLabel, | |
| 104 | + FamilyKey, | |
| 105 | + PublicUrl, | |
| 106 | + UriHint, | |
| 107 | + FamilyKeyHint, | |
| 108 | + PublicUrlHint, | |
| 109 | + ClientEditTitle, | |
| 110 | + ClientSaved, | |
| 111 | + SecretShown, | |
| 112 | + SecretOnce, | |
| 113 | + SecretLabel, | |
| 114 | + ClientIdLabel, | |
| 115 | + RotateSecret, | |
| 116 | + NoticeSecretRotated, | |
| 117 | + DisableClient, | |
| 118 | + NoticeClientDisabled, | |
| 119 | + ClientDisabledLabel, | |
| 120 | + Healthy, | |
| 121 | + Unhealthy, | |
| 122 | + NotChecked, | |
| 123 | + ErrClientName, | |
| 124 | + ErrUri, | |
| 125 | + ErrFamilyKey, | |
| 126 | + ErrFamilyKeyTaken, | |
| 127 | + ErrPublicUrl, | |
| 128 | + ErrScopes, | |
| 129 | + ErrNoSuchClient, | |
| 130 | + ErrSettingsInvalid, | |
| 131 | + TestMailSubject, | |
| 132 | + TestMailBody, | |
| 133 | + UseFileValue, | |
| 134 | + NoticeFileValue, | |
| 135 | + MailTitle, | |
| 136 | + MailIntro, | |
| 137 | + SmtpStatus, | |
| 138 | + SmtpNotConfigured, | |
| 139 | + SmtpHost, | |
| 140 | + SmtpSender, | |
| 141 | + SmtpLogin, | |
| 142 | + SendTest, | |
| 143 | + NoticeTestQueued, | |
| 144 | + OutboxTitle, | |
| 145 | + OutboxFilter, | |
| 146 | + AllStates, | |
| 147 | + Attempts, | |
| 148 | + NextAttempt, | |
| 149 | + LastError, | |
| 150 | + NoMail, | |
| 151 | + NoticeMailRetried, | |
| 152 | + NoticeMailAbandoned, | |
| 153 | + ErrMailNotRetryable, | |
| 154 | + ErrMailNotAbandonable, | |
| 155 | + MessageTitle, | |
| 156 | + MessageIntro, | |
| 157 | + MessageSubject, | |
| 158 | + MessageBody, | |
| 159 | + MessageBodyHint, | |
| 160 | + MessageSend, | |
| 161 | + ErrMessageEmpty, | |
| 162 | + ErrMessageSubjectLong, | |
| 163 | + ErrMessageBodyLong, | |
| 164 | + ErrMessageEmailInvalid, | |
| 165 | + ErrMessageRateLimited, | |
| 166 | + SettingsTitle, | |
| 167 | + SettingsIntro, | |
| 168 | + SettingName, | |
| 169 | + SettingValue, | |
| 170 | + SettingSource, | |
| 171 | + SourceUi, | |
| 172 | + SourceFile, | |
| 173 | + SourceDefault, | |
| 174 | + FileOnlyTitle, | |
| 175 | + FileOnlyIntro, | |
| 176 | + NoticeSettingsSaved, | |
| 177 | + SettingLabelRequire2fa, | |
| 178 | + SettingLabelMaxSessions, | |
| 179 | + SettingLabelSessionDays, | |
| 180 | + SettingLabelInviteDays, | |
| 181 | + SettingLabelResetMinutes, | |
| 182 | + SettingLabelEmailHours, | |
| 183 | + SettingHintRequire2fa, | |
| 184 | + SettingHintMaxSessions, | |
| 185 | + SettingHintSessionDays, | |
| 186 | + SettingHintInviteDays, | |
| 187 | + SettingHintResetMinutes, | |
| 188 | + SettingHintEmailHours, | |
| 189 | + FileBaseUrl, | |
| 190 | + FileListen, | |
| 191 | + FileDatabase, | |
| 192 | + FileDataDir, | |
| 193 | + FileTrustedProxies, | |
| 194 | + KeysTitle, | |
| 195 | + KeysIntro, | |
| 196 | + KeyCreated, | |
| 197 | + KeyActivates, | |
| 198 | + KeyRetires, | |
| 199 | + KeyCurrent, | |
| 200 | + KeyPublished, | |
| 201 | + KeyRetired, | |
| 202 | + KeyPending, | |
| 203 | + RotateNow, | |
| 204 | + RetireKey, | |
| 205 | + NoticeKeyRotated, | |
| 206 | + NoticeKeyRetired, | |
| 207 | + ErrKeyNotRetirable, | |
| 208 | + AuditTitle, | |
| 209 | + AuditIntro, | |
| 210 | + AuditAction, | |
| 211 | + AuditActor, | |
| 212 | + AuditTarget, | |
| 213 | + AuditFrom, | |
| 214 | + AuditTo, | |
| 215 | + AuditWhen, | |
| 216 | + AuditWho, | |
| 217 | + AuditIp, | |
| 218 | + AuditDetails, | |
| 219 | + AuditNoEntries, | |
| 220 | + AuditNewer, | |
| 221 | + AuditOlder, | |
| 222 | + HealthTitle, | |
| 223 | + HealthIntro, | |
| 224 | + HealthServices, | |
| 225 | + HealthOutbox, | |
| 226 | + HealthDatabase, | |
| 227 | + HealthBackups, | |
| 228 | + HealthBackupLast, | |
| 229 | + HealthBackupError, | |
| 230 | + HealthBackupOff, | |
| 231 | + HealthUsers, | |
| 232 | + HealthAdmins, | |
| 233 | + HealthBytes, | |
| 234 | +} | |
| 235 | + | |
| 236 | +/// The English and the Turkish text of `key`. | |
| 237 | +fn pair(key: A) -> (&'static str, &'static str) { | |
| 238 | + match key { | |
| 239 | + A::StatePending => ("Pending", "Bekliyor"), | |
| 240 | + A::StateSent => ("Sent", "Gönderildi"), | |
| 241 | + A::StateFailed => ("Failed", "Başarısız"), | |
| 242 | + A::StateAbandoned => ("Abandoned", "Vazgeçildi"), | |
| 243 | + A::NoticeMessageSent => ( | |
| 244 | + "The message was queued for every enabled account.", | |
| 245 | + "İleti etkin tüm hesaplar için kuyruğa alındı.", | |
| 246 | + ), | |
| 247 | + A::NavUsers => ("Users", "Kullanıcılar"), | |
| 248 | + A::NavInvites => ("Invitations", "Davetler"), | |
| 249 | + A::NavServices => ("Services", "Hizmetler"), | |
| 250 | + A::NavMail => ("Mail", "E-posta"), | |
| 251 | + A::NavMessage => ("Message", "İleti"), | |
| 252 | + A::NavSettings => ("Settings", "Ayarlar"), | |
| 253 | + A::NavKeys => ("Keys", "Anahtarlar"), | |
| 254 | + A::NavAudit => ("Audit log", "Denetim günlüğü"), | |
| 255 | + A::NavHealth => ("Health", "Sağlık"), | |
| 256 | + A::Save => ("Save", "Kaydet"), | |
| 257 | + A::Create => ("Create", "Oluştur"), | |
| 258 | + A::Search => ("Search", "Ara"), | |
| 259 | + A::Apply => ("Apply", "Uygula"), | |
| 260 | + A::NextPage => ("Next page", "Sonraki sayfa"), | |
| 261 | + A::Open => ("Open", "Aç"), | |
| 262 | + A::Retry => ("Retry", "Yeniden dene"), | |
| 263 | + A::Abandon => ("Abandon", "Vazgeç"), | |
| 264 | + A::Yes => ("Yes", "Evet"), | |
| 265 | + A::No => ("No", "Hayır"), | |
| 266 | + A::UsersTitle => ("Users", "Kullanıcılar"), | |
| 267 | + A::UsersIntro => ( | |
| 268 | + "Everyone who has an account. Search by part of an address or a name.", | |
| 269 | + "Hesabı olan herkes. Adresin veya adın bir parçasıyla arayın.", | |
| 270 | + ), | |
| 271 | + A::SearchLabel => ("Address or name", "Adres veya ad"), | |
| 272 | + A::NoUsers => ("No account matches.", "Eşleşen hesap yok."), | |
| 273 | + A::Name => ("Name", "Ad"), | |
| 274 | + A::Email => ("Email", "E-posta"), | |
| 275 | + A::Status => ("Status", "Durum"), | |
| 276 | + A::Active => ("Active", "Etkin"), | |
| 277 | + A::Disabled => ("Disabled", "Devre dışı"), | |
| 278 | + A::Administrator => ("Administrator", "Yönetici"), | |
| 279 | + A::Created => ("Created", "Oluşturuldu"), | |
| 280 | + A::SessionsLabel => ("Sessions", "Oturumlar"), | |
| 281 | + A::TwoFactor => ("Two-factor sign-in", "İki adımlı giriş"), | |
| 282 | + A::UserTitle => ("Account", "Hesap"), | |
| 283 | + A::YouLabel => ("This is you", "Bu sizsiniz"), | |
| 284 | + A::DisableAccount => ("Disable account", "Hesabı devre dışı bırak"), | |
| 285 | + A::EnableAccount => ("Enable account", "Hesabı etkinleştir"), | |
| 286 | + A::MakeAdmin => ("Make administrator", "Yönetici yap"), | |
| 287 | + A::RemoveAdmin => ("Remove administrator", "Yöneticilikten çıkar"), | |
| 288 | + A::ResetTwoFactor => ("Reset two-factor sign-in", "İki adımlı girişi sıfırla"), | |
| 289 | + A::TwoFactorOn => ("Two-factor sign-in is on.", "İki adımlı giriş açık."), | |
| 290 | + A::TwoFactorOff => ("Two-factor sign-in is off.", "İki adımlı giriş kapalı."), | |
| 291 | + A::RevokeSessions => ("Sign out every session", "Tüm oturumları kapat"), | |
| 292 | + A::DeleteAccount => ("Delete account", "Hesabı sil"), | |
| 293 | + A::DeleteWarning => ( | |
| 294 | + "Deleting removes the account, its sessions, its photo and its links. This cannot be undone.", | |
| 295 | + "Silme; hesabı, oturumlarını, fotoğrafını ve bağlantılarını kaldırır. Geri alınamaz.", | |
| 296 | + ), | |
| 297 | + A::ConfirmEmail => ("Type the address to confirm", "Onaylamak için adresi yazın"), | |
| 298 | + A::NoOwnAccountHere => ( | |
| 299 | + "You cannot change your own account here. Another administrator must do it.", | |
| 300 | + "Kendi hesabınızı burada değiştiremezsiniz. Başka bir yönetici yapmalı.", | |
| 301 | + ), | |
| 302 | + A::ErrLastAdmin => ( | |
| 303 | + "This is the last enabled administrator. Make another administrator first.", | |
| 304 | + "Bu, etkin son yönetici. Önce başka bir yönetici atayın.", | |
| 305 | + ), | |
| 306 | + A::ErrSelfDisable => ( | |
| 307 | + "You cannot disable your own account.", | |
| 308 | + "Kendi hesabınızı devre dışı bırakamazsınız.", | |
| 309 | + ), | |
| 310 | + A::ErrSelfAdmin => ( | |
| 311 | + "You cannot change your own administrator status. Another administrator must do it.", | |
| 312 | + "Kendi yönetici durumunuzu değiştiremezsiniz. Başka bir yönetici yapmalı.", | |
| 313 | + ), | |
| 314 | + A::ErrSelfDelete => ( | |
| 315 | + "You cannot delete your own account.", | |
| 316 | + "Kendi hesabınızı silemezsiniz.", | |
| 317 | + ), | |
| 318 | + A::ErrConfirmEmail => ( | |
| 319 | + "The address you typed does not match the account. Nothing was deleted.", | |
| 320 | + "Yazdığınız adres hesapla eşleşmiyor. Hiçbir şey silinmedi.", | |
| 321 | + ), | |
| 322 | + A::NoticeDisabled => ( | |
| 323 | + "The account is disabled and its sessions have ended.", | |
| 324 | + "Hesap devre dışı; oturumları kapandı.", | |
| 325 | + ), | |
| 326 | + A::NoticeEnabled => ( | |
| 327 | + "The account is enabled again.", | |
| 328 | + "Hesap yeniden etkinleştirildi.", | |
| 329 | + ), | |
| 330 | + A::NoticeAdminGranted => ( | |
| 331 | + "The account is now an administrator.", | |
| 332 | + "Hesap artık bir yönetici.", | |
| 333 | + ), | |
| 334 | + A::NoticeAdminRemoved => ( | |
| 335 | + "The account is no longer an administrator.", | |
| 336 | + "Hesap artık yönetici değil.", | |
| 337 | + ), | |
| 338 | + A::NoticeTwoFactorReset => ( | |
| 339 | + "Two-factor sign-in and the recovery codes were reset. The person has been told by mail.", | |
| 340 | + "İki adımlı giriş ve kurtarma kodları sıfırlandı. Kişiye e-postayla bildirildi.", | |
| 341 | + ), | |
| 342 | + A::NoticeSessionsRevoked => ( | |
| 343 | + "Every session of the account has ended.", | |
| 344 | + "Hesabın tüm oturumları kapandı.", | |
| 345 | + ), | |
| 346 | + A::NoticeDeleted => ("The account was deleted.", "Hesap silindi."), | |
| 347 | + A::InvitesTitle => ("Invitations", "Davetler"), | |
| 348 | + A::InvitesIntro => ( | |
| 349 | + "An invitation is a link that creates an account. Only the newest link for an address works.", | |
| 350 | + "Davet, hesap oluşturan bir bağlantıdır. Bir adres için yalnızca en yeni bağlantı çalışır.", | |
| 351 | + ), | |
| 352 | + A::InviteNew => ("New invitation", "Yeni davet"), | |
| 353 | + A::InviteEmailLabel => ("Email", "E-posta"), | |
| 354 | + A::InviteAsAdmin => ("Make the account an administrator", "Hesabı yönetici yap"), | |
| 355 | + A::InviteSendButton => ("Send invitation", "Daveti gönder"), | |
| 356 | + A::InviteQueued => ( | |
| 357 | + "The invitation is queued for sending.", | |
| 358 | + "Davet gönderilmek üzere kuyruğa alındı.", | |
| 359 | + ), | |
| 360 | + A::PendingInvites => ("Pending invitations", "Bekleyen davetler"), | |
| 361 | + A::NoInvites => ("No invitation is waiting.", "Bekleyen davet yok."), | |
| 362 | + A::Expires => ("Expires", "Sona erer"), | |
| 363 | + A::RevokeInvite => ("Revoke", "İptal et"), | |
| 364 | + A::ResendInvite => ("Send a new link", "Yeni bağlantı gönder"), | |
| 365 | + A::NoticeInviteRevoked => ("The invitation was revoked.", "Davet iptal edildi."), | |
| 366 | + A::NoticeInviteResent => ( | |
| 367 | + "A new invitation was sent. The old link stopped working.", | |
| 368 | + "Yeni davet gönderildi. Eski bağlantı çalışmıyor.", | |
| 369 | + ), | |
| 370 | + A::ErrInviteTaken => ( | |
| 371 | + "That address already has an account.", | |
| 372 | + "Bu adresin zaten bir hesabı var.", | |
| 373 | + ), | |
| 374 | + A::ErrInviteAddress => ( | |
| 375 | + "That is not an email address.", | |
| 376 | + "Bu bir e-posta adresi değil.", | |
| 377 | + ), | |
| 378 | + A::ErrInviteGone => ( | |
| 379 | + "That invitation was already used or has expired.", | |
| 380 | + "Bu davet zaten kullanıldı veya süresi doldu.", | |
| 381 | + ), | |
| 382 | + A::ServicesTitle => ("Services and clients", "Hizmetler ve istemciler"), | |
| 383 | + A::ServicesIntro => ( | |
| 384 | + "Family apps are clients with a family key. Their public address is what the switcher links to.", | |
| 385 | + "Aile uygulamaları, aile anahtarı olan istemcilerdir. Geçiş menüsü onların genel adresine bağlanır.", | |
| 386 | + ), | |
| 387 | + A::ServicesList => ("Switcher", "Geçiş menüsü"), | |
| 388 | + A::NoServices => ("No service is listed.", "Listelenen hizmet yok."), | |
| 389 | + A::ClientsList => ("OpenID clients", "OpenID istemcileri"), | |
| 390 | + A::NoClients => ("No client is registered.", "Kayıtlı istemci yok."), | |
| 391 | + A::ClientCreateTitle => ("Register a client", "İstemci kaydet"), | |
| 392 | + A::ClientName => ("Name", "Ad"), | |
| 393 | + A::RedirectUris => ("Redirect URIs", "Yönlendirme adresleri"), | |
| 394 | + A::PostLogoutUris => ("Post-logout URIs", "Çıkış sonrası adresleri"), | |
| 395 | + A::BackchannelUri => ("Back-channel logout URI", "Arka kanal çıkış adresi"), | |
| 396 | + A::ScopesLabel => ("Scopes", "Kapsamlar"), | |
| 397 | + A::FamilyKey => ("Family key", "Aile anahtarı"), | |
| 398 | + A::PublicUrl => ("Public address", "Genel adres"), | |
| 399 | + A::UriHint => ( | |
| 400 | + "One per line. Exact matches only.", | |
| 401 | + "Her satıra bir tane. Yalnızca birebir eşleşme.", | |
| 402 | + ), | |
| 403 | + A::FamilyKeyHint => ( | |
| 404 | + "Such as in or iz. Leave empty for a client that is not a family app.", | |
| 405 | + "Örneğin in veya iz. Aile uygulaması değilse boş bırakın.", | |
| 406 | + ), | |
| 407 | + A::PublicUrlHint => ( | |
| 408 | + "The origin of the app, such as https://in.example.com. Needs a family key.", | |
| 409 | + "Uygulamanın kökü, örneğin https://in.example.com. Aile anahtarı gerektirir.", | |
| 410 | + ), | |
| 411 | + A::ClientEditTitle => ("Client", "İstemci"), | |
| 412 | + A::ClientSaved => ("The client was saved.", "İstemci kaydedildi."), | |
| 413 | + A::SecretShown => ( | |
| 414 | + "Client created. The secret is shown once; copy it now.", | |
| 415 | + "İstemci oluşturuldu. Gizli anahtar yalnızca bir kez gösterilir; şimdi kopyalayın.", | |
| 416 | + ), | |
| 417 | + A::SecretOnce => ( | |
| 418 | + "Shown once. It is not stored and cannot be shown again.", | |
| 419 | + "Yalnızca bir kez gösterilir. Saklanmaz ve tekrar gösterilemez.", | |
| 420 | + ), | |
| 421 | + A::SecretLabel => ("Client secret", "İstemci gizli anahtarı"), | |
| 422 | + A::ClientIdLabel => ("Client id", "İstemci kimliği"), | |
| 423 | + A::RotateSecret => ("Rotate secret", "Gizli anahtarı döndür"), | |
| 424 | + A::NoticeSecretRotated => ( | |
| 425 | + "A new secret was issued. The old one no longer works.", | |
| 426 | + "Yeni gizli anahtar üretildi. Eskisi artık çalışmıyor.", | |
| 427 | + ), | |
| 428 | + A::DisableClient => ("Disable client", "İstemciyi devre dışı bırak"), | |
| 429 | + A::NoticeClientDisabled => ( | |
| 430 | + "The client is disabled. It cannot sign in or exchange tokens.", | |
| 431 | + "İstemci devre dışı. Giriş yapamaz veya belirteç alamaz.", | |
| 432 | + ), | |
| 433 | + A::ClientDisabledLabel => ("Disabled", "Devre dışı"), | |
| 434 | + A::Healthy => ("Up", "Çalışıyor"), | |
| 435 | + A::Unhealthy => ("Down", "Çalışmıyor"), | |
| 436 | + A::NotChecked => ("Not checked yet", "Henüz denetlenmedi"), | |
| 437 | + A::ErrClientName => ("The name is empty or too long.", "Ad boş veya çok uzun."), | |
| 438 | + A::ErrUri => ( | |
| 439 | + "A URI is not valid. Use https, or http on loopback, with no fragment.", | |
| 440 | + "Bir adres geçerli değil. https kullanın; yalnızca yerel adreste http, parça (#) olmadan.", | |
| 441 | + ), | |
| 442 | + A::ErrFamilyKey => ( | |
| 443 | + "A family key uses lowercase letters, digits and hyphens.", | |
| 444 | + "Aile anahtarı küçük harf, rakam ve kısa çizgi kullanır.", | |
| 445 | + ), | |
| 446 | + A::ErrFamilyKeyTaken => ( | |
| 447 | + "Another client already uses that family key.", | |
| 448 | + "Bu aile anahtarını başka bir istemci kullanıyor.", | |
| 449 | + ), | |
| 450 | + A::ErrPublicUrl => ( | |
| 451 | + "The public address must be an origin such as https://in.example.com.", | |
| 452 | + "Genel adres https://in.example.com gibi bir kök adres olmalı.", | |
| 453 | + ), | |
| 454 | + A::ErrScopes => ( | |
| 455 | + "Choose at least one known scope.", | |
| 456 | + "En az bir bilinen kapsam seçin.", | |
| 457 | + ), | |
| 458 | + A::ErrNoSuchClient => ("That client does not exist.", "Bu istemci yok."), | |
| 459 | + A::TestMailSubject => ("im: test mail", "im: deneme e-postası"), | |
| 460 | + A::TestMailBody => ( | |
| 461 | + "This is a test of the outgoing mail. If you can read it, sending works.", | |
| 462 | + "Bu, giden e-postanın bir denemesidir. Bunu okuyabiliyorsanız gönderim çalışıyor.", | |
| 463 | + ), | |
| 464 | + A::UseFileValue => ("Use the file value", "Dosya değerini kullan"), | |
| 465 | + A::NoticeFileValue => ( | |
| 466 | + "The setting now follows the file again.", | |
| 467 | + "Ayar artık yeniden dosyayı izliyor.", | |
| 468 | + ), | |
| 469 | + A::ErrSettingsInvalid => ( | |
| 470 | + "A setting is missing or out of range. Nothing was saved.", | |
| 471 | + "Bir ayar eksik veya aralık dışında. Hiçbir şey kaydedilmedi.", | |
| 472 | + ), | |
| 473 | + A::MailTitle => ("Mail", "E-posta"), | |
| 474 | + A::MailIntro => ( | |
| 475 | + "What is sent, to whom, and what is waiting.", | |
| 476 | + "Ne gönderildiği, kime gittiği ve neyin beklediği.", | |
| 477 | + ), | |
| 478 | + A::SmtpStatus => ("Sending", "Gönderim"), | |
| 479 | + A::SmtpNotConfigured => ( | |
| 480 | + "No SMTP server is configured. Mail waits in the outbox and no attempt is spent.", | |
| 481 | + "SMTP sunucusu yapılandırılmamış. E-postalar kutuda bekler; deneme harcanmaz.", | |
| 482 | + ), | |
| 483 | + A::SmtpHost => ("Server", "Sunucu"), | |
| 484 | + A::SmtpSender => ("Sender", "Gönderen"), | |
| 485 | + A::SmtpLogin => ("Login", "Oturum adı"), | |
| 486 | + A::SendTest => ("Send a test mail to me", "Bana bir deneme e-postası gönder"), | |
| 487 | + A::NoticeTestQueued => ( | |
| 488 | + "A test mail is queued for your address.", | |
| 489 | + "Adresinize bir deneme e-postası kuyruğa alındı.", | |
| 490 | + ), | |
| 491 | + A::OutboxTitle => ("Outbox", "Giden kutusu"), | |
| 492 | + A::OutboxFilter => ("State", "Durum"), | |
| 493 | + A::AllStates => ("All", "Tümü"), | |
| 494 | + A::Attempts => ("Attempts", "Denemeler"), | |
| 495 | + A::NextAttempt => ("Next attempt", "Sonraki deneme"), | |
| 496 | + A::LastError => ("Last error", "Son hata"), | |
| 497 | + A::NoMail => ( | |
| 498 | + "Nothing in the outbox for this filter.", | |
| 499 | + "Bu filtrede giden kutusunda bir şey yok.", | |
| 500 | + ), | |
| 501 | + A::NoticeMailRetried => ( | |
| 502 | + "The mail will be sent again now.", | |
| 503 | + "E-posta şimdi yeniden gönderilecek.", | |
| 504 | + ), | |
| 505 | + A::NoticeMailAbandoned => ( | |
| 506 | + "The mail was abandoned and its body removed.", | |
| 507 | + "E-posta vazgeçildi ve içeriği silindi.", | |
| 508 | + ), | |
| 509 | + A::ErrMailNotRetryable => ( | |
| 510 | + "Only a failed mail can be retried.", | |
| 511 | + "Yalnızca başarısız bir e-posta yeniden denenebilir.", | |
| 512 | + ), | |
| 513 | + A::ErrMailNotAbandonable => ( | |
| 514 | + "Only a mail that is not yet sent can be abandoned.", | |
| 515 | + "Yalnızca henüz gönderilmemiş bir e-posta vazgeçilebilir.", | |
| 516 | + ), | |
| 517 | + A::MessageTitle => ("Message", "İleti"), | |
| 518 | + A::MessageIntro => ( | |
| 519 | + "A plain mail to everyone with an account, or to one address. It is queued and sent in the background.", | |
| 520 | + "Hesabı olan herkese veya tek bir adrese düz bir e-posta. Kuyruğa alınır ve arka planda gönderilir.", | |
| 521 | + ), | |
| 522 | + A::MessageSubject => ("Subject", "Konu"), | |
| 523 | + A::MessageBody => ("Message", "İleti"), | |
| 524 | + A::MessageBodyHint => ( | |
| 525 | + "Paragraphs are separated by an empty line.", | |
| 526 | + "Paragraflar boş satırla ayrılır.", | |
| 527 | + ), | |
| 528 | + A::MessageSend => ("Queue the message", "İletiyi kuyruğa al"), | |
| 529 | + A::ErrMessageEmpty => ( | |
| 530 | + "Write a subject and a message.", | |
| 531 | + "Bir konu ve bir ileti yazın.", | |
| 532 | + ), | |
| 533 | + A::ErrMessageSubjectLong => ( | |
| 534 | + "The subject is longer than 150 characters or has a line break.", | |
| 535 | + "Konu 150 karakterden uzun veya satır sonu içeriyor.", | |
| 536 | + ), | |
| 537 | + A::ErrMessageBodyLong => ( | |
| 538 | + "The message is longer than 10000 characters.", | |
| 539 | + "İleti 10000 karakterden uzun.", | |
| 540 | + ), | |
| 541 | + A::ErrMessageEmailInvalid => ( | |
| 542 | + "That address is not an account's address.", | |
| 543 | + "Bu adres bir hesaba ait değil.", | |
| 544 | + ), | |
| 545 | + A::ErrMessageRateLimited => ( | |
| 546 | + "A message was sent a moment ago. Wait a while before the next one.", | |
| 547 | + "Az önce bir ileti gönderildi. Bir sonrakinden önce biraz bekleyin.", | |
| 548 | + ), | |
| 549 | + A::SettingsTitle => ("Settings", "Ayarlar"), | |
| 550 | + A::SettingsIntro => ( | |
| 551 | + "A value saved here wins over the configuration file, and applies at once. The file applies to every setting with no saved value.", | |
| 552 | + "Burada kaydedilen değer yapılandırma dosyasının önündedir ve hemen uygulanır. Kayıtlı değeri olmayan her ayar için dosya geçerlidir.", | |
| 553 | + ), | |
| 554 | + A::SettingName => ("Setting", "Ayar"), | |
| 555 | + A::SettingValue => ("Value", "Değer"), | |
| 556 | + A::SettingSource => ("Source", "Kaynak"), | |
| 557 | + A::SourceUi => ("saved here", "burada kaydedildi"), | |
| 558 | + A::SourceFile => ("config file", "yapılandırma dosyası"), | |
| 559 | + A::SourceDefault => ("default", "varsayılan"), | |
| 560 | + A::FileOnlyTitle => ("File settings", "Dosya ayarları"), | |
| 561 | + A::FileOnlyIntro => ( | |
| 562 | + "These are read from the configuration file and need a restart to change.", | |
| 563 | + "Bunlar yapılandırma dosyasından okunur ve değişmesi yeniden başlatma gerektirir.", | |
| 564 | + ), | |
| 565 | + A::NoticeSettingsSaved => ( | |
| 566 | + "The settings were saved and apply now.", | |
| 567 | + "Ayarlar kaydedildi ve şimdi uygulanıyor.", | |
| 568 | + ), | |
| 569 | + A::SettingLabelRequire2fa => ( | |
| 570 | + "Two-factor sign-in for administrators", | |
| 571 | + "Yöneticiler için iki adımlı giriş", | |
| 572 | + ), | |
| 573 | + A::SettingLabelMaxSessions => ("Sessions per person", "Kişi başına oturum"), | |
| 574 | + A::SettingLabelSessionDays => ("Session lifetime, days", "Oturum süresi, gün"), | |
| 575 | + A::SettingLabelInviteDays => ("Invitation lifetime, days", "Davet süresi, gün"), | |
| 576 | + A::SettingLabelResetMinutes => ( | |
| 577 | + "Reset link lifetime, minutes", | |
| 578 | + "Sıfırlama bağlantısı süresi, dakika", | |
| 579 | + ), | |
| 580 | + A::SettingLabelEmailHours => ( | |
| 581 | + "Email change lifetime, hours", | |
| 582 | + "E-posta değişikliği süresi, saat", | |
| 583 | + ), | |
| 584 | + A::SettingHintRequire2fa => ( | |
| 585 | + "true or false. An administrator without it is sent to enrol after signing in.", | |
| 586 | + "true veya false. Olmadan yönetici giriş sonrası kaydolmaya yönlendirilir.", | |
| 587 | + ), | |
| 588 | + A::SettingHintMaxSessions => ( | |
| 589 | + "At least 1. The oldest session ends when a new sign-in would exceed it.", | |
| 590 | + "En az 1. Yeni girişte sınır aşılırsa en eski oturum kapanır.", | |
| 591 | + ), | |
| 592 | + A::SettingHintSessionDays => ("1 to 365.", "1 ile 365 arası."), | |
| 593 | + A::SettingHintInviteDays => ("1 to 30.", "1 ile 30 arası."), | |
| 594 | + A::SettingHintResetMinutes => ("5 to 1440.", "5 ile 1440 arası."), | |
| 595 | + A::SettingHintEmailHours => ("1 to 168.", "1 ile 168 arası."), | |
| 596 | + A::FileBaseUrl => ("Public address (base_url)", "Genel adres (base_url)"), | |
| 597 | + A::FileListen => ("Listen address", "Dinleme adresi"), | |
| 598 | + A::FileDatabase => ("Database file", "Veritabanı dosyası"), | |
| 599 | + A::FileDataDir => ("Data directory", "Veri dizini"), | |
| 600 | + A::FileTrustedProxies => ("Trusted proxies", "Güvenilen vekiller"), | |
| 601 | + A::KeysTitle => ("Signing keys", "İmzalama anahtarları"), | |
| 602 | + A::KeysIntro => ( | |
| 603 | + "Tokens are signed with the current key. Retired keys stay published for a while so their tokens still verify.", | |
| 604 | + "Belirteçler güncel anahtarla imzalanır. Emekli anahtarlar, imzaladıkları belirteçler doğrulansın diye bir süre yayımlı kalır.", | |
| 605 | + ), | |
| 606 | + A::KeyCreated => ("Created", "Oluşturuldu"), | |
| 607 | + A::KeyActivates => ("Signs from", "İmzalamaya başlama"), | |
| 608 | + A::KeyRetires => ("Retired at", "Emekli olma"), | |
| 609 | + A::KeyCurrent => ("current", "güncel"), | |
| 610 | + A::KeyPublished => ("published", "yayımlı"), | |
| 611 | + A::KeyRetired => ("retired", "emekli"), | |
| 612 | + A::KeyPending => ("waiting to sign", "imzalamayı bekliyor"), | |
| 613 | + A::RotateNow => ("Rotate now", "Şimdi döndür"), | |
| 614 | + A::RetireKey => ("Retire", "Emekli yap"), | |
| 615 | + A::NoticeKeyRotated => ( | |
| 616 | + "A new signing key is current. The old key is retired.", | |
| 617 | + "Yeni imzalama anahtarı güncel. Eski anahtar emekli yapıldı.", | |
| 618 | + ), | |
| 619 | + A::NoticeKeyRetired => ( | |
| 620 | + "The key is retired. It stays published for the usual overlap.", | |
| 621 | + "Anahtar emekli yapıldı. Olağan örtüşme süresi kadar yayımlı kalır.", | |
| 622 | + ), | |
| 623 | + A::ErrKeyNotRetirable => ( | |
| 624 | + "The current key cannot be retired. Rotate first.", | |
| 625 | + "Güncel anahtar emekli yapılamaz. Önce döndürün.", | |
| 626 | + ), | |
| 627 | + A::AuditTitle => ("Audit log", "Denetim günlüğü"), | |
| 628 | + A::AuditIntro => ( | |
| 629 | + "Every change, newest first. Filter, then page with the links below the table.", | |
| 630 | + "Her değişiklik, en yeni önce. Süzün, ardından tablonun altındaki bağlantılarla sayfalayın.", | |
| 631 | + ), | |
| 632 | + A::AuditAction => ("Action", "İşlem"), | |
| 633 | + A::AuditActor => ("Actor id", "Yapan kimlik"), | |
| 634 | + A::AuditTarget => ("Target id", "Hedef kimlik"), | |
| 635 | + A::AuditFrom => ("From (UTC date)", "Başlangıç (UTC tarih)"), | |
| 636 | + A::AuditTo => ("To (UTC date)", "Bitiş (UTC tarih)"), | |
| 637 | + A::AuditWhen => ("When", "Zaman"), | |
| 638 | + A::AuditWho => ("Who", "Kim"), | |
| 639 | + A::AuditIp => ("Address", "Adres"), | |
| 640 | + A::AuditDetails => ("Details", "Ayrıntı"), | |
| 641 | + A::AuditNoEntries => ("No entries match.", "Eşleşen kayıt yok."), | |
| 642 | + A::AuditNewer => ("Newer", "Daha yeni"), | |
| 643 | + A::AuditOlder => ("Older", "Daha eski"), | |
| 644 | + A::HealthTitle => ("Health", "Sağlık"), | |
| 645 | + A::HealthIntro => ( | |
| 646 | + "The state of the server and its outboxes.", | |
| 647 | + "Sunucunun ve giden kutularının durumu.", | |
| 648 | + ), | |
| 649 | + A::HealthServices => ("Services", "Hizmetler"), | |
| 650 | + A::HealthOutbox => ("Mail outbox", "E-posta giden kutusu"), | |
| 651 | + A::HealthDatabase => ("Database", "Veritabanı"), | |
| 652 | + A::HealthBackups => ("Backups", "Yedekler"), | |
| 653 | + A::HealthBackupLast => ("Last success", "Son başarılı"), | |
| 654 | + A::HealthBackupError => ("Last error", "Son hata"), | |
| 655 | + A::HealthBackupOff => ( | |
| 656 | + "Backups are off. Set [backup] dir to turn them on.", | |
| 657 | + "Yedekleme kapalı. Açmak için [backup] dir ayarlayın.", | |
| 658 | + ), | |
| 659 | + A::HealthUsers => ("Accounts", "Hesaplar"), | |
| 660 | + A::HealthAdmins => ("Enabled administrators", "Etkin yöneticiler"), | |
| 661 | + A::HealthBytes => ("Database size", "Veritabanı boyutu"), | |
| 662 | + } | |
| 663 | +} | |
| 664 | + | |
| 665 | +/// The text of `key` in `lang`. | |
| 666 | +pub fn text(lang: Lang, key: A) -> &'static str { | |
| 667 | + let (en, tr) = pair(key); | |
| 668 | + match lang { | |
| 669 | + Lang::En => en, | |
| 670 | + Lang::Tr => tr, | |
| 671 | + } | |
| 672 | +} |
crates/im-web/src/i18n/flows.rsmodified+0 -22
| @@ -31,17 +31,11 @@ pub enum Flow { | ||
| 31 | 31 | /// The button that creates the account. |
| 32 | 32 | InviteSubmit, |
| 33 | 33 | /// Title of the administrator invitation page. |
| 34 | - AdminInvitesTitle, | |
| 35 | 34 | /// The sentence under that title. |
| 36 | - AdminInvitesIntro, | |
| 37 | 35 | /// Checkbox: the invitee becomes an administrator. |
| 38 | - InviteAsAdmin, | |
| 39 | 36 | /// The button that sends the invitation. |
| 40 | - InviteSend, | |
| 41 | 37 | /// Notice after an invitation was queued. |
| 42 | - InviteQueued, | |
| 43 | 38 | /// Alert: the address already has an account. |
| 44 | - InviteAddressTaken, | |
| 45 | 39 | /// The profile link to the email change page. |
| 46 | 40 | ChangeEmailLink, |
| 47 | 41 | /// Title of the email change request page. |
| @@ -119,22 +113,6 @@ pub fn text(lang: Lang, key: Flow) -> &'static str { | ||
| 119 | 113 | } |
| 120 | 114 | (Flow::InviteSubmit, Lang::En) => "Create my account", |
| 121 | 115 | (Flow::InviteSubmit, Lang::Tr) => "Hesabımı oluştur", |
| 122 | - (Flow::AdminInvitesTitle, Lang::En) => "Invitations", | |
| 123 | - (Flow::AdminInvitesTitle, Lang::Tr) => "Davetler", | |
| 124 | - (Flow::AdminInvitesIntro, Lang::En) => { | |
| 125 | - "Send an invitation to an address. The person chooses their own name and password." | |
| 126 | - } | |
| 127 | - (Flow::AdminInvitesIntro, Lang::Tr) => { | |
| 128 | - "Bir adrese davet gönderin. Kişi kendi adını ve parolasını seçer." | |
| 129 | - } | |
| 130 | - (Flow::InviteAsAdmin, Lang::En) => "Make this person an administrator", | |
| 131 | - (Flow::InviteAsAdmin, Lang::Tr) => "Bu kişiyi yönetici yap", | |
| 132 | - (Flow::InviteSend, Lang::En) => "Send the invitation", | |
| 133 | - (Flow::InviteSend, Lang::Tr) => "Daveti gönder", | |
| 134 | - (Flow::InviteQueued, Lang::En) => "The invitation was queued for sending.", | |
| 135 | - (Flow::InviteQueued, Lang::Tr) => "Davet gönderilmek üzere kuyruğa alındı.", | |
| 136 | - (Flow::InviteAddressTaken, Lang::En) => "That address already has an account.", | |
| 137 | - (Flow::InviteAddressTaken, Lang::Tr) => "Bu adrese ait bir hesap zaten var.", | |
| 138 | 116 | (Flow::ChangeEmailLink, Lang::En) => "Change email address", |
| 139 | 117 | (Flow::ChangeEmailLink, Lang::Tr) => "E-posta adresini değiştir", |
| 140 | 118 | (Flow::EmailChangeTitle, Lang::En) => "Change email address", |
crates/im-web/src/i18n/mod.rsmodified+1 -0
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | //! helper functions next to their keys. |
| 9 | 9 | |
| 10 | 10 | pub mod account; |
| 11 | +pub mod admin; | |
| 11 | 12 | pub mod flows; |
| 12 | 13 | pub mod mail; |
| 13 | 14 | pub mod oidc; |
crates/im-web/src/live.rsmodified+45 -9
| @@ -9,10 +9,8 @@ | ||
| 9 | 9 | //! The hub is not a queue and not an authorisation check. Each route that opens a stream |
| 10 | 10 | //! authenticates and authorises first, then calls [`stream_changes`]. |
| 11 | 11 | //! |
| 12 | -//! The account stream (`/-/alive`) is the only user of the hub so far. [`stream_changes`] waits for | |
| 13 | -//! the admin pages that follow a list. | |
| 14 | - | |
| 15 | -#![allow(dead_code)] // `stream_changes` and `Topic::AdminAudit` wait for the admin pages. | |
| 12 | +//! Every stream ends when the process stops (the stop flag in [`AppState`]), so a shutdown does not wait | |
| 13 | +//! for a browser to close its connection. | |
| 16 | 14 | |
| 17 | 15 | use std::collections::HashMap; |
| 18 | 16 | use std::future::Future; |
| @@ -42,8 +40,9 @@ pub const KEEP_ALIVE: Duration = Duration::from_secs(30); | ||
| 42 | 40 | pub enum Topic { |
| 43 | 41 | /// A user's own settings, sessions or sign-ins. Keyed by user id. Streamed only to that user. |
| 44 | 42 | Account(String), |
| 45 | - /// The audit log: an entry was written. Global. Admin pages only. | |
| 46 | - AdminAudit, | |
| 43 | + /// Anything an administrator page shows: users, invitations, clients, mail, keys, settings, audit | |
| 44 | + /// entries, health. Bumped by every administrator write. Streamed only to administrators. | |
| 45 | + Admin, | |
| 47 | 46 | } |
| 48 | 47 | |
| 49 | 48 | /// The change counters of all open topics. Cheap to share: every clone of the app state holds the |
| @@ -72,6 +71,14 @@ impl LiveHub { | ||
| 72 | 71 | .subscribe() |
| 73 | 72 | } |
| 74 | 73 | |
| 74 | + /// The change counter of `topic` now. It moves on every bump, so a stream that compares it with the | |
| 75 | + /// value it sent last sends one event per change. Zero when nobody listens. | |
| 76 | + pub fn generation(&self, topic: &Topic) -> u64 { | |
| 77 | + self.topics() | |
| 78 | + .get(topic) | |
| 79 | + .map_or(0, |sender| *sender.borrow()) | |
| 80 | + } | |
| 81 | + | |
| 75 | 82 | /// Wakes the subscribers of `topic`. Does nothing when nobody listens. |
| 76 | 83 | pub fn bump(&self, topic: &Topic) { |
| 77 | 84 | let mut topics = self.topics(); |
| @@ -88,6 +95,7 @@ impl LiveHub { | ||
| 88 | 95 | /// The state a stream carries between wakes. |
| 89 | 96 | struct Follow<F> { |
| 90 | 97 | wakes: Vec<watch::Receiver<u64>>, |
| 98 | + stop: watch::Receiver<bool>, | |
| 91 | 99 | fingerprint: F, |
| 92 | 100 | last: String, |
| 93 | 101 | } |
| @@ -114,12 +122,17 @@ where | ||
| 114 | 122 | let last = fingerprint().await?; |
| 115 | 123 | let follow = Follow { |
| 116 | 124 | wakes, |
| 125 | + stop: app_context::<AppState>(cx).stop.clone(), | |
| 117 | 126 | fingerprint, |
| 118 | 127 | last, |
| 119 | 128 | }; |
| 120 | 129 | let events = stream::unfold(follow, |mut follow| async move { |
| 121 | 130 | loop { |
| 122 | - if !wait_any(&mut follow.wakes).await { | |
| 131 | + let woke = tokio::select! { | |
| 132 | + woke = wait_any(&mut follow.wakes) => woke, | |
| 133 | + () = stopped(&mut follow.stop) => false, | |
| 134 | + }; | |
| 135 | + if !woke { | |
| 123 | 136 | return None; |
| 124 | 137 | } |
| 125 | 138 | match (follow.fingerprint)().await { |
| @@ -143,6 +156,14 @@ fn changed_event() -> Result<Event> { | ||
| 143 | 156 | Ok(Event::new().event("changed").data("1")) |
| 144 | 157 | } |
| 145 | 158 | |
| 159 | +/// Resolves when the stop flag is set. A flag whose sender is gone never resolves, so the stream is not | |
| 160 | +/// ended by mistake. | |
| 161 | +pub async fn stopped(stop: &mut watch::Receiver<bool>) { | |
| 162 | + if stop.wait_for(|stopped| *stopped).await.is_err() { | |
| 163 | + std::future::pending::<()>().await; | |
| 164 | + } | |
| 165 | +} | |
| 166 | + | |
| 146 | 167 | /// Resolves when one of `wakes` changes. False when that topic is gone, which ends the stream. |
| 147 | 168 | /// With no topics at all it never resolves: the stream then only sends keep-alives. |
| 148 | 169 | async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool { |
| @@ -174,6 +195,8 @@ pub fn events_response( | ||
| 174 | 195 | struct AccountFollow { |
| 175 | 196 | /// Woken by every change of the viewer's account (sessions, security). |
| 176 | 197 | wake: watch::Receiver<u64>, |
| 198 | + /// Set when the process stops. The stream then ends. | |
| 199 | + stop: watch::Receiver<bool>, | |
| 177 | 200 | /// Checks that the session of this stream still exists. |
| 178 | 201 | store: Store, |
| 179 | 202 | /// The session the stream was opened with. |
| @@ -192,18 +215,31 @@ struct AccountFollow { | ||
| 192 | 215 | async fn alive(cx: &Cx) -> Result<Response> { |
| 193 | 216 | let state = app_context::<AppState>(cx); |
| 194 | 217 | let Some(viewer) = current_user(cx).await? else { |
| 195 | - return events_response(cx, stream::pending::<Result<Event>>()); | |
| 218 | + // Anonymous: no events, but the stream still ends when the process stops. | |
| 219 | + let events = stream::unfold(state.stop.clone(), |mut stop| async move { | |
| 220 | + stopped(&mut stop).await; | |
| 221 | + None::<(Result<Event>, watch::Receiver<bool>)> | |
| 222 | + }); | |
| 223 | + return events_response(cx, events); | |
| 196 | 224 | }; |
| 197 | 225 | let follow = AccountFollow { |
| 198 | 226 | wake: state |
| 199 | 227 | .live |
| 200 | 228 | .subscribe(&Topic::Account(viewer.user.id.clone())), |
| 229 | + stop: state.stop.clone(), | |
| 201 | 230 | store: state.store.clone(), |
| 202 | 231 | session_id: viewer.session.id.clone(), |
| 203 | 232 | done: false, |
| 204 | 233 | }; |
| 205 | 234 | let events = stream::unfold(follow, |mut follow| async move { |
| 206 | - if follow.done || follow.wake.changed().await.is_err() { | |
| 235 | + if follow.done { | |
| 236 | + return None; | |
| 237 | + } | |
| 238 | + let changed = tokio::select! { | |
| 239 | + changed = follow.wake.changed() => changed.is_ok(), | |
| 240 | + () = stopped(&mut follow.stop) => false, | |
| 241 | + }; | |
| 242 | + if !changed { | |
| 207 | 243 | return None; |
| 208 | 244 | } |
| 209 | 245 | match follow.store.session_is_live(&follow.session_id).await { |
crates/im-web/src/mail/mod.rsmodified+17 -0
| @@ -79,6 +79,21 @@ pub enum Mail<'a> { | ||
| 79 | 79 | }, |
| 80 | 80 | /// A security notice. |
| 81 | 81 | Security(Notice), |
| 82 | + /// A message from an administrator. The subject and the body are the administrator's own words; they | |
| 83 | + /// are escaped like every other value, and the body is split into paragraphs at blank lines. | |
| 84 | + Notice { | |
| 85 | + /// The subject line. Single line, checked by the caller. | |
| 86 | + subject: &'a str, | |
| 87 | + /// The body, plain text. | |
| 88 | + body: &'a str, | |
| 89 | + }, | |
| 90 | + /// A test mail sent from the administrator's mail page. Its text is fixed. | |
| 91 | + Test { | |
| 92 | + /// The subject. | |
| 93 | + subject: &'a str, | |
| 94 | + /// The body, paragraphs separated by a blank line. | |
| 95 | + body: &'a str, | |
| 96 | + }, | |
| 82 | 97 | } |
| 83 | 98 | |
| 84 | 99 | impl Mail<'_> { |
| @@ -91,6 +106,8 @@ impl Mail<'_> { | ||
| 91 | 106 | Mail::EmailNew { .. } => "email_new", |
| 92 | 107 | Mail::EmailDone { .. } => "email_done", |
| 93 | 108 | Mail::Security(_) => "security", |
| 109 | + Mail::Notice { .. } => "notice", | |
| 110 | + Mail::Test { .. } => "test", | |
| 94 | 111 | } |
| 95 | 112 | } |
| 96 | 113 | } |
crates/im-web/src/mail/templates.rsmodified+12 -0
| @@ -110,6 +110,18 @@ fn parts(lang: Lang, name: Option<&str>, mail: &Mail<'_>) -> Parts { | ||
| 110 | 110 | closing: vec![signature], |
| 111 | 111 | } |
| 112 | 112 | } |
| 113 | + Mail::Notice { subject, body } | Mail::Test { subject, body } => Parts { | |
| 114 | + subject: subject.to_owned(), | |
| 115 | + greeting, | |
| 116 | + paragraphs: body | |
| 117 | + .split("\n\n") | |
| 118 | + .map(str::trim) | |
| 119 | + .filter(|paragraph| !paragraph.is_empty()) | |
| 120 | + .map(str::to_owned) | |
| 121 | + .collect(), | |
| 122 | + action: None, | |
| 123 | + closing: vec![signature], | |
| 124 | + }, | |
| 113 | 125 | } |
| 114 | 126 | } |
| 115 | 127 |
crates/im-web/src/main.rsmodified+6 -5
| @@ -9,6 +9,7 @@ mod assets; | ||
| 9 | 9 | mod audit; |
| 10 | 10 | mod auth; |
| 11 | 11 | mod backchannel; |
| 12 | +mod backups; | |
| 12 | 13 | mod boot; |
| 13 | 14 | mod cli; |
| 14 | 15 | mod client_ip; |
| @@ -30,7 +31,7 @@ use std::process::ExitCode; | ||
| 30 | 31 | use tracing_subscriber::EnvFilter; |
| 31 | 32 | |
| 32 | 33 | /// Printed with a usage error. |
| 33 | -const USAGE: &str = "usage: im [--config <path>] [serve | client <add|list|disable> ...]"; | |
| 34 | +const USAGE: &str = "usage: im [--config <path>] [serve | client <add|list|disable> ... | backup now | restore --from <set> | fsck | keys rotate]"; | |
| 34 | 35 | |
| 35 | 36 | /// The configuration file when neither `--config` nor `IM_CONFIG` names one. |
| 36 | 37 | const DEFAULT_CONFIG: &str = "config/im.toml"; |
| @@ -100,10 +101,10 @@ async fn main() -> ExitCode { | ||
| 100 | 101 | match words.as_slice() { |
| 101 | 102 | [] | ["serve"] => serve(&config_path(cli.config)).await, |
| 102 | 103 | ["client", ..] => cli::client(&config_path(cli.config), &cli.words[1..]).await, |
| 103 | - ["admin", ..] => { | |
| 104 | - eprintln!("im: admin commands are not implemented yet"); | |
| 105 | - ExitCode::from(2) | |
| 106 | - } | |
| 104 | + ["backup", ..] => cli::backup(&config_path(cli.config), &cli.words[1..]).await, | |
| 105 | + ["restore", ..] => cli::restore(&config_path(cli.config), &cli.words[1..]).await, | |
| 106 | + ["fsck"] => cli::fsck(&config_path(cli.config)).await, | |
| 107 | + ["keys", ..] => cli::keys(&config_path(cli.config), &cli.words[1..]).await, | |
| 107 | 108 | _ => { |
| 108 | 109 | eprintln!("im: unknown command\n{USAGE}"); |
| 109 | 110 | ExitCode::from(2) |
crates/im-web/src/oidc/authorize.rsmodified+1 -4
| @@ -195,10 +195,7 @@ async fn authorize(cx: &Cx) -> Result<impl View> { | ||
| 195 | 195 | |
| 196 | 196 | // An administrator must have two-factor sign-in first (the policy). The security page enrols it; a |
| 197 | 197 | // prompt=none request cannot show a page, so it is refused instead. |
| 198 | - if viewer.user.is_admin | |
| 199 | - && app.config.policy.require_2fa_for_admins | |
| 200 | - && !viewer.user.totp_enabled() | |
| 201 | - { | |
| 198 | + if viewer.user.is_admin && app.policy().require_2fa_for_admins && !viewer.user.totp_enabled() { | |
| 202 | 199 | if asked.no_prompt { |
| 203 | 200 | let refused = Refused { |
| 204 | 201 | code: "interaction_required", |
crates/im-web/src/oidc/signing.rsmodified+17 -0
| @@ -66,6 +66,23 @@ pub fn spawn( | ||
| 66 | 66 | }) |
| 67 | 67 | } |
| 68 | 68 | |
| 69 | +/// Makes a new key the signing key now. The previous key stops signing at once and stays published for the | |
| 70 | +/// usual overlap, so tokens it signed still verify. Returns the new key id. | |
| 71 | +pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result<String> { | |
| 72 | + let fresh = keys::generate(); | |
| 73 | + let now = now_stamp(); | |
| 74 | + let record = KeyRecord { | |
| 75 | + kid: fresh.kid.clone(), | |
| 76 | + private_sealed: secret::seal(instance_key, &fresh.seed)?, | |
| 77 | + public_raw: fresh.public.to_vec(), | |
| 78 | + created_at: now.clone(), | |
| 79 | + activates_at: now, | |
| 80 | + retires_at: None, | |
| 81 | + }; | |
| 82 | + store.add_signing_key(&record).await?; | |
| 83 | + Ok(fresh.kid) | |
| 84 | +} | |
| 85 | + | |
| 69 | 86 | /// The keys published now, for the JWKS document and for verifying tokens. |
| 70 | 87 | pub async fn published_keys(store: &Store) -> im_core::Result<Vec<KeyRecord>> { |
| 71 | 88 | let rows = store.signing_keys().await?; |
crates/im-web/src/pages/admin/audit.rsadded+211 -0
| @@ -0,0 +1,211 @@ | ||
| 1 | +//! `/admin/audit`: the audit log, newest first, with filters and keyset paging. | |
| 2 | +//! | |
| 3 | +//! The filters are an action, an actor id, a target id, and a day range. The cursor of the next page is the | |
| 4 | +//! position of the last entry (`at|id`), so entries written while an administrator pages do not shift the | |
| 5 | +//! pages. The day range is read in UTC: `from` is the first nanosecond of its day, and `to` is the last | |
| 6 | +//! nanosecond of its day, so both days are included in full. | |
| 7 | + | |
| 8 | +use im_core::model::AuditEntry; | |
| 9 | +use im_core::store::audit::{AuditCursor, AuditFilter}; | |
| 10 | +use serde::Deserialize; | |
| 11 | +use topcoat::Result; | |
| 12 | +use topcoat::context::{Cx, app_context}; | |
| 13 | +use topcoat::router::content::Form; | |
| 14 | +use topcoat::router::page; | |
| 15 | +use topcoat::view::{View, component, view}; | |
| 16 | + | |
| 17 | +use crate::auth::require_admin; | |
| 18 | +use crate::i18n::Lang; | |
| 19 | +use crate::i18n::admin::{A, text}; | |
| 20 | +use crate::pages::admin::{PAGE_SIZE, Tab, frame_info, tabs}; | |
| 21 | +use crate::state::AppState; | |
| 22 | +use crate::views::{ViewerInfo, shell}; | |
| 23 | + | |
| 24 | +/// The query: the four filters, and the cursor of the page. | |
| 25 | +#[derive(Deserialize, Default)] | |
| 26 | +struct AuditQuery { | |
| 27 | + #[serde(default)] | |
| 28 | + action: String, | |
| 29 | + #[serde(default)] | |
| 30 | + actor: String, | |
| 31 | + #[serde(default)] | |
| 32 | + target: String, | |
| 33 | + /// A day, `YYYY-MM-DD`. | |
| 34 | + #[serde(default)] | |
| 35 | + from: String, | |
| 36 | + /// A day, `YYYY-MM-DD`, included. | |
| 37 | + #[serde(default)] | |
| 38 | + to: String, | |
| 39 | + /// `at|id` of the last entry of the previous page. | |
| 40 | + #[serde(default)] | |
| 41 | + after: String, | |
| 42 | +} | |
| 43 | + | |
| 44 | +/// `GET /admin/audit`. | |
| 45 | +#[page("/admin/audit")] | |
| 46 | +async fn audit_page(cx: &Cx, Form(query): Form<AuditQuery>) -> Result<impl View> { | |
| 47 | + let viewer = require_admin(cx).await?; | |
| 48 | + let state = app_context::<AppState>(cx); | |
| 49 | + let (lang, info) = frame_info(cx, &viewer); | |
| 50 | + let filter = AuditFilter { | |
| 51 | + action: non_empty(&query.action), | |
| 52 | + actor_id: non_empty(&query.actor), | |
| 53 | + target_id: non_empty(&query.target), | |
| 54 | + from: day_stamp(&query.from, false), | |
| 55 | + to: day_stamp(&query.to, true), | |
| 56 | + }; | |
| 57 | + let cursor = cursor_of(&query.after); | |
| 58 | + let (entries, next) = state | |
| 59 | + .store | |
| 60 | + .list_audit(&filter, cursor.as_ref(), PAGE_SIZE) | |
| 61 | + .await?; | |
| 62 | + let base = filter_query(&query); | |
| 63 | + let next_href = next.map(|next| { | |
| 64 | + format!( | |
| 65 | + "/admin/audit?{base}&after={}", | |
| 66 | + encode(&format!("{}|{}", next.at, next.id)) | |
| 67 | + ) | |
| 68 | + }); | |
| 69 | + Ok(audit_view(cx, lang, info, base, query, entries, next_href)) | |
| 70 | +} | |
| 71 | + | |
| 72 | +/// Trimmed text, or `None` when it is empty. | |
| 73 | +fn non_empty(text: &str) -> Option<String> { | |
| 74 | + let text = text.trim(); | |
| 75 | + (!text.is_empty()).then(|| text.to_owned()) | |
| 76 | +} | |
| 77 | + | |
| 78 | +/// The stamp of the first (or, with `end`, the last) nanosecond of a `YYYY-MM-DD` day. A day that is not | |
| 79 | +/// well formed is ignored, so the filter is simply not applied. | |
| 80 | +fn day_stamp(day: &str, end: bool) -> Option<String> { | |
| 81 | + let bytes = day.trim().as_bytes(); | |
| 82 | + let well_formed = bytes.len() == 10 | |
| 83 | + && bytes.iter().enumerate().all(|(index, byte)| match index { | |
| 84 | + 4 | 7 => *byte == b'-', | |
| 85 | + _ => byte.is_ascii_digit(), | |
| 86 | + }); | |
| 87 | + if !well_formed { | |
| 88 | + return None; | |
| 89 | + } | |
| 90 | + let day = day.trim(); | |
| 91 | + Some(if end { | |
| 92 | + format!("{day}T23:59:59.999999999Z") | |
| 93 | + } else { | |
| 94 | + format!("{day}T00:00:00.000000000Z") | |
| 95 | + }) | |
| 96 | +} | |
| 97 | + | |
| 98 | +/// The cursor of the page, from `at|id`. A cursor that is not well formed starts the first page. | |
| 99 | +fn cursor_of(after: &str) -> Option<AuditCursor> { | |
| 100 | + let (at, id) = after.split_once('|')?; | |
| 101 | + (!at.is_empty() && !id.is_empty()).then(|| AuditCursor { | |
| 102 | + at: at.to_owned(), | |
| 103 | + id: id.to_owned(), | |
| 104 | + }) | |
| 105 | +} | |
| 106 | + | |
| 107 | +/// The filters as a query string, without the cursor. | |
| 108 | +fn filter_query(query: &AuditQuery) -> String { | |
| 109 | + format!( | |
| 110 | + "action={}&actor={}&target={}&from={}&to={}", | |
| 111 | + encode(&query.action), | |
| 112 | + encode(&query.actor), | |
| 113 | + encode(&query.target), | |
| 114 | + encode(&query.from), | |
| 115 | + encode(&query.to), | |
| 116 | + ) | |
| 117 | +} | |
| 118 | + | |
| 119 | +/// Percent-encodes everything but the unreserved characters, so a filter value cannot add a parameter. | |
| 120 | +fn encode(value: &str) -> String { | |
| 121 | + let mut out = String::with_capacity(value.len()); | |
| 122 | + for byte in value.bytes() { | |
| 123 | + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') { | |
| 124 | + out.push(char::from(byte)); | |
| 125 | + } else { | |
| 126 | + out.push_str(&format!("%{byte:02X}")); | |
| 127 | + } | |
| 128 | + } | |
| 129 | + out | |
| 130 | +} | |
| 131 | + | |
| 132 | +/// The audit page: the filters, the entries, and the links to the newest and the next page. | |
| 133 | +fn audit_view( | |
| 134 | + cx: &Cx, | |
| 135 | + lang: Lang, | |
| 136 | + info: ViewerInfo, | |
| 137 | + base: String, | |
| 138 | + query: AuditQuery, | |
| 139 | + entries: Vec<AuditEntry>, | |
| 140 | + next_href: Option<String>, | |
| 141 | +) -> impl View { | |
| 142 | + let newest = format!("/admin/audit?{base}"); | |
| 143 | + view! { cx => | |
| 144 | + shell(title: text(lang, A::AuditTitle), lang: lang, viewer: Some(info), | |
| 145 | + tabs(lang: lang, current: Tab::Audit) | |
| 146 | + <section class="stack"> | |
| 147 | + <h1>(text(lang, A::AuditTitle))</h1> | |
| 148 | + <p class="muted">(text(lang, A::AuditIntro))</p> | |
| 149 | + <form method="get" action="/admin/audit" class="filters"> | |
| 150 | + <label class="field"><span class="field-label">(text(lang, A::AuditAction))</span> | |
| 151 | + <input name="action" type="text" autocomplete="off" value=(query.action.clone())></label> | |
| 152 | + <label class="field"><span class="field-label">(text(lang, A::AuditActor))</span> | |
| 153 | + <input name="actor" type="text" autocomplete="off" value=(query.actor.clone())></label> | |
| 154 | + <label class="field"><span class="field-label">(text(lang, A::AuditTarget))</span> | |
| 155 | + <input name="target" type="text" autocomplete="off" value=(query.target.clone())></label> | |
| 156 | + <label class="field"><span class="field-label">(text(lang, A::AuditFrom))</span> | |
| 157 | + <input name="from" type="date" value=(query.from.clone())></label> | |
| 158 | + <label class="field"><span class="field-label">(text(lang, A::AuditTo))</span> | |
| 159 | + <input name="to" type="date" value=(query.to.clone())></label> | |
| 160 | + <button type="submit" class="button ghost">(text(lang, A::Apply))</button> | |
| 161 | + </form> | |
| 162 | + <p><a href=(newest)>(text(lang, A::AuditNewer))</a></p> | |
| 163 | + if entries.is_empty() { | |
| 164 | + <p class="muted">(text(lang, A::AuditNoEntries))</p> | |
| 165 | + } else { | |
| 166 | + <table class="audit"> | |
| 167 | + <thead><tr> | |
| 168 | + <th>(text(lang, A::AuditWhen))</th> | |
| 169 | + <th>(text(lang, A::AuditWho))</th> | |
| 170 | + <th>(text(lang, A::AuditAction))</th> | |
| 171 | + <th>(text(lang, A::AuditTarget))</th> | |
| 172 | + <th>(text(lang, A::AuditIp))</th> | |
| 173 | + <th>(text(lang, A::AuditDetails))</th> | |
| 174 | + </tr></thead> | |
| 175 | + <tbody> | |
| 176 | + for entry in entries { | |
| 177 | + audit_row(entry: entry) | |
| 178 | + } | |
| 179 | + </tbody> | |
| 180 | + </table> | |
| 181 | + } | |
| 182 | + if let Some(href) = next_href { | |
| 183 | + <p><a class="button ghost" href=(href)>(text(lang, A::AuditOlder))</a></p> | |
| 184 | + } | |
| 185 | + </section> | |
| 186 | + ) | |
| 187 | + } | |
| 188 | +} | |
| 189 | + | |
| 190 | +/// One entry of the log. Its details are text from the store; the view escapes them. | |
| 191 | +#[component] | |
| 192 | +async fn audit_row(entry: AuditEntry) -> Result<impl View> { | |
| 193 | + let who = entry | |
| 194 | + .actor_id | |
| 195 | + .clone() | |
| 196 | + .unwrap_or_else(|| entry.actor_kind.clone()); | |
| 197 | + let target = match (&entry.target_kind, &entry.target_id) { | |
| 198 | + (Some(kind), Some(id)) => format!("{kind}:{id}"), | |
| 199 | + _ => String::new(), | |
| 200 | + }; | |
| 201 | + Ok(view! { | |
| 202 | + <tr> | |
| 203 | + <td>(entry.at.clone())</td> | |
| 204 | + <td>(who)</td> | |
| 205 | + <td><code>(entry.action.clone())</code></td> | |
| 206 | + <td>(target)</td> | |
| 207 | + <td>(entry.ip.clone().unwrap_or_default())</td> | |
| 208 | + <td><code>(entry.data.clone().unwrap_or_default())</code></td> | |
| 209 | + </tr> | |
| 210 | + }) | |
| 211 | +} |
crates/im-web/src/pages/admin/clients.rsadded+646 -0
| @@ -0,0 +1,646 @@ | ||
| 1 | +//! `/admin/services`: the OpenID clients and the switcher list, with the form that registers a client, and | |
| 2 | +//! `/admin/services/{id}`: one client's settings, with rotate and disable. | |
| 3 | +//! | |
| 4 | +//! Registering a client here does what `im client add` does, with the same rules (`check`): the secret is | |
| 5 | +//! generated, shown once on the page that created it, and only its hash is stored. A family key also | |
| 6 | +//! needs a public address, because that is the link the switcher shows; the address is kept in the | |
| 7 | +//! switcher row of the same key. A rejected form is shown again with what was typed in it. | |
| 8 | +//! | |
| 9 | +//! The rotate action shows the new secret once on the same page, for the same reason. | |
| 10 | + | |
| 11 | +use im_core::Error as CoreError; | |
| 12 | +use im_core::model::{AuditAction, Client, Service}; | |
| 13 | +use im_core::names::parse_display_name; | |
| 14 | +use im_core::oauth::{is_supported_scope, is_valid_family_key, is_valid_registered_uri}; | |
| 15 | +use im_core::store::admin::ClientEdit; | |
| 16 | +use im_core::store::clients::NewClient; | |
| 17 | +use im_core::token::{generate_token, hash_token}; | |
| 18 | +use serde::Deserialize; | |
| 19 | +use serde_json::json; | |
| 20 | +use topcoat::Result; | |
| 21 | +use topcoat::context::{Cx, app_context}; | |
| 22 | +use topcoat::router::content::Form; | |
| 23 | +use topcoat::router::error::{SeeOther, not_found}; | |
| 24 | +use topcoat::router::{page, route}; | |
| 25 | +use topcoat::view::{View, component, view}; | |
| 26 | + | |
| 27 | +use crate::audit::{Actor, record}; | |
| 28 | +use crate::auth::{require_admin, require_admin_csrf}; | |
| 29 | +use crate::i18n::Lang; | |
| 30 | +use crate::i18n::admin::{A, text}; | |
| 31 | +use crate::pages::admin::{ | |
| 32 | + FlashQuery, Tab, action_button, changed, done, error_text, flash_messages, frame_info, | |
| 33 | + notice_text, refused, tabs, | |
| 34 | +}; | |
| 35 | +use crate::pages::path_param; | |
| 36 | +use crate::state::AppState; | |
| 37 | +use crate::views::{ViewerInfo, field, shell}; | |
| 38 | + | |
| 39 | +/// The scopes a new client gets when the form leaves them as they are: what a family app signs in with. | |
| 40 | +const DEFAULT_SCOPES: &str = "openid profile email"; | |
| 41 | + | |
| 42 | +/// The key of im's own switcher row. A family app may not take it. | |
| 43 | +const HOME_KEY: &str = "im"; | |
| 44 | + | |
| 45 | +/// The fields of the client form. Every field is text, as typed; [`check`] turns it into values. | |
| 46 | +#[derive(Deserialize, Default, Clone)] | |
| 47 | +struct ClientForm { | |
| 48 | + #[serde(default)] | |
| 49 | + csrf: String, | |
| 50 | + #[serde(default)] | |
| 51 | + name: String, | |
| 52 | + /// One URI per line. | |
| 53 | + #[serde(default)] | |
| 54 | + redirect_uris: String, | |
| 55 | + /// One URI per line. | |
| 56 | + #[serde(default)] | |
| 57 | + post_logout_uris: String, | |
| 58 | + #[serde(default)] | |
| 59 | + backchannel_uri: String, | |
| 60 | + /// Space-separated scopes. | |
| 61 | + #[serde(default)] | |
| 62 | + scopes: String, | |
| 63 | + #[serde(default)] | |
| 64 | + family_key: String, | |
| 65 | + /// The origin of a family app, such as `https://in.example.com`. | |
| 66 | + #[serde(default)] | |
| 67 | + public_url: String, | |
| 68 | +} | |
| 69 | + | |
| 70 | +/// A form with only the CSRF token. | |
| 71 | +#[derive(Deserialize, Default)] | |
| 72 | +struct CsrfForm { | |
| 73 | + #[serde(default)] | |
| 74 | + csrf: String, | |
| 75 | +} | |
| 76 | + | |
| 77 | +/// A client form after its checks: every value is in the form the store takes. | |
| 78 | +struct Checked { | |
| 79 | + name: String, | |
| 80 | + redirect_uris: Vec<String>, | |
| 81 | + post_logout_uris: Vec<String>, | |
| 82 | + backchannel_uri: Option<String>, | |
| 83 | + scopes: String, | |
| 84 | + family_key: Option<String>, | |
| 85 | + public_url: Option<String>, | |
| 86 | +} | |
| 87 | + | |
| 88 | +/// Checks a client form the way `im client add` does. Returns the code of the first problem, which | |
| 89 | +/// [`error_text`] turns into a message. | |
| 90 | +fn check(form: &ClientForm) -> std::result::Result<Checked, &'static str> { | |
| 91 | + let name = parse_display_name(&form.name).map_err(|_| "client-name")?; | |
| 92 | + let redirect_uris = uri_lines(&form.redirect_uris)?; | |
| 93 | + let post_logout_uris = uri_lines(&form.post_logout_uris)?; | |
| 94 | + let backchannel = form.backchannel_uri.trim(); | |
| 95 | + let backchannel_uri = if backchannel.is_empty() { | |
| 96 | + None | |
| 97 | + } else if is_valid_registered_uri(backchannel) { | |
| 98 | + Some(backchannel.to_owned()) | |
| 99 | + } else { | |
| 100 | + return Err("client-uri"); | |
| 101 | + }; | |
| 102 | + let mut scopes: Vec<&str> = Vec::new(); | |
| 103 | + for word in form.scopes.split_whitespace() { | |
| 104 | + if !is_supported_scope(word) { | |
| 105 | + return Err("scopes"); | |
| 106 | + } | |
| 107 | + if !scopes.contains(&word) { | |
| 108 | + scopes.push(word); | |
| 109 | + } | |
| 110 | + } | |
| 111 | + if scopes.is_empty() { | |
| 112 | + return Err("scopes"); | |
| 113 | + } | |
| 114 | + let key = form.family_key.trim(); | |
| 115 | + let family_key = if key.is_empty() { | |
| 116 | + None | |
| 117 | + } else if key == HOME_KEY || !is_valid_family_key(key) { | |
| 118 | + return Err("family-key"); | |
| 119 | + } else { | |
| 120 | + Some(key.to_owned()) | |
| 121 | + }; | |
| 122 | + let public = form.public_url.trim(); | |
| 123 | + let public_url = match (&family_key, public.is_empty()) { | |
| 124 | + // A family app needs the public address its switcher link goes to. | |
| 125 | + (Some(_), false) if is_origin(public) => Some(public.to_owned()), | |
| 126 | + (Some(_), _) => return Err("public-url"), | |
| 127 | + (None, false) => return Err("public-url"), | |
| 128 | + (None, true) => None, | |
| 129 | + }; | |
| 130 | + Ok(Checked { | |
| 131 | + name, | |
| 132 | + redirect_uris, | |
| 133 | + post_logout_uris, | |
| 134 | + backchannel_uri, | |
| 135 | + scopes: scopes.join(" "), | |
| 136 | + family_key, | |
| 137 | + public_url, | |
| 138 | + }) | |
| 139 | +} | |
| 140 | + | |
| 141 | +/// The URIs of a textarea: one per line, blank lines ignored, each checked by the same rule the | |
| 142 | +/// endpoints use. | |
| 143 | +fn uri_lines(text: &str) -> std::result::Result<Vec<String>, &'static str> { | |
| 144 | + let mut uris = Vec::new(); | |
| 145 | + for line in text.lines().map(str::trim).filter(|line| !line.is_empty()) { | |
| 146 | + if !is_valid_registered_uri(line) { | |
| 147 | + return Err("client-uri"); | |
| 148 | + } | |
| 149 | + uris.push(line.to_owned()); | |
| 150 | + } | |
| 151 | + Ok(uris) | |
| 152 | +} | |
| 153 | + | |
| 154 | +/// True for an origin: `http://` or `https://`, a host, and no path, space or query. | |
| 155 | +pub(crate) fn is_origin(url: &str) -> bool { | |
| 156 | + let rest = url | |
| 157 | + .strip_prefix("https://") | |
| 158 | + .or_else(|| url.strip_prefix("http://")); | |
| 159 | + rest.is_some_and(|rest| { | |
| 160 | + !rest.is_empty() | |
| 161 | + && !rest.contains(['/', '?', '#', '@']) | |
| 162 | + && !url.chars().any(char::is_whitespace) | |
| 163 | + }) | |
| 164 | +} | |
| 165 | + | |
| 166 | +/// The form values of a stored client, for the edit form. | |
| 167 | +fn prefill(client: &Client, public_url: Option<&str>) -> ClientForm { | |
| 168 | + ClientForm { | |
| 169 | + csrf: String::new(), | |
| 170 | + name: client.name.clone(), | |
| 171 | + redirect_uris: client.redirect_uris.join("\n"), | |
| 172 | + post_logout_uris: client.post_logout_redirect_uris.join("\n"), | |
| 173 | + backchannel_uri: client.backchannel_logout_uri.clone().unwrap_or_default(), | |
| 174 | + scopes: client.allowed_scopes.clone(), | |
| 175 | + family_key: client.service_key.clone().unwrap_or_default(), | |
| 176 | + public_url: public_url.unwrap_or_default().to_owned(), | |
| 177 | + } | |
| 178 | +} | |
| 179 | + | |
| 180 | +/// `GET /admin/services`: the switcher, the clients, and the form that registers one. | |
| 181 | +#[page("/admin/services")] | |
| 182 | +async fn services_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> { | |
| 183 | + let viewer = require_admin(cx).await?; | |
| 184 | + let state = app_context::<AppState>(cx); | |
| 185 | + let (lang, info) = frame_info(cx, &viewer); | |
| 186 | + let services = state.store.list_services().await?; | |
| 187 | + let clients = state.store.list_clients().await?; | |
| 188 | + let defaults = ClientForm { | |
| 189 | + scopes: DEFAULT_SCOPES.to_owned(), | |
| 190 | + ..ClientForm::default() | |
| 191 | + }; | |
| 192 | + Ok(services_view( | |
| 193 | + cx, | |
| 194 | + lang, | |
| 195 | + info, | |
| 196 | + viewer.session.csrf_token.clone(), | |
| 197 | + services, | |
| 198 | + clients, | |
| 199 | + defaults, | |
| 200 | + notice_text(lang, &query.notice).map(str::to_owned), | |
| 201 | + error_text(lang, &query.error).map(str::to_owned), | |
| 202 | + None, | |
| 203 | + )) | |
| 204 | +} | |
| 205 | + | |
| 206 | +/// `POST /admin/services`: registers a client. On success the secret is shown on this page, once. | |
| 207 | +#[page(POST "/admin/services")] | |
| 208 | +async fn create_client(cx: &Cx, Form(form): Form<ClientForm>) -> Result<impl View> { | |
| 209 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 210 | + let (lang, info) = frame_info(cx, &viewer); | |
| 211 | + let state = app_context::<AppState>(cx); | |
| 212 | + let csrf = viewer.session.csrf_token.clone(); | |
| 213 | + let mut success = None; | |
| 214 | + let mut problem = None; | |
| 215 | + let mut created = None; | |
| 216 | + let mut shown = ClientForm { | |
| 217 | + scopes: DEFAULT_SCOPES.to_owned(), | |
| 218 | + ..ClientForm::default() | |
| 219 | + }; | |
| 220 | + match check(&form) { | |
| 221 | + Err(code) => { | |
| 222 | + problem = error_text(lang, code).map(str::to_owned); | |
| 223 | + shown = ClientForm { | |
| 224 | + csrf: String::new(), | |
| 225 | + ..form | |
| 226 | + }; | |
| 227 | + } | |
| 228 | + Ok(checked) => { | |
| 229 | + let secret = generate_token(); | |
| 230 | + match state | |
| 231 | + .store | |
| 232 | + .create_client(&NewClient { | |
| 233 | + name: &checked.name, | |
| 234 | + secret_hash: &hash_token(&secret), | |
| 235 | + redirect_uris: &checked.redirect_uris, | |
| 236 | + post_logout_redirect_uris: &checked.post_logout_uris, | |
| 237 | + backchannel_logout_uri: checked.backchannel_uri.as_deref(), | |
| 238 | + allowed_scopes: &checked.scopes, | |
| 239 | + service_key: checked.family_key.as_deref(), | |
| 240 | + }) | |
| 241 | + .await | |
| 242 | + { | |
| 243 | + Ok(client) => { | |
| 244 | + if let (Some(key), Some(url)) = (&checked.family_key, &checked.public_url) { | |
| 245 | + state | |
| 246 | + .store | |
| 247 | + .link_service(key, &checked.name, url, &client.id) | |
| 248 | + .await?; | |
| 249 | + } | |
| 250 | + record( | |
| 251 | + cx, | |
| 252 | + Actor::User(&viewer.user.id), | |
| 253 | + AuditAction::ClientCreated, | |
| 254 | + Some(("client", &client.id)), | |
| 255 | + json!({ "family": checked.family_key.is_some() }), | |
| 256 | + ) | |
| 257 | + .await; | |
| 258 | + changed(&state.live); | |
| 259 | + success = Some(text(lang, A::ClientSaved).to_owned()); | |
| 260 | + created = Some(Created { | |
| 261 | + id: client.id, | |
| 262 | + name: client.name, | |
| 263 | + secret, | |
| 264 | + }); | |
| 265 | + } | |
| 266 | + Err(CoreError::Conflict(_)) => { | |
| 267 | + problem = error_text(lang, "family-taken").map(str::to_owned); | |
| 268 | + shown = ClientForm { | |
| 269 | + csrf: String::new(), | |
| 270 | + ..form | |
| 271 | + }; | |
| 272 | + } | |
| 273 | + Err(error) => return Err(error.into()), | |
| 274 | + } | |
| 275 | + } | |
| 276 | + } | |
| 277 | + let services = state.store.list_services().await?; | |
| 278 | + let clients = state.store.list_clients().await?; | |
| 279 | + Ok(services_view( | |
| 280 | + cx, lang, info, csrf, services, clients, shown, success, problem, created, | |
| 281 | + )) | |
| 282 | +} | |
| 283 | + | |
| 284 | +/// What the page shows once about a new client: its id and its secret. | |
| 285 | +struct Created { | |
| 286 | + id: String, | |
| 287 | + name: String, | |
| 288 | + secret: String, | |
| 289 | +} | |
| 290 | + | |
| 291 | +/// `GET /admin/services/{id}`: one client's settings. | |
| 292 | +#[page("/admin/services/{id}")] | |
| 293 | +async fn client_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> { | |
| 294 | + let viewer = require_admin(cx).await?; | |
| 295 | + let state = app_context::<AppState>(cx); | |
| 296 | + let (lang, info) = frame_info(cx, &viewer); | |
| 297 | + let client = client_from_path(cx, state).await?; | |
| 298 | + let public_url = public_url_of(state, &client).await?; | |
| 299 | + Ok(detail_view( | |
| 300 | + cx, | |
| 301 | + lang, | |
| 302 | + info, | |
| 303 | + viewer.session.csrf_token.clone(), | |
| 304 | + client, | |
| 305 | + public_url, | |
| 306 | + notice_text(lang, &query.notice).map(str::to_owned), | |
| 307 | + error_text(lang, &query.error).map(str::to_owned), | |
| 308 | + None, | |
| 309 | + )) | |
| 310 | +} | |
| 311 | + | |
| 312 | +/// The client named by the path, or 404. | |
| 313 | +async fn client_from_path(cx: &Cx, state: &AppState) -> Result<Client> { | |
| 314 | + let Some(id) = path_param(cx, "id") else { | |
| 315 | + return Err(not_found().into()); | |
| 316 | + }; | |
| 317 | + state | |
| 318 | + .store | |
| 319 | + .client_row(&id) | |
| 320 | + .await? | |
| 321 | + .ok_or_else(|| not_found().into()) | |
| 322 | +} | |
| 323 | + | |
| 324 | +/// The public address of a family client: the URL of its switcher row, when it has one. | |
| 325 | +async fn public_url_of(state: &AppState, client: &Client) -> Result<Option<String>> { | |
| 326 | + let Some(key) = &client.service_key else { | |
| 327 | + return Ok(None); | |
| 328 | + }; | |
| 329 | + Ok(state | |
| 330 | + .store | |
| 331 | + .list_services() | |
| 332 | + .await? | |
| 333 | + .into_iter() | |
| 334 | + .find(|service: &Service| &service.key == key) | |
| 335 | + .map(|service| service.url)) | |
| 336 | +} | |
| 337 | + | |
| 338 | +/// `POST /admin/services/{id}/edit`. A rejected form goes back to the client's page with the reason. | |
| 339 | +#[route(POST "/admin/services/{id}/edit")] | |
| 340 | +async fn edit_client(cx: &Cx, Form(form): Form<ClientForm>) -> Result<SeeOther> { | |
| 341 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 342 | + let state = app_context::<AppState>(cx); | |
| 343 | + let client = client_from_path(cx, state).await?; | |
| 344 | + let base = format!("/admin/services/{}", client.id); | |
| 345 | + let checked = match check(&form) { | |
| 346 | + Ok(checked) => checked, | |
| 347 | + Err(code) => return Ok(refused(&base, code)), | |
| 348 | + }; | |
| 349 | + let edit = ClientEdit { | |
| 350 | + name: &checked.name, | |
| 351 | + redirect_uris: &checked.redirect_uris, | |
| 352 | + post_logout_redirect_uris: &checked.post_logout_uris, | |
| 353 | + backchannel_logout_uri: checked.backchannel_uri.as_deref(), | |
| 354 | + allowed_scopes: &checked.scopes, | |
| 355 | + service_key: checked.family_key.as_deref(), | |
| 356 | + }; | |
| 357 | + match state.store.update_client(&client.id, &edit).await { | |
| 358 | + Ok(true) => {} | |
| 359 | + Ok(false) => return Ok(refused("/admin/services", "no-client")), | |
| 360 | + Err(CoreError::Conflict(_)) => return Ok(refused(&base, "family-taken")), | |
| 361 | + Err(error) => return Err(error.into()), | |
| 362 | + } | |
| 363 | + if let (Some(key), Some(url)) = (&checked.family_key, &checked.public_url) { | |
| 364 | + state | |
| 365 | + .store | |
| 366 | + .link_service(key, &checked.name, url, &client.id) | |
| 367 | + .await?; | |
| 368 | + } | |
| 369 | + record( | |
| 370 | + cx, | |
| 371 | + Actor::User(&viewer.user.id), | |
| 372 | + AuditAction::ClientUpdated, | |
| 373 | + Some(("client", &client.id)), | |
| 374 | + json!({}), | |
| 375 | + ) | |
| 376 | + .await; | |
| 377 | + changed(&state.live); | |
| 378 | + Ok(done(&base, "client-saved")) | |
| 379 | +} | |
| 380 | + | |
| 381 | +/// `POST /admin/services/{id}/rotate`. The old secret stops working at once; the new one is shown here, once. | |
| 382 | +#[page(POST "/admin/services/{id}/rotate")] | |
| 383 | +async fn rotate_secret(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl View> { | |
| 384 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 385 | + let (lang, info) = frame_info(cx, &viewer); | |
| 386 | + let state = app_context::<AppState>(cx); | |
| 387 | + let client = client_from_path(cx, state).await?; | |
| 388 | + let secret = generate_token(); | |
| 389 | + state | |
| 390 | + .store | |
| 391 | + .rotate_client_secret(&client.id, &hash_token(&secret)) | |
| 392 | + .await?; | |
| 393 | + record( | |
| 394 | + cx, | |
| 395 | + Actor::User(&viewer.user.id), | |
| 396 | + AuditAction::ClientSecretRotated, | |
| 397 | + Some(("client", &client.id)), | |
| 398 | + json!({}), | |
| 399 | + ) | |
| 400 | + .await; | |
| 401 | + changed(&state.live); | |
| 402 | + let public_url = public_url_of(state, &client).await?; | |
| 403 | + let created = Created { | |
| 404 | + id: client.id.clone(), | |
| 405 | + name: client.name.clone(), | |
| 406 | + secret, | |
| 407 | + }; | |
| 408 | + Ok(detail_view( | |
| 409 | + cx, | |
| 410 | + lang, | |
| 411 | + info, | |
| 412 | + viewer.session.csrf_token.clone(), | |
| 413 | + client, | |
| 414 | + public_url, | |
| 415 | + Some(text(lang, A::NoticeSecretRotated).to_owned()), | |
| 416 | + None, | |
| 417 | + Some(created), | |
| 418 | + )) | |
| 419 | +} | |
| 420 | + | |
| 421 | +/// `POST /admin/services/{id}/disable`. A disabled client cannot sign in or exchange tokens. | |
| 422 | +#[route(POST "/admin/services/{id}/disable")] | |
| 423 | +async fn disable_client(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 424 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 425 | + let state = app_context::<AppState>(cx); | |
| 426 | + let client = client_from_path(cx, state).await?; | |
| 427 | + let base = format!("/admin/services/{}", client.id); | |
| 428 | + if !state.store.disable_client(&client.id).await? { | |
| 429 | + return Ok(refused(&base, "no-client")); | |
| 430 | + } | |
| 431 | + record( | |
| 432 | + cx, | |
| 433 | + Actor::User(&viewer.user.id), | |
| 434 | + AuditAction::ClientDisabled, | |
| 435 | + Some(("client", &client.id)), | |
| 436 | + json!({}), | |
| 437 | + ) | |
| 438 | + .await; | |
| 439 | + changed(&state.live); | |
| 440 | + Ok(done(&base, "client-disabled")) | |
| 441 | +} | |
| 442 | + | |
| 443 | +/// The services and clients page. | |
| 444 | +#[allow(clippy::too_many_arguments)] | |
| 445 | +fn services_view( | |
| 446 | + cx: &Cx, | |
| 447 | + lang: Lang, | |
| 448 | + info: ViewerInfo, | |
| 449 | + csrf: String, | |
| 450 | + services: Vec<Service>, | |
| 451 | + clients: Vec<Client>, | |
| 452 | + form: ClientForm, | |
| 453 | + success: Option<String>, | |
| 454 | + problem: Option<String>, | |
| 455 | + created: Option<Created>, | |
| 456 | +) -> impl View { | |
| 457 | + view! { cx => | |
| 458 | + shell(title: text(lang, A::ServicesTitle), lang: lang, viewer: Some(info), | |
| 459 | + tabs(lang: lang, current: Tab::Services) | |
| 460 | + <section class="stack" data-live="/admin/events"> | |
| 461 | + <h1>(text(lang, A::ServicesTitle))</h1> | |
| 462 | + <p class="muted">(text(lang, A::ServicesIntro))</p> | |
| 463 | + flash_messages(success: success, problem: problem) | |
| 464 | + if let Some(created) = created { | |
| 465 | + secret_box(lang: lang, created: created) | |
| 466 | + } | |
| 467 | + <h2>(text(lang, A::ServicesList))</h2> | |
| 468 | + if services.is_empty() { | |
| 469 | + <p class="muted">(text(lang, A::NoServices))</p> | |
| 470 | + } else { | |
| 471 | + <ul class="item-list"> | |
| 472 | + for service in services { | |
| 473 | + service_item(lang: lang, service: service) | |
| 474 | + } | |
| 475 | + </ul> | |
| 476 | + } | |
| 477 | + <h2>(text(lang, A::ClientsList))</h2> | |
| 478 | + if clients.is_empty() { | |
| 479 | + <p class="muted">(text(lang, A::NoClients))</p> | |
| 480 | + } else { | |
| 481 | + <ul class="item-list"> | |
| 482 | + for client in clients { | |
| 483 | + client_item(lang: lang, client: client) | |
| 484 | + } | |
| 485 | + </ul> | |
| 486 | + } | |
| 487 | + <h2>(text(lang, A::ClientCreateTitle))</h2> | |
| 488 | + <form method="post" action="/admin/services" class="stack"> | |
| 489 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 490 | + client_fields(lang: lang, values: form) | |
| 491 | + <button type="submit" class="button primary">(text(lang, A::Create))</button> | |
| 492 | + </form> | |
| 493 | + </section> | |
| 494 | + ) | |
| 495 | + } | |
| 496 | +} | |
| 497 | + | |
| 498 | +/// The one-time secret of a new or rotated client. | |
| 499 | +#[component] | |
| 500 | +async fn secret_box(lang: Lang, created: Created) -> Result<impl View> { | |
| 501 | + Ok(view! { | |
| 502 | + <section class="card stack" role="status"> | |
| 503 | + <h2>(created.name.clone())</h2> | |
| 504 | + <p>(text(lang, A::SecretShown))</p> | |
| 505 | + <dl class="facts"> | |
| 506 | + <dt>(text(lang, A::ClientIdLabel))</dt><dd><code>(created.id.clone())</code></dd> | |
| 507 | + <dt>(text(lang, A::SecretLabel))</dt><dd><code>(created.secret.clone())</code></dd> | |
| 508 | + </dl> | |
| 509 | + <p class="hint">(text(lang, A::SecretOnce))</p> | |
| 510 | + </section> | |
| 511 | + }) | |
| 512 | +} | |
| 513 | + | |
| 514 | +/// One switcher row: the name, its address and its last health check. | |
| 515 | +#[component] | |
| 516 | +async fn service_item(lang: Lang, service: Service) -> Result<impl View> { | |
| 517 | + let health = match service.healthy { | |
| 518 | + Some(true) => text(lang, A::Healthy), | |
| 519 | + Some(false) => text(lang, A::Unhealthy), | |
| 520 | + None => text(lang, A::NotChecked), | |
| 521 | + }; | |
| 522 | + Ok(view! { | |
| 523 | + <li class="item"> | |
| 524 | + <div class="item-main"> | |
| 525 | + <strong>(service.name.clone())</strong> | |
| 526 | + <div class="muted"> | |
| 527 | + <span>(service.url.clone())</span> | |
| 528 | + <span>" · "(health)</span> | |
| 529 | + </div> | |
| 530 | + </div> | |
| 531 | + </li> | |
| 532 | + }) | |
| 533 | +} | |
| 534 | + | |
| 535 | +/// One client row, linking to its page. | |
| 536 | +#[component] | |
| 537 | +async fn client_item(lang: Lang, client: Client) -> Result<impl View> { | |
| 538 | + let href = format!("/admin/services/{}", client.id); | |
| 539 | + let status = if client.disabled_at.is_some() { | |
| 540 | + text(lang, A::ClientDisabledLabel) | |
| 541 | + } else { | |
| 542 | + text(lang, A::Active) | |
| 543 | + }; | |
| 544 | + Ok(view! { | |
| 545 | + <li class="item"> | |
| 546 | + <div class="item-main"> | |
| 547 | + <strong>(client.name.clone())</strong> | |
| 548 | + if let Some(key) = client.service_key.clone() { | |
| 549 | + <span class="badge accent">(key)</span> | |
| 550 | + } | |
| 551 | + <div class="muted"> | |
| 552 | + <span>(client.allowed_scopes.clone())</span> | |
| 553 | + <span>" · "(status)</span> | |
| 554 | + </div> | |
| 555 | + </div> | |
| 556 | + <a class="button ghost" href=(href)>(text(lang, A::Open))</a> | |
| 557 | + </li> | |
| 558 | + }) | |
| 559 | +} | |
| 560 | + | |
| 561 | +/// The fields of a client, shared by the create and the edit forms. | |
| 562 | +#[component] | |
| 563 | +async fn client_fields(lang: Lang, values: ClientForm) -> Result<impl View> { | |
| 564 | + Ok(view! { | |
| 565 | + field(label: text(lang, A::ClientName), name: "name", kind: "text", autocomplete: "off", value: values.name.clone()) | |
| 566 | + <label class="field"> | |
| 567 | + <span class="field-label">(text(lang, A::RedirectUris))</span> | |
| 568 | + <textarea name="redirect_uris" rows="3" spellcheck="false">(values.redirect_uris.clone())</textarea> | |
| 569 | + <span class="hint">(text(lang, A::UriHint))</span> | |
| 570 | + </label> | |
| 571 | + <label class="field"> | |
| 572 | + <span class="field-label">(text(lang, A::PostLogoutUris))</span> | |
| 573 | + <textarea name="post_logout_uris" rows="2" spellcheck="false">(values.post_logout_uris.clone())</textarea> | |
| 574 | + <span class="hint">(text(lang, A::UriHint))</span> | |
| 575 | + </label> | |
| 576 | + <label class="field"> | |
| 577 | + <span class="field-label">(text(lang, A::BackchannelUri))</span> | |
| 578 | + <input name="backchannel_uri" type="text" autocomplete="off" spellcheck="false" value=(values.backchannel_uri.clone())> | |
| 579 | + </label> | |
| 580 | + <label class="field"> | |
| 581 | + <span class="field-label">(text(lang, A::ScopesLabel))</span> | |
| 582 | + <input name="scopes" type="text" autocomplete="off" spellcheck="false" value=(values.scopes.clone())> | |
| 583 | + </label> | |
| 584 | + <label class="field"> | |
| 585 | + <span class="field-label">(text(lang, A::FamilyKey))</span> | |
| 586 | + <input name="family_key" type="text" autocomplete="off" spellcheck="false" value=(values.family_key.clone())> | |
| 587 | + <span class="hint">(text(lang, A::FamilyKeyHint))</span> | |
| 588 | + </label> | |
| 589 | + <label class="field"> | |
| 590 | + <span class="field-label">(text(lang, A::PublicUrl))</span> | |
| 591 | + <input name="public_url" type="url" autocomplete="off" spellcheck="false" value=(values.public_url.clone())> | |
| 592 | + <span class="hint">(text(lang, A::PublicUrlHint))</span> | |
| 593 | + </label> | |
| 594 | + }) | |
| 595 | +} | |
| 596 | + | |
| 597 | +/// One client's page: its facts, the edit form, and the rotate and disable actions. | |
| 598 | +#[allow(clippy::too_many_arguments)] | |
| 599 | +fn detail_view( | |
| 600 | + cx: &Cx, | |
| 601 | + lang: Lang, | |
| 602 | + info: ViewerInfo, | |
| 603 | + csrf: String, | |
| 604 | + client: Client, | |
| 605 | + public_url: Option<String>, | |
| 606 | + success: Option<String>, | |
| 607 | + problem: Option<String>, | |
| 608 | + secret: Option<Created>, | |
| 609 | +) -> impl View { | |
| 610 | + let base = format!("/admin/services/{}", client.id); | |
| 611 | + let values = prefill(&client, public_url.as_deref()); | |
| 612 | + let status = if client.disabled_at.is_some() { | |
| 613 | + text(lang, A::ClientDisabledLabel) | |
| 614 | + } else { | |
| 615 | + text(lang, A::Active) | |
| 616 | + }; | |
| 617 | + view! { cx => | |
| 618 | + shell(title: text(lang, A::ClientEditTitle), lang: lang, viewer: Some(info), | |
| 619 | + tabs(lang: lang, current: Tab::Services) | |
| 620 | + <section class="stack" data-live="/admin/events"> | |
| 621 | + <p><a href="/admin/services">(text(lang, A::ServicesTitle))</a></p> | |
| 622 | + <h1>(client.name.clone())</h1> | |
| 623 | + flash_messages(success: success, problem: problem) | |
| 624 | + if let Some(secret) = secret { | |
| 625 | + secret_box(lang: lang, created: secret) | |
| 626 | + } | |
| 627 | + <dl class="facts"> | |
| 628 | + <dt>(text(lang, A::ClientIdLabel))</dt><dd><code>(client.id.clone())</code></dd> | |
| 629 | + <dt>(text(lang, A::Status))</dt><dd>(status)</dd> | |
| 630 | + <dt>(text(lang, A::Created))</dt><dd>(client.created_at.clone())</dd> | |
| 631 | + </dl> | |
| 632 | + <form method="post" action=(format!("{base}/edit")) class="stack"> | |
| 633 | + <input type="hidden" name="csrf" value=(csrf.clone())> | |
| 634 | + client_fields(lang: lang, values: values) | |
| 635 | + <button type="submit" class="button primary">(text(lang, A::Save))</button> | |
| 636 | + </form> | |
| 637 | + <div class="row"> | |
| 638 | + action_button(action: format!("{base}/rotate"), csrf: csrf.clone(), label: text(lang, A::RotateSecret), class: "button ghost", on: "") | |
| 639 | + if !client.disabled_at.is_some() { | |
| 640 | + action_button(action: format!("{base}/disable"), csrf: csrf.clone(), label: text(lang, A::DisableClient), class: "button danger", on: "") | |
| 641 | + } | |
| 642 | + </div> | |
| 643 | + </section> | |
| 644 | + ) | |
| 645 | + } | |
| 646 | +} |
crates/im-web/src/pages/admin/health.rsadded+149 -0
| @@ -0,0 +1,149 @@ | ||
| 1 | +//! `/admin/health`: the state of the switcher services, the mail outboxes, the database file, the backups, | |
| 2 | +//! and the account counts. Read only; nothing here changes anything. | |
| 3 | +//! | |
| 4 | +//! A service shows the answer of its last health probe, or "not checked" before the first one. | |
| 5 | + | |
| 6 | +use topcoat::Result; | |
| 7 | +use topcoat::context::{Cx, app_context}; | |
| 8 | +use topcoat::router::page; | |
| 9 | +use topcoat::view::{View, component, view}; | |
| 10 | + | |
| 11 | +use crate::auth::require_admin; | |
| 12 | +use crate::i18n::Lang; | |
| 13 | +use crate::i18n::admin::{A, text}; | |
| 14 | +use crate::pages::admin::{Tab, frame_info, tabs}; | |
| 15 | +use crate::state::AppState; | |
| 16 | +use crate::views::{ViewerInfo, shell}; | |
| 17 | + | |
| 18 | +/// `GET /admin/health`. | |
| 19 | +#[page("/admin/health")] | |
| 20 | +async fn health_page(cx: &Cx) -> Result<impl View> { | |
| 21 | + let viewer = require_admin(cx).await?; | |
| 22 | + let state = app_context::<AppState>(cx); | |
| 23 | + let (lang, info) = frame_info(cx, &viewer); | |
| 24 | + let services = state.store.list_services().await?; | |
| 25 | + let outbox = state.store.outbox_counts().await?; | |
| 26 | + let users = state.store.user_count().await?; | |
| 27 | + let admins = state.store.enabled_admin_count().await?; | |
| 28 | + let database_bytes = std::fs::metadata(&state.config.database) | |
| 29 | + .map(|meta| meta.len()) | |
| 30 | + .unwrap_or(0); | |
| 31 | + let backups = if state.config.backup.dir.as_os_str().is_empty() { | |
| 32 | + None | |
| 33 | + } else { | |
| 34 | + Some(Backups { | |
| 35 | + last_success: state.store.setting("backup.last_success").await?, | |
| 36 | + last_error: state.store.setting("backup.last_error").await?, | |
| 37 | + }) | |
| 38 | + }; | |
| 39 | + Ok(health_view( | |
| 40 | + cx, | |
| 41 | + lang, | |
| 42 | + info, | |
| 43 | + services | |
| 44 | + .into_iter() | |
| 45 | + .map(|service| ServiceRow { | |
| 46 | + name: service.name, | |
| 47 | + url: service.url, | |
| 48 | + healthy: service.healthy, | |
| 49 | + }) | |
| 50 | + .collect(), | |
| 51 | + outbox, | |
| 52 | + users, | |
| 53 | + admins, | |
| 54 | + database_bytes, | |
| 55 | + backups, | |
| 56 | + )) | |
| 57 | +} | |
| 58 | + | |
| 59 | +/// The backup settings as the page reads them. | |
| 60 | +struct Backups { | |
| 61 | + last_success: Option<String>, | |
| 62 | + last_error: Option<String>, | |
| 63 | +} | |
| 64 | + | |
| 65 | +/// One switcher service, as the page shows it. | |
| 66 | +struct ServiceRow { | |
| 67 | + name: String, | |
| 68 | + url: String, | |
| 69 | + healthy: Option<bool>, | |
| 70 | +} | |
| 71 | + | |
| 72 | +/// The health page. | |
| 73 | +#[allow(clippy::too_many_arguments)] | |
| 74 | +fn health_view( | |
| 75 | + cx: &Cx, | |
| 76 | + lang: Lang, | |
| 77 | + info: ViewerInfo, | |
| 78 | + services: Vec<ServiceRow>, | |
| 79 | + outbox: Vec<(String, i64)>, | |
| 80 | + users: u64, | |
| 81 | + admins: u64, | |
| 82 | + database_bytes: u64, | |
| 83 | + backups: Option<Backups>, | |
| 84 | +) -> impl View { | |
| 85 | + view! { cx => | |
| 86 | + shell(title: text(lang, A::HealthTitle), lang: lang, viewer: Some(info), | |
| 87 | + tabs(lang: lang, current: Tab::Health) | |
| 88 | + <section class="stack"> | |
| 89 | + <h1>(text(lang, A::HealthTitle))</h1> | |
| 90 | + <p class="muted">(text(lang, A::HealthIntro))</p> | |
| 91 | + <h2>(text(lang, A::HealthServices))</h2> | |
| 92 | + if services.is_empty() { | |
| 93 | + <p class="muted">(text(lang, A::NoServices))</p> | |
| 94 | + } else { | |
| 95 | + <ul class="item-list"> | |
| 96 | + for service in services { | |
| 97 | + service_row(lang: lang, service: service) | |
| 98 | + } | |
| 99 | + </ul> | |
| 100 | + } | |
| 101 | + <h2>(text(lang, A::HealthOutbox))</h2> | |
| 102 | + if outbox.is_empty() { | |
| 103 | + <p class="muted">(text(lang, A::NoMail))</p> | |
| 104 | + } else { | |
| 105 | + <dl class="facts"> | |
| 106 | + for (state, count) in outbox { | |
| 107 | + <dt>(state.clone())</dt><dd>(count)</dd> | |
| 108 | + } | |
| 109 | + </dl> | |
| 110 | + } | |
| 111 | + <h2>(text(lang, A::HealthBackups))</h2> | |
| 112 | + if let Some(backups) = backups { | |
| 113 | + <dl class="facts"> | |
| 114 | + <dt>(text(lang, A::HealthBackupLast))</dt><dd>(backups.last_success.clone().unwrap_or_else(|| String::from("-")))</dd> | |
| 115 | + if let Some(error) = backups.last_error { | |
| 116 | + <dt>(text(lang, A::HealthBackupError))</dt><dd>(error)</dd> | |
| 117 | + } | |
| 118 | + </dl> | |
| 119 | + } else { | |
| 120 | + <p class="muted">(text(lang, A::HealthBackupOff))</p> | |
| 121 | + } | |
| 122 | + <h2>(text(lang, A::HealthDatabase))</h2> | |
| 123 | + <dl class="facts"> | |
| 124 | + <dt>(text(lang, A::HealthBytes))</dt><dd>(database_bytes.to_string())</dd> | |
| 125 | + <dt>(text(lang, A::HealthUsers))</dt><dd>(users.to_string())</dd> | |
| 126 | + <dt>(text(lang, A::HealthAdmins))</dt><dd>(admins.to_string())</dd> | |
| 127 | + </dl> | |
| 128 | + </section> | |
| 129 | + ) | |
| 130 | + } | |
| 131 | +} | |
| 132 | + | |
| 133 | +/// One service row: its name, its address, and the answer of its last probe. | |
| 134 | +#[component] | |
| 135 | +async fn service_row(lang: Lang, service: ServiceRow) -> Result<impl View> { | |
| 136 | + let health = match service.healthy { | |
| 137 | + Some(true) => text(lang, A::Healthy), | |
| 138 | + Some(false) => text(lang, A::Unhealthy), | |
| 139 | + None => text(lang, A::NotChecked), | |
| 140 | + }; | |
| 141 | + Ok(view! { | |
| 142 | + <li class="item"> | |
| 143 | + <div class="item-main"> | |
| 144 | + <strong>(service.name.clone())</strong> | |
| 145 | + <div class="muted"><span>(service.url.clone())</span><span>" · "(health)</span></div> | |
| 146 | + </div> | |
| 147 | + </li> | |
| 148 | + }) | |
| 149 | +} |
crates/im-web/src/pages/admin/invites.rsadded+281 -0
| @@ -0,0 +1,281 @@ | ||
| 1 | +//! `/admin/invites`: the invitations that can still be used, a form to send a new one, and the two actions on | |
| 2 | +//! a pending invitation: revoke it, and send a new link (which replaces the old one). | |
| 3 | +//! | |
| 4 | +//! A pending invitation is identified in the page by the hash of its token. The hash is not a usable token, | |
| 5 | +//! so showing it is harmless. Creating an invitation for an address replaces that address's older pending | |
| 6 | +//! invitations in the store, so only the newest link works. | |
| 7 | + | |
| 8 | +use im_core::Error as CoreError; | |
| 9 | +use im_core::model::AuditAction; | |
| 10 | +use im_core::names::parse_email; | |
| 11 | +use im_core::store::invites::invite_lifetime; | |
| 12 | +use im_core::time::stamp_after; | |
| 13 | +use im_core::token::{generate_token, hash_token}; | |
| 14 | +use serde::Deserialize; | |
| 15 | +use serde_json::json; | |
| 16 | +use topcoat::Result; | |
| 17 | +use topcoat::context::{Cx, app_context}; | |
| 18 | +use topcoat::router::content::Form; | |
| 19 | +use topcoat::router::error::{SeeOther, not_found}; | |
| 20 | +use topcoat::router::{page, route}; | |
| 21 | +use topcoat::view::{View, component, view}; | |
| 22 | + | |
| 23 | +use crate::audit::{Actor, record}; | |
| 24 | +use crate::auth::{Viewer, require_admin, require_admin_csrf}; | |
| 25 | +use crate::i18n::Lang; | |
| 26 | +use crate::i18n::admin::{A, text}; | |
| 27 | +use crate::mail::{self, Mail, Recipient}; | |
| 28 | +use crate::pages::admin::{ | |
| 29 | + FlashQuery, Tab, action_button, changed, done, error_text, flash_messages, frame_info, | |
| 30 | + notice_text, refused, tabs, | |
| 31 | +}; | |
| 32 | +use crate::pages::path_param; | |
| 33 | +use crate::state::AppState; | |
| 34 | +use crate::views::{ViewerInfo, field, page_lang, shell}; | |
| 35 | + | |
| 36 | +/// The form that sends an invitation. | |
| 37 | +#[derive(Deserialize, Default)] | |
| 38 | +struct InviteForm { | |
| 39 | + #[serde(default)] | |
| 40 | + csrf: String, | |
| 41 | + #[serde(default)] | |
| 42 | + email: String, | |
| 43 | + /// The checkbox: `on` when ticked. | |
| 44 | + #[serde(default)] | |
| 45 | + admin: String, | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// The form of a pending invitation's actions: only the CSRF token. | |
| 49 | +#[derive(Deserialize, Default)] | |
| 50 | +struct CsrfForm { | |
| 51 | + #[serde(default)] | |
| 52 | + csrf: String, | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// One pending invitation, with its text resolved. | |
| 56 | +struct InviteRow { | |
| 57 | + email: String, | |
| 58 | + admin: bool, | |
| 59 | + expires: String, | |
| 60 | + hash: String, | |
| 61 | +} | |
| 62 | + | |
| 63 | +/// `GET /admin/invites`. | |
| 64 | +#[page("/admin/invites")] | |
| 65 | +async fn invites_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> { | |
| 66 | + let viewer = require_admin(cx).await?; | |
| 67 | + let state = app_context::<AppState>(cx); | |
| 68 | + let (lang, info) = frame_info(cx, &viewer); | |
| 69 | + let rows: Vec<InviteRow> = state | |
| 70 | + .store | |
| 71 | + .pending_invites() | |
| 72 | + .await? | |
| 73 | + .into_iter() | |
| 74 | + .map(|invite| InviteRow { | |
| 75 | + email: invite.email_folded, | |
| 76 | + admin: invite.is_admin, | |
| 77 | + expires: invite.expires_at, | |
| 78 | + hash: invite.token_hash, | |
| 79 | + }) | |
| 80 | + .collect(); | |
| 81 | + Ok(invites_view( | |
| 82 | + cx, | |
| 83 | + lang, | |
| 84 | + info, | |
| 85 | + viewer.session.csrf_token.clone(), | |
| 86 | + rows, | |
| 87 | + notice_text(lang, &query.notice).map(str::to_owned), | |
| 88 | + error_text(lang, &query.error).map(str::to_owned), | |
| 89 | + )) | |
| 90 | +} | |
| 91 | + | |
| 92 | +/// `POST /admin/invites`: creates the invitation and queues its mail. | |
| 93 | +#[route(POST "/admin/invites")] | |
| 94 | +async fn send_invite(cx: &Cx, Form(form): Form<InviteForm>) -> Result<SeeOther> { | |
| 95 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 96 | + let email = match parse_email(&form.email) { | |
| 97 | + Ok(email) => email, | |
| 98 | + Err(_) => return Ok(refused("/admin/invites", "email")), | |
| 99 | + }; | |
| 100 | + let is_admin = form.admin == "on"; | |
| 101 | + let state = app_context::<AppState>(cx); | |
| 102 | + let days = state.policy().invite_days; | |
| 103 | + let token = generate_token(); | |
| 104 | + let expires = stamp_after(invite_lifetime(days)); | |
| 105 | + match state | |
| 106 | + .store | |
| 107 | + .create_invite( | |
| 108 | + &hash_token(&token), | |
| 109 | + &email, | |
| 110 | + is_admin, | |
| 111 | + &viewer.user.id, | |
| 112 | + &expires, | |
| 113 | + ) | |
| 114 | + .await | |
| 115 | + { | |
| 116 | + Ok(()) => {} | |
| 117 | + Err(CoreError::Conflict(_)) => return Ok(refused("/admin/invites", "invite-taken")), | |
| 118 | + Err(error) => return Err(error.into()), | |
| 119 | + } | |
| 120 | + queue_invite(cx, &viewer, &email, &token, days).await; | |
| 121 | + record( | |
| 122 | + cx, | |
| 123 | + Actor::User(&viewer.user.id), | |
| 124 | + AuditAction::InviteCreated, | |
| 125 | + None, | |
| 126 | + json!({ "admin": is_admin }), | |
| 127 | + ) | |
| 128 | + .await; | |
| 129 | + changed(&state.live); | |
| 130 | + Ok(done("/admin/invites", "invite-sent")) | |
| 131 | +} | |
| 132 | + | |
| 133 | +/// Queues the invitation mail for `email`, with the link for `token`. A failure is logged, not returned: | |
| 134 | +/// the invitation exists and can be sent again from this page. | |
| 135 | +async fn queue_invite(cx: &Cx, viewer: &Viewer, email: &str, token: &str, days: u32) { | |
| 136 | + let state = app_context::<AppState>(cx); | |
| 137 | + let lang = page_lang(cx, Some(viewer)); | |
| 138 | + let link = format!("{}/invite/{token}", state.config.base_url); | |
| 139 | + match Recipient::new(None, email) { | |
| 140 | + Ok(to) => { | |
| 141 | + let mail = Mail::Invite { link: &link, days }; | |
| 142 | + if let Err(error) = mail::queue(&state.store, &state.key, &to, lang, &mail).await { | |
| 143 | + tracing::error!(error = %error, "invitation mail not queued"); | |
| 144 | + } | |
| 145 | + } | |
| 146 | + Err(error) => tracing::error!(error, "invitation mail not queued"), | |
| 147 | + } | |
| 148 | +} | |
| 149 | + | |
| 150 | +/// `POST /admin/invites/{hash}/revoke`. | |
| 151 | +#[route(POST "/admin/invites/{hash}/revoke")] | |
| 152 | +async fn revoke_invite(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 153 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 154 | + let hash = invite_hash(cx)?; | |
| 155 | + let state = app_context::<AppState>(cx); | |
| 156 | + if state.store.revoke_invite(&hash).await? { | |
| 157 | + record( | |
| 158 | + cx, | |
| 159 | + Actor::User(&viewer.user.id), | |
| 160 | + AuditAction::InviteRevoked, | |
| 161 | + None, | |
| 162 | + json!({}), | |
| 163 | + ) | |
| 164 | + .await; | |
| 165 | + changed(&state.live); | |
| 166 | + return Ok(done("/admin/invites", "invite-revoked")); | |
| 167 | + } | |
| 168 | + Ok(refused("/admin/invites", "invite-gone")) | |
| 169 | +} | |
| 170 | + | |
| 171 | +/// `POST /admin/invites/{hash}/resend`. A new token is made and mailed; the old link stops working, because | |
| 172 | +/// the store keeps only the newest pending invitation for an address. | |
| 173 | +#[route(POST "/admin/invites/{hash}/resend")] | |
| 174 | +async fn resend_invite(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 175 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 176 | + let hash = invite_hash(cx)?; | |
| 177 | + let state = app_context::<AppState>(cx); | |
| 178 | + let Some(old) = state.store.pending_invite(&hash).await? else { | |
| 179 | + return Ok(refused("/admin/invites", "invite-gone")); | |
| 180 | + }; | |
| 181 | + let days = state.policy().invite_days; | |
| 182 | + let token = generate_token(); | |
| 183 | + let expires = stamp_after(invite_lifetime(days)); | |
| 184 | + match state | |
| 185 | + .store | |
| 186 | + .create_invite( | |
| 187 | + &hash_token(&token), | |
| 188 | + &old.email_folded, | |
| 189 | + old.is_admin, | |
| 190 | + &viewer.user.id, | |
| 191 | + &expires, | |
| 192 | + ) | |
| 193 | + .await | |
| 194 | + { | |
| 195 | + Ok(()) => {} | |
| 196 | + Err(CoreError::Conflict(_)) => return Ok(refused("/admin/invites", "invite-taken")), | |
| 197 | + Err(error) => return Err(error.into()), | |
| 198 | + } | |
| 199 | + queue_invite(cx, &viewer, &old.email_folded, &token, days).await; | |
| 200 | + record( | |
| 201 | + cx, | |
| 202 | + Actor::User(&viewer.user.id), | |
| 203 | + AuditAction::InviteCreated, | |
| 204 | + None, | |
| 205 | + json!({ "admin": old.is_admin, "resent": true }), | |
| 206 | + ) | |
| 207 | + .await; | |
| 208 | + changed(&state.live); | |
| 209 | + Ok(done("/admin/invites", "invite-resent")) | |
| 210 | +} | |
| 211 | + | |
| 212 | +/// The hash in the path of an invitation action. Anything that is not 64 hex digits is a 404. | |
| 213 | +fn invite_hash(cx: &Cx) -> Result<String> { | |
| 214 | + match path_param(cx, "hash") { | |
| 215 | + Some(hash) if hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(hash), | |
| 216 | + _ => Err(not_found().into()), | |
| 217 | + } | |
| 218 | +} | |
| 219 | + | |
| 220 | +/// The invitations page: the pending list, then the form that sends a new one. | |
| 221 | +fn invites_view( | |
| 222 | + cx: &Cx, | |
| 223 | + lang: Lang, | |
| 224 | + info: ViewerInfo, | |
| 225 | + csrf: String, | |
| 226 | + rows: Vec<InviteRow>, | |
| 227 | + success: Option<String>, | |
| 228 | + problem: Option<String>, | |
| 229 | +) -> impl View { | |
| 230 | + view! { cx => | |
| 231 | + shell(title: text(lang, A::InvitesTitle), lang: lang, viewer: Some(info), | |
| 232 | + tabs(lang: lang, current: Tab::Invites) | |
| 233 | + <section class="stack" data-live="/admin/events"> | |
| 234 | + <h1>(text(lang, A::InvitesTitle))</h1> | |
| 235 | + <p class="muted">(text(lang, A::InvitesIntro))</p> | |
| 236 | + flash_messages(success: success, problem: problem) | |
| 237 | + <h2>(text(lang, A::PendingInvites))</h2> | |
| 238 | + if rows.is_empty() { | |
| 239 | + <p class="muted">(text(lang, A::NoInvites))</p> | |
| 240 | + } else { | |
| 241 | + <ul class="item-list"> | |
| 242 | + for row in rows { | |
| 243 | + invite_item(lang: lang, csrf: csrf.clone(), row: row) | |
| 244 | + } | |
| 245 | + </ul> | |
| 246 | + } | |
| 247 | + <h2>(text(lang, A::InviteNew))</h2> | |
| 248 | + <form method="post" action="/admin/invites" class="stack"> | |
| 249 | + <input type="hidden" name="csrf" value=(csrf.clone())> | |
| 250 | + field(label: text(lang, A::InviteEmailLabel), name: "email", kind: "email", autocomplete: "off", value: String::new()) | |
| 251 | + <label class="check"> | |
| 252 | + <input type="checkbox" name="admin"> | |
| 253 | + <span>(text(lang, A::InviteAsAdmin))</span> | |
| 254 | + </label> | |
| 255 | + <button type="submit" class="button primary">(text(lang, A::InviteSendButton))</button> | |
| 256 | + </form> | |
| 257 | + </section> | |
| 258 | + ) | |
| 259 | + } | |
| 260 | +} | |
| 261 | + | |
| 262 | +/// One pending invitation with its two actions. | |
| 263 | +#[component] | |
| 264 | +async fn invite_item(lang: Lang, csrf: String, row: InviteRow) -> Result<impl View> { | |
| 265 | + let base = format!("/admin/invites/{}", row.hash); | |
| 266 | + Ok(view! { | |
| 267 | + <li class="item"> | |
| 268 | + <div class="item-main"> | |
| 269 | + <strong>(row.email.clone())</strong> | |
| 270 | + if row.admin { | |
| 271 | + <span class="badge accent">(text(lang, A::Administrator))</span> | |
| 272 | + } | |
| 273 | + <div class="muted"> | |
| 274 | + <span>(text(lang, A::Expires))": "(row.expires.clone())</span> | |
| 275 | + </div> | |
| 276 | + </div> | |
| 277 | + action_button(action: format!("{base}/resend"), csrf: csrf.clone(), label: text(lang, A::ResendInvite), class: "button ghost", on: "") | |
| 278 | + action_button(action: format!("{base}/revoke"), csrf: csrf.clone(), label: text(lang, A::RevokeInvite), class: "button danger", on: "") | |
| 279 | + </li> | |
| 280 | + }) | |
| 281 | +} |
crates/im-web/src/pages/admin/keys.rsadded+222 -0
| @@ -0,0 +1,222 @@ | ||
| 1 | +//! `/admin/keys`: the token-signing keys, with a rotation now and the retirement of a key that is still | |
| 2 | +//! published. | |
| 3 | +//! | |
| 4 | +//! A key's state is read from the same rules the signer uses (`im_core::keys`): the current key signs, the | |
| 5 | +//! published keys are in the JWKS, and a retired key is no longer published. The store refuses to retire the | |
| 6 | +//! current key, so a token can always be signed. | |
| 7 | + | |
| 8 | +use im_core::model::AuditAction; | |
| 9 | +use im_core::time::now_stamp; | |
| 10 | +use serde::Deserialize; | |
| 11 | +use serde_json::json; | |
| 12 | +use topcoat::Result; | |
| 13 | +use topcoat::context::{Cx, app_context}; | |
| 14 | +use topcoat::router::content::Form; | |
| 15 | +use topcoat::router::error::{SeeOther, not_found}; | |
| 16 | +use topcoat::router::{page, route}; | |
| 17 | +use topcoat::view::{View, component, view}; | |
| 18 | + | |
| 19 | +use crate::audit::{Actor, record}; | |
| 20 | +use crate::auth::{require_admin, require_admin_csrf}; | |
| 21 | +use crate::i18n::Lang; | |
| 22 | +use crate::i18n::admin::{A, text}; | |
| 23 | +use crate::oidc::signing; | |
| 24 | +use crate::pages::admin::{ | |
| 25 | + FlashQuery, Tab, action_button, changed, done, error_text, flash_messages, frame_info, | |
| 26 | + notice_text, refused, tabs, | |
| 27 | +}; | |
| 28 | +use crate::pages::path_param; | |
| 29 | +use crate::state::AppState; | |
| 30 | +use crate::views::{ViewerInfo, shell}; | |
| 31 | + | |
| 32 | +/// The form of the key actions: only the CSRF token. | |
| 33 | +#[derive(Deserialize, Default)] | |
| 34 | +struct CsrfForm { | |
| 35 | + #[serde(default)] | |
| 36 | + csrf: String, | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// Where a key stands now. | |
| 40 | +#[derive(Clone, Copy, PartialEq, Eq)] | |
| 41 | +enum KeyState { | |
| 42 | + Current, | |
| 43 | + Published, | |
| 44 | + Retired, | |
| 45 | + Pending, | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// One key, with its times and its state resolved. | |
| 49 | +struct KeyRow { | |
| 50 | + kid: String, | |
| 51 | + created: String, | |
| 52 | + activates: String, | |
| 53 | + retires: String, | |
| 54 | + state: KeyState, | |
| 55 | + /// True when the store will retire the key: not yet retired, not current, and already active. | |
| 56 | + retirable: bool, | |
| 57 | +} | |
| 58 | + | |
| 59 | +/// `GET /admin/keys`. | |
| 60 | +#[page("/admin/keys")] | |
| 61 | +async fn keys_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> { | |
| 62 | + let viewer = require_admin(cx).await?; | |
| 63 | + let state = app_context::<AppState>(cx); | |
| 64 | + let (lang, info) = frame_info(cx, &viewer); | |
| 65 | + let now = now_stamp(); | |
| 66 | + let keys = state.store.signing_keys().await?; | |
| 67 | + let current = im_core::keys::current(&keys, &now).map(|key| key.kid.clone()); | |
| 68 | + let published: Vec<String> = im_core::keys::published(&keys, &now) | |
| 69 | + .iter() | |
| 70 | + .map(|key| key.kid.clone()) | |
| 71 | + .collect(); | |
| 72 | + let rows: Vec<KeyRow> = keys | |
| 73 | + .iter() | |
| 74 | + .map(|key| { | |
| 75 | + let is_current = Some(&key.kid) == current.as_ref(); | |
| 76 | + let state = if is_current { | |
| 77 | + KeyState::Current | |
| 78 | + } else if published.contains(&key.kid) { | |
| 79 | + KeyState::Published | |
| 80 | + } else if key.activates_at > now { | |
| 81 | + KeyState::Pending | |
| 82 | + } else { | |
| 83 | + KeyState::Retired | |
| 84 | + }; | |
| 85 | + KeyRow { | |
| 86 | + kid: key.kid.clone(), | |
| 87 | + created: key.created_at.clone(), | |
| 88 | + activates: key.activates_at.clone(), | |
| 89 | + retires: key.retires_at.clone().unwrap_or_default(), | |
| 90 | + state, | |
| 91 | + retirable: key.retires_at.is_none() && !is_current && key.activates_at <= now, | |
| 92 | + } | |
| 93 | + }) | |
| 94 | + .collect(); | |
| 95 | + Ok(keys_view( | |
| 96 | + cx, | |
| 97 | + lang, | |
| 98 | + info, | |
| 99 | + viewer.session.csrf_token.clone(), | |
| 100 | + rows, | |
| 101 | + notice_text(lang, &query.notice).map(str::to_owned), | |
| 102 | + error_text(lang, &query.error).map(str::to_owned), | |
| 103 | + )) | |
| 104 | +} | |
| 105 | + | |
| 106 | +/// `POST /admin/keys/rotate`: makes a new key the signing key now. | |
| 107 | +#[route(POST "/admin/keys/rotate")] | |
| 108 | +async fn rotate_keys(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 109 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 110 | + let state = app_context::<AppState>(cx); | |
| 111 | + let kid = signing::rotate_now(&state.store, &state.key).await?; | |
| 112 | + record( | |
| 113 | + cx, | |
| 114 | + Actor::User(&viewer.user.id), | |
| 115 | + AuditAction::KeyRotated, | |
| 116 | + Some(("signing_key", &kid)), | |
| 117 | + json!({}), | |
| 118 | + ) | |
| 119 | + .await; | |
| 120 | + changed(&state.live); | |
| 121 | + Ok(done("/admin/keys", "key-rotated")) | |
| 122 | +} | |
| 123 | + | |
| 124 | +/// `POST /admin/keys/{kid}/retire`. | |
| 125 | +#[route(POST "/admin/keys/{kid}/retire")] | |
| 126 | +async fn retire_key(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 127 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 128 | + let kid = key_id(cx)?; | |
| 129 | + let state = app_context::<AppState>(cx); | |
| 130 | + if state.store.retire_signing_key(&kid).await? { | |
| 131 | + record( | |
| 132 | + cx, | |
| 133 | + Actor::User(&viewer.user.id), | |
| 134 | + AuditAction::KeyRetired, | |
| 135 | + Some(("signing_key", &kid)), | |
| 136 | + json!({}), | |
| 137 | + ) | |
| 138 | + .await; | |
| 139 | + changed(&state.live); | |
| 140 | + return Ok(done("/admin/keys", "key-retired")); | |
| 141 | + } | |
| 142 | + Ok(refused("/admin/keys", "key-current")) | |
| 143 | +} | |
| 144 | + | |
| 145 | +/// The key id in the path. Key ids are letters, digits, `-` and `_`; anything else is a 404. | |
| 146 | +fn key_id(cx: &Cx) -> Result<String> { | |
| 147 | + match path_param(cx, "kid") { | |
| 148 | + Some(kid) | |
| 149 | + if !kid.is_empty() | |
| 150 | + && kid.len() <= 64 | |
| 151 | + && kid | |
| 152 | + .bytes() | |
| 153 | + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') => | |
| 154 | + { | |
| 155 | + Ok(kid) | |
| 156 | + } | |
| 157 | + _ => Err(not_found().into()), | |
| 158 | + } | |
| 159 | +} | |
| 160 | + | |
| 161 | +/// The text of a key state. | |
| 162 | +fn state_text(lang: Lang, state: KeyState) -> &'static str { | |
| 163 | + match state { | |
| 164 | + KeyState::Current => text(lang, A::KeyCurrent), | |
| 165 | + KeyState::Published => text(lang, A::KeyPublished), | |
| 166 | + KeyState::Retired => text(lang, A::KeyRetired), | |
| 167 | + KeyState::Pending => text(lang, A::KeyPending), | |
| 168 | + } | |
| 169 | +} | |
| 170 | + | |
| 171 | +/// The keys page: the rotation button, then one row per key. | |
| 172 | +fn keys_view( | |
| 173 | + cx: &Cx, | |
| 174 | + lang: Lang, | |
| 175 | + info: ViewerInfo, | |
| 176 | + csrf: String, | |
| 177 | + rows: Vec<KeyRow>, | |
| 178 | + success: Option<String>, | |
| 179 | + problem: Option<String>, | |
| 180 | +) -> impl View { | |
| 181 | + view! { cx => | |
| 182 | + shell(title: text(lang, A::KeysTitle), lang: lang, viewer: Some(info), | |
| 183 | + tabs(lang: lang, current: Tab::Keys) | |
| 184 | + <section class="stack" data-live="/admin/events"> | |
| 185 | + <h1>(text(lang, A::KeysTitle))</h1> | |
| 186 | + <p class="muted">(text(lang, A::KeysIntro))</p> | |
| 187 | + flash_messages(success: success, problem: problem) | |
| 188 | + action_button(action: "/admin/keys/rotate".to_owned(), csrf: csrf.clone(), label: text(lang, A::RotateNow), class: "button primary", on: "") | |
| 189 | + <ul class="item-list"> | |
| 190 | + for row in rows { | |
| 191 | + key_item(lang: lang, csrf: csrf.clone(), row: row) | |
| 192 | + } | |
| 193 | + </ul> | |
| 194 | + </section> | |
| 195 | + ) | |
| 196 | + } | |
| 197 | +} | |
| 198 | + | |
| 199 | +/// One key: its id, its times, its state, and the retire button when the store allows it. | |
| 200 | +#[component] | |
| 201 | +async fn key_item(lang: Lang, csrf: String, row: KeyRow) -> Result<impl View> { | |
| 202 | + let state = state_text(lang, row.state); | |
| 203 | + let retire = format!("/admin/keys/{}/retire", row.kid); | |
| 204 | + Ok(view! { | |
| 205 | + <li class="item"> | |
| 206 | + <div class="item-main"> | |
| 207 | + <strong><code>(row.kid.clone())</code></strong> | |
| 208 | + <div class="muted"> | |
| 209 | + <span>(text(lang, A::KeyCreated))": "(row.created.clone())</span> | |
| 210 | + <span>" · "(text(lang, A::KeyActivates))": "(row.activates.clone())</span> | |
| 211 | + if !row.retires.is_empty() { | |
| 212 | + <span>" · "(text(lang, A::KeyRetires))": "(row.retires.clone())</span> | |
| 213 | + } | |
| 214 | + <span>" · "(state)</span> | |
| 215 | + </div> | |
| 216 | + </div> | |
| 217 | + if row.retirable { | |
| 218 | + action_button(action: retire, csrf: csrf.clone(), label: text(lang, A::RetireKey), class: "button danger", on: "") | |
| 219 | + } | |
| 220 | + </li> | |
| 221 | + }) | |
| 222 | +} |
crates/im-web/src/pages/admin/mail.rsadded+299 -0
| @@ -0,0 +1,299 @@ | ||
| 1 | +//! `/admin/mail`: the state of the SMTP settings, the mail outbox with its states, the retry and abandon | |
| 2 | +//! actions, and a test mail to the administrator's own address. | |
| 3 | +//! | |
| 4 | +//! The outbox never shows a body: the store holds it sealed, and the list selects only the header columns. | |
| 5 | +//! Retrying a failed row sends it again at once; abandoning a row that is not yet sent blanks its body, as | |
| 6 | +//! the worker does when it gives up. | |
| 7 | + | |
| 8 | +use im_core::model::AuditAction; | |
| 9 | +use serde::Deserialize; | |
| 10 | +use serde_json::json; | |
| 11 | +use topcoat::Result; | |
| 12 | +use topcoat::context::{Cx, app_context}; | |
| 13 | +use topcoat::router::content::Form; | |
| 14 | +use topcoat::router::error::{SeeOther, not_found}; | |
| 15 | +use topcoat::router::{page, route}; | |
| 16 | +use topcoat::view::{View, component, view}; | |
| 17 | + | |
| 18 | +use crate::audit::{Actor, record}; | |
| 19 | +use crate::auth::{require_admin, require_admin_csrf}; | |
| 20 | +use crate::i18n::Lang; | |
| 21 | +use crate::i18n::admin::{A, text}; | |
| 22 | +use crate::mail::{self, Mail, Recipient}; | |
| 23 | +use crate::pages::admin::{ | |
| 24 | + PAGE_SIZE, Tab, action_button, changed, done, error_text, flash_messages, frame_info, | |
| 25 | + notice_text, refused, tabs, | |
| 26 | +}; | |
| 27 | +use crate::pages::path_param; | |
| 28 | +use crate::state::AppState; | |
| 29 | +use crate::views::{ViewerInfo, page_lang, shell}; | |
| 30 | + | |
| 31 | +/// The query of the mail page: the flash codes, the state filter, and the cursor of the next page. | |
| 32 | +#[derive(Deserialize, Default)] | |
| 33 | +struct MailQuery { | |
| 34 | + #[serde(default)] | |
| 35 | + notice: String, | |
| 36 | + #[serde(default)] | |
| 37 | + error: String, | |
| 38 | + /// `pending`, `sent`, `failed` or `abandoned`. Anything else shows every state. | |
| 39 | + #[serde(default)] | |
| 40 | + state: String, | |
| 41 | + /// The id of the last row of the previous page. | |
| 42 | + #[serde(default)] | |
| 43 | + after: String, | |
| 44 | +} | |
| 45 | + | |
| 46 | +/// The form of the mail actions: only the CSRF token. | |
| 47 | +#[derive(Deserialize, Default)] | |
| 48 | +struct CsrfForm { | |
| 49 | + #[serde(default)] | |
| 50 | + csrf: String, | |
| 51 | +} | |
| 52 | + | |
| 53 | +/// The SMTP settings as the page shows them. The password is never shown, only whether a login is set. | |
| 54 | +struct SmtpInfo { | |
| 55 | + host: String, | |
| 56 | + sender: String, | |
| 57 | + login: String, | |
| 58 | +} | |
| 59 | + | |
| 60 | +/// The states the filter links offer. | |
| 61 | +const STATES: [&str; 4] = ["pending", "sent", "failed", "abandoned"]; | |
| 62 | + | |
| 63 | +/// `GET /admin/mail`. | |
| 64 | +#[page("/admin/mail")] | |
| 65 | +async fn mail_page(cx: &Cx, Form(query): Form<MailQuery>) -> Result<impl View> { | |
| 66 | + let viewer = require_admin(cx).await?; | |
| 67 | + let state = app_context::<AppState>(cx); | |
| 68 | + let (lang, info) = frame_info(cx, &viewer); | |
| 69 | + let filter = STATES | |
| 70 | + .contains(&query.state.as_str()) | |
| 71 | + .then(|| query.state.clone()); | |
| 72 | + let after = (!query.after.is_empty()).then(|| query.after.clone()); | |
| 73 | + let mut rows = state | |
| 74 | + .store | |
| 75 | + .outbox_page(filter.as_deref(), after.as_deref(), PAGE_SIZE + 1) | |
| 76 | + .await?; | |
| 77 | + let next = if rows.len() > PAGE_SIZE as usize { | |
| 78 | + rows.truncate(PAGE_SIZE as usize); | |
| 79 | + rows.last().map(|row| row.id.clone()) | |
| 80 | + } else { | |
| 81 | + None | |
| 82 | + }; | |
| 83 | + let counts = state.store.outbox_counts().await?; | |
| 84 | + let smtp = state.config.smtp.enabled().then(|| SmtpInfo { | |
| 85 | + host: format!("{}:{}", state.config.smtp.host, state.config.smtp.port), | |
| 86 | + sender: format!( | |
| 87 | + "{} <{}>", | |
| 88 | + state.config.smtp.from_name, state.config.smtp.from | |
| 89 | + ), | |
| 90 | + login: if state.config.smtp.username.is_empty() { | |
| 91 | + String::from("-") | |
| 92 | + } else { | |
| 93 | + state.config.smtp.username.clone() | |
| 94 | + }, | |
| 95 | + }); | |
| 96 | + Ok(mail_view( | |
| 97 | + cx, | |
| 98 | + lang, | |
| 99 | + info, | |
| 100 | + viewer.session.csrf_token.clone(), | |
| 101 | + smtp, | |
| 102 | + counts, | |
| 103 | + filter.unwrap_or_default(), | |
| 104 | + rows, | |
| 105 | + next, | |
| 106 | + notice_text(lang, &query.notice).map(str::to_owned), | |
| 107 | + error_text(lang, &query.error).map(str::to_owned), | |
| 108 | + )) | |
| 109 | +} | |
| 110 | + | |
| 111 | +/// `POST /admin/mail/test`: queues a test mail to the administrator's own address. | |
| 112 | +#[route(POST "/admin/mail/test")] | |
| 113 | +async fn send_test(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 114 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 115 | + let state = app_context::<AppState>(cx); | |
| 116 | + let lang = page_lang(cx, Some(&viewer)); | |
| 117 | + let Ok(to) = Recipient::new(Some(&viewer.user.name), &viewer.user.email) else { | |
| 118 | + return Ok(refused("/admin/mail", "email")); | |
| 119 | + }; | |
| 120 | + let mail = Mail::Test { | |
| 121 | + subject: text(lang, A::TestMailSubject), | |
| 122 | + body: text(lang, A::TestMailBody), | |
| 123 | + }; | |
| 124 | + mail::queue(&state.store, &state.key, &to, lang, &mail).await?; | |
| 125 | + record( | |
| 126 | + cx, | |
| 127 | + Actor::User(&viewer.user.id), | |
| 128 | + AuditAction::MailTestQueued, | |
| 129 | + None, | |
| 130 | + json!({}), | |
| 131 | + ) | |
| 132 | + .await; | |
| 133 | + changed(&state.live); | |
| 134 | + Ok(done("/admin/mail", "test-queued")) | |
| 135 | +} | |
| 136 | + | |
| 137 | +/// `POST /admin/mail/{id}/retry`: a failed row is sent again now. | |
| 138 | +#[route(POST "/admin/mail/{id}/retry")] | |
| 139 | +async fn retry_mail(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 140 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 141 | + let id = outbox_id(cx)?; | |
| 142 | + let state = app_context::<AppState>(cx); | |
| 143 | + if !state.store.retry_mail(&id).await? { | |
| 144 | + return Ok(refused("/admin/mail", "mail-retry")); | |
| 145 | + } | |
| 146 | + record( | |
| 147 | + cx, | |
| 148 | + Actor::User(&viewer.user.id), | |
| 149 | + AuditAction::MailRetried, | |
| 150 | + Some(("mail", &id)), | |
| 151 | + json!({}), | |
| 152 | + ) | |
| 153 | + .await; | |
| 154 | + changed(&state.live); | |
| 155 | + Ok(done("/admin/mail", "mail-retried")) | |
| 156 | +} | |
| 157 | + | |
| 158 | +/// `POST /admin/mail/{id}/abandon`: a row that is not yet sent is given up, and its body is removed. | |
| 159 | +#[route(POST "/admin/mail/{id}/abandon")] | |
| 160 | +async fn abandon_mail(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 161 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 162 | + let id = outbox_id(cx)?; | |
| 163 | + let state = app_context::<AppState>(cx); | |
| 164 | + if !state.store.abandon_mail(&id).await? { | |
| 165 | + return Ok(refused("/admin/mail", "mail-abandon")); | |
| 166 | + } | |
| 167 | + record( | |
| 168 | + cx, | |
| 169 | + Actor::User(&viewer.user.id), | |
| 170 | + AuditAction::MailAbandoned, | |
| 171 | + Some(("mail", &id)), | |
| 172 | + json!({}), | |
| 173 | + ) | |
| 174 | + .await; | |
| 175 | + changed(&state.live); | |
| 176 | + Ok(done("/admin/mail", "mail-abandoned")) | |
| 177 | +} | |
| 178 | + | |
| 179 | +/// The outbox id in the path. Ids are ULIDs: 26 letters and digits. Anything else is a 404. | |
| 180 | +fn outbox_id(cx: &Cx) -> Result<String> { | |
| 181 | + match path_param(cx, "id") { | |
| 182 | + Some(id) if id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) => Ok(id), | |
| 183 | + _ => Err(not_found().into()), | |
| 184 | + } | |
| 185 | +} | |
| 186 | + | |
| 187 | +/// The mail page: SMTP status, the state counts, the filter links, the outbox, and the test button. | |
| 188 | +#[allow(clippy::too_many_arguments)] | |
| 189 | +fn mail_view( | |
| 190 | + cx: &Cx, | |
| 191 | + lang: Lang, | |
| 192 | + info: ViewerInfo, | |
| 193 | + csrf: String, | |
| 194 | + smtp: Option<SmtpInfo>, | |
| 195 | + counts: Vec<(String, i64)>, | |
| 196 | + filter: String, | |
| 197 | + rows: Vec<im_core::store::admin::OutboxRow>, | |
| 198 | + next: Option<String>, | |
| 199 | + success: Option<String>, | |
| 200 | + problem: Option<String>, | |
| 201 | +) -> impl View { | |
| 202 | + let next_href = next.map(|after| { | |
| 203 | + if filter.is_empty() { | |
| 204 | + format!("/admin/mail?after={after}") | |
| 205 | + } else { | |
| 206 | + format!("/admin/mail?state={filter}&after={after}") | |
| 207 | + } | |
| 208 | + }); | |
| 209 | + view! { cx => | |
| 210 | + shell(title: text(lang, A::MailTitle), lang: lang, viewer: Some(info), | |
| 211 | + tabs(lang: lang, current: Tab::Mail) | |
| 212 | + <section class="stack" data-live="/admin/events"> | |
| 213 | + <h1>(text(lang, A::MailTitle))</h1> | |
| 214 | + <p class="muted">(text(lang, A::MailIntro))</p> | |
| 215 | + flash_messages(success: success, problem: problem) | |
| 216 | + <h2>(text(lang, A::SmtpStatus))</h2> | |
| 217 | + if let Some(smtp) = smtp { | |
| 218 | + <dl class="facts"> | |
| 219 | + <dt>(text(lang, A::SmtpHost))</dt><dd>(smtp.host.clone())</dd> | |
| 220 | + <dt>(text(lang, A::SmtpSender))</dt><dd>(smtp.sender.clone())</dd> | |
| 221 | + <dt>(text(lang, A::SmtpLogin))</dt><dd>(smtp.login.clone())</dd> | |
| 222 | + </dl> | |
| 223 | + } else { | |
| 224 | + <p class="muted">(text(lang, A::SmtpNotConfigured))</p> | |
| 225 | + } | |
| 226 | + action_button(action: "/admin/mail/test".to_owned(), csrf: csrf.clone(), label: text(lang, A::SendTest), class: "button ghost", on: "") | |
| 227 | + <h2>(text(lang, A::OutboxTitle))</h2> | |
| 228 | + <p class="row"> | |
| 229 | + <span class="muted">(text(lang, A::OutboxFilter))": "</span> | |
| 230 | + <a href="/admin/mail">(text(lang, A::AllStates))</a> | |
| 231 | + for (state, count) in counts { | |
| 232 | + <a href=(format!("/admin/mail?state={state}"))>(state_label(lang, &state))" ("(count)")"</a> | |
| 233 | + } | |
| 234 | + </p> | |
| 235 | + if rows.is_empty() { | |
| 236 | + <p class="muted">(text(lang, A::NoMail))</p> | |
| 237 | + } else { | |
| 238 | + <ul class="item-list"> | |
| 239 | + for row in rows { | |
| 240 | + mail_item(lang: lang, csrf: csrf.clone(), row: row) | |
| 241 | + } | |
| 242 | + </ul> | |
| 243 | + } | |
| 244 | + if let Some(href) = next_href { | |
| 245 | + <p><a class="button ghost" href=(href)>(text(lang, A::NextPage))</a></p> | |
| 246 | + } | |
| 247 | + </section> | |
| 248 | + ) | |
| 249 | + } | |
| 250 | +} | |
| 251 | + | |
| 252 | +/// The text of an outbox state. Unknown states are shown as they are stored. | |
| 253 | +fn state_label(lang: Lang, state: &str) -> String { | |
| 254 | + match state { | |
| 255 | + "pending" => text(lang, A::StatePending).to_owned(), | |
| 256 | + "sent" => text(lang, A::StateSent).to_owned(), | |
| 257 | + "failed" => text(lang, A::StateFailed).to_owned(), | |
| 258 | + "abandoned" => text(lang, A::StateAbandoned).to_owned(), | |
| 259 | + other => other.to_owned(), | |
| 260 | + } | |
| 261 | +} | |
| 262 | + | |
| 263 | +/// One outbox row: its recipient, subject, state, attempts, and the actions the state allows. | |
| 264 | +#[component] | |
| 265 | +async fn mail_item( | |
| 266 | + lang: Lang, | |
| 267 | + csrf: String, | |
| 268 | + row: im_core::store::admin::OutboxRow, | |
| 269 | +) -> Result<impl View> { | |
| 270 | + let state = state_label(lang, &row.state); | |
| 271 | + let retry = format!("/admin/mail/{}/retry", row.id); | |
| 272 | + let abandon = format!("/admin/mail/{}/abandon", row.id); | |
| 273 | + let can_retry = row.state == "failed"; | |
| 274 | + let can_abandon = row.state == "pending" || row.state == "failed"; | |
| 275 | + Ok(view! { | |
| 276 | + <li class="item"> | |
| 277 | + <div class="item-main"> | |
| 278 | + <strong>(row.subject.clone())</strong> | |
| 279 | + <div class="muted"> | |
| 280 | + <span>(row.to_addr.clone())</span> | |
| 281 | + <span>" · "(row.kind.clone())</span> | |
| 282 | + <span>" · "(state)</span> | |
| 283 | + <span>" · "(text(lang, A::Attempts))": "(row.attempts)</span> | |
| 284 | + <span>" · "(text(lang, A::NextAttempt))": "(row.next_attempt_at.clone())</span> | |
| 285 | + <span>" · "(text(lang, A::Created))": "(row.created_at.clone())</span> | |
| 286 | + </div> | |
| 287 | + if let Some(error) = row.last_error.clone() { | |
| 288 | + <div class="hint">(text(lang, A::LastError))": "(error)</div> | |
| 289 | + } | |
| 290 | + </div> | |
| 291 | + if can_retry { | |
| 292 | + action_button(action: retry, csrf: csrf.clone(), label: text(lang, A::Retry), class: "button ghost", on: "") | |
| 293 | + } | |
| 294 | + if can_abandon { | |
| 295 | + action_button(action: abandon, csrf: csrf.clone(), label: text(lang, A::Abandon), class: "button danger", on: "") | |
| 296 | + } | |
| 297 | + </li> | |
| 298 | + }) | |
| 299 | +} |
crates/im-web/src/pages/admin/message.rsadded+150 -0
| @@ -0,0 +1,150 @@ | ||
| 1 | +//! `/admin/message`: a message from the administrator to every enabled account. | |
| 2 | +//! | |
| 3 | +//! The message is queued as one mail per account, in that account's language, through the same outbox as | |
| 4 | +//! every other mail. The subject is one line of at most 150 characters; the body is at most 10 000 | |
| 5 | +//! characters, and blank lines separate its paragraphs. Each send counts against a small rate limit, so a | |
| 6 | +//! form that is submitted again and again cannot queue thousands of mails. | |
| 7 | + | |
| 8 | +use std::time::Instant; | |
| 9 | + | |
| 10 | +use im_core::model::AuditAction; | |
| 11 | +use serde::Deserialize; | |
| 12 | +use serde_json::json; | |
| 13 | +use topcoat::Result; | |
| 14 | +use topcoat::context::{Cx, app_context}; | |
| 15 | +use topcoat::router::content::Form; | |
| 16 | +use topcoat::router::error::SeeOther; | |
| 17 | +use topcoat::router::{page, route}; | |
| 18 | +use topcoat::view::{View, view}; | |
| 19 | + | |
| 20 | +use crate::audit::{Actor, record}; | |
| 21 | +use crate::auth::{require_admin, require_admin_csrf}; | |
| 22 | +use crate::i18n::Lang; | |
| 23 | +use crate::i18n::admin::{A, text}; | |
| 24 | +use crate::mail::{self, Mail, Recipient}; | |
| 25 | +use crate::pages::admin::{ | |
| 26 | + FlashQuery, Tab, changed, done, error_text, flash_messages, frame_info, notice_text, refused, | |
| 27 | + tabs, | |
| 28 | +}; | |
| 29 | +use crate::state::AppState; | |
| 30 | +use crate::views::{ViewerInfo, field, page_lang, shell}; | |
| 31 | + | |
| 32 | +/// The longest subject, in characters. | |
| 33 | +const SUBJECT_MAX: usize = 150; | |
| 34 | + | |
| 35 | +/// The longest body, in characters. | |
| 36 | +const BODY_MAX: usize = 10_000; | |
| 37 | + | |
| 38 | +/// Sends that the limit allows in one window of the throttle. | |
| 39 | +const SENDS_PER_WINDOW: usize = 5; | |
| 40 | + | |
| 41 | +/// The throttle key of the message form. | |
| 42 | +const THROTTLE_KEY: &str = "admin-message"; | |
| 43 | + | |
| 44 | +/// The message form. | |
| 45 | +#[derive(Deserialize, Default)] | |
| 46 | +struct MessageForm { | |
| 47 | + #[serde(default)] | |
| 48 | + csrf: String, | |
| 49 | + #[serde(default)] | |
| 50 | + subject: String, | |
| 51 | + #[serde(default)] | |
| 52 | + body: String, | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// `GET /admin/message`. | |
| 56 | +#[page("/admin/message")] | |
| 57 | +async fn message_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> { | |
| 58 | + let viewer = require_admin(cx).await?; | |
| 59 | + let (lang, info) = frame_info(cx, &viewer); | |
| 60 | + Ok(message_view( | |
| 61 | + cx, | |
| 62 | + lang, | |
| 63 | + info, | |
| 64 | + viewer.session.csrf_token.clone(), | |
| 65 | + notice_text(lang, &query.notice).map(str::to_owned), | |
| 66 | + error_text(lang, &query.error).map(str::to_owned), | |
| 67 | + )) | |
| 68 | +} | |
| 69 | + | |
| 70 | +/// `POST /admin/message`: queues the message for every enabled account. | |
| 71 | +#[route(POST "/admin/message")] | |
| 72 | +async fn send_message(cx: &Cx, Form(form): Form<MessageForm>) -> Result<SeeOther> { | |
| 73 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 74 | + let state = app_context::<AppState>(cx); | |
| 75 | + let subject = form.subject.trim(); | |
| 76 | + let body = form.body.replace("\r\n", "\n"); | |
| 77 | + let body = body.trim(); | |
| 78 | + if subject.is_empty() || body.is_empty() { | |
| 79 | + return Ok(refused("/admin/message", "message-empty")); | |
| 80 | + } | |
| 81 | + if subject.chars().count() > SUBJECT_MAX || subject.contains(['\r', '\n']) { | |
| 82 | + return Ok(refused("/admin/message", "message-subject")); | |
| 83 | + } | |
| 84 | + if body.chars().count() > BODY_MAX { | |
| 85 | + return Ok(refused("/admin/message", "message-body")); | |
| 86 | + } | |
| 87 | + let now = Instant::now(); | |
| 88 | + if state | |
| 89 | + .throttle | |
| 90 | + .check(THROTTLE_KEY, SENDS_PER_WINDOW, now) | |
| 91 | + .is_some() | |
| 92 | + { | |
| 93 | + return Ok(refused("/admin/message", "rate-limited")); | |
| 94 | + } | |
| 95 | + let request = page_lang(cx, Some(&viewer)); | |
| 96 | + let users = state.store.list_users(None, None, u32::MAX).await?; | |
| 97 | + let mut recipients = 0_usize; | |
| 98 | + for user in users.iter().filter(|user| user.disabled_at.is_none()) { | |
| 99 | + let Ok(to) = Recipient::new(Some(&user.name), &user.email) else { | |
| 100 | + tracing::error!(user = %user.id, "message not queued: stored address is not valid"); | |
| 101 | + continue; | |
| 102 | + }; | |
| 103 | + let lang = mail::lang_for(user, request); | |
| 104 | + let mail = Mail::Notice { subject, body }; | |
| 105 | + mail::queue(&state.store, &state.key, &to, lang, &mail).await?; | |
| 106 | + recipients += 1; | |
| 107 | + } | |
| 108 | + state.throttle.record_failure(THROTTLE_KEY, now); | |
| 109 | + record( | |
| 110 | + cx, | |
| 111 | + Actor::User(&viewer.user.id), | |
| 112 | + AuditAction::MessageSent, | |
| 113 | + None, | |
| 114 | + json!({ "recipients": recipients }), | |
| 115 | + ) | |
| 116 | + .await; | |
| 117 | + changed(&state.live); | |
| 118 | + Ok(done("/admin/message", "message-sent")) | |
| 119 | +} | |
| 120 | + | |
| 121 | +/// The message page: the subject and body fields, and the send button. | |
| 122 | +fn message_view( | |
| 123 | + cx: &Cx, | |
| 124 | + lang: Lang, | |
| 125 | + info: ViewerInfo, | |
| 126 | + csrf: String, | |
| 127 | + success: Option<String>, | |
| 128 | + problem: Option<String>, | |
| 129 | +) -> impl View { | |
| 130 | + view! { cx => | |
| 131 | + shell(title: text(lang, A::MessageTitle), lang: lang, viewer: Some(info), | |
| 132 | + tabs(lang: lang, current: Tab::Message) | |
| 133 | + <section class="stack"> | |
| 134 | + <h1>(text(lang, A::MessageTitle))</h1> | |
| 135 | + <p class="muted">(text(lang, A::MessageIntro))</p> | |
| 136 | + flash_messages(success: success, problem: problem) | |
| 137 | + <form method="post" action="/admin/message" class="stack"> | |
| 138 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 139 | + field(label: text(lang, A::MessageSubject), name: "subject", kind: "text", autocomplete: "off", value: String::new()) | |
| 140 | + <label class="field"> | |
| 141 | + <span class="field-label">(text(lang, A::MessageBody))</span> | |
| 142 | + <textarea name="body" rows="10"></textarea> | |
| 143 | + <span class="hint">(text(lang, A::MessageBodyHint))</span> | |
| 144 | + </label> | |
| 145 | + <button type="submit" class="button primary">(text(lang, A::MessageSend))</button> | |
| 146 | + </form> | |
| 147 | + </section> | |
| 148 | + ) | |
| 149 | + } | |
| 150 | +} |
crates/im-web/src/pages/admin/mod.rsadded+226 -0
| @@ -0,0 +1,226 @@ | ||
| 1 | +//! The administrator area: users, invitations, services and clients, mail, message, policy settings, signing | |
| 2 | +//! keys, the audit log and health. | |
| 3 | +//! | |
| 4 | +//! Every page and every form here calls [`require_admin`] (or [`require_admin_csrf`] for a form). A member, or | |
| 5 | +//! anyone signed out, gets the styled 404 before anything else happens, so the area does not reveal itself. | |
| 6 | +//! A form also checks its CSRF token before any side effect, and answers 403 when the token is wrong. | |
| 7 | +//! | |
| 8 | +//! Writes redirect (Post/Redirect/Get) with a short code in the query string: `?notice=<code>` for success, | |
| 9 | +//! `?error=<code>` for a refusal. The codes map to translated text in [`notice_text`] and [`error_text`]. A | |
| 10 | +//! write that changes what an admin page shows calls [`changed`], which wakes the page's live stream | |
| 11 | +//! (`/admin/events`). A write that changes what a person sees of their own account also bumps that account's | |
| 12 | +//! topic, so their open pages refresh. | |
| 13 | + | |
| 14 | +pub mod audit; | |
| 15 | +pub mod clients; | |
| 16 | +pub mod health; | |
| 17 | +pub mod invites; | |
| 18 | +pub mod keys; | |
| 19 | +pub mod mail; | |
| 20 | +pub mod message; | |
| 21 | +pub mod settings; | |
| 22 | +pub mod users; | |
| 23 | + | |
| 24 | +#[cfg(test)] | |
| 25 | +mod tests; | |
| 26 | + | |
| 27 | +use serde::Deserialize; | |
| 28 | +use topcoat::Result; | |
| 29 | +use topcoat::context::{Cx, app_context}; | |
| 30 | +use topcoat::router::error::{SeeOther, see_other}; | |
| 31 | +use topcoat::router::response::Response; | |
| 32 | +use topcoat::router::route; | |
| 33 | +use topcoat::view::{View, component, view}; | |
| 34 | + | |
| 35 | +use crate::auth::require_admin; | |
| 36 | +use crate::i18n::Lang; | |
| 37 | +use crate::i18n::account::{Txt, text as account_text}; | |
| 38 | +use crate::i18n::admin::{A, text}; | |
| 39 | +use crate::live::{LiveHub, Topic, stream_changes}; | |
| 40 | +use crate::state::AppState; | |
| 41 | +use crate::views::{ViewerInfo, alert, notice, page_lang}; | |
| 42 | + | |
| 43 | +/// Rows per page of the long lists (users, mail, audit log). | |
| 44 | +pub const PAGE_SIZE: u32 = 50; | |
| 45 | + | |
| 46 | +/// The query of every admin list and of the redirects after a write. | |
| 47 | +#[derive(Deserialize, Default)] | |
| 48 | +pub struct FlashQuery { | |
| 49 | + /// A success code, see [`notice_text`]. | |
| 50 | + #[serde(default)] | |
| 51 | + pub notice: String, | |
| 52 | + /// A refusal code, see [`error_text`]. | |
| 53 | + #[serde(default)] | |
| 54 | + pub error: String, | |
| 55 | +} | |
| 56 | + | |
| 57 | +/// The tabs of the administrator area. | |
| 58 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 59 | +pub enum Tab { | |
| 60 | + Users, | |
| 61 | + Invites, | |
| 62 | + Services, | |
| 63 | + Mail, | |
| 64 | + Message, | |
| 65 | + Settings, | |
| 66 | + Keys, | |
| 67 | + Audit, | |
| 68 | + Health, | |
| 69 | +} | |
| 70 | + | |
| 71 | +/// The tab bar, with the current tab marked. | |
| 72 | +#[component] | |
| 73 | +pub async fn tabs(lang: Lang, current: Tab) -> Result<impl View> { | |
| 74 | + Ok(view! { | |
| 75 | + <nav class="tabs" aria-label=(account_text(lang, Txt::AdminArea))> | |
| 76 | + <a href="/admin/users" class=(tab_class(current, Tab::Users))>(text(lang, A::NavUsers))</a> | |
| 77 | + <a href="/admin/invites" class=(tab_class(current, Tab::Invites))>(text(lang, A::NavInvites))</a> | |
| 78 | + <a href="/admin/services" class=(tab_class(current, Tab::Services))>(text(lang, A::NavServices))</a> | |
| 79 | + <a href="/admin/mail" class=(tab_class(current, Tab::Mail))>(text(lang, A::NavMail))</a> | |
| 80 | + <a href="/admin/message" class=(tab_class(current, Tab::Message))>(text(lang, A::NavMessage))</a> | |
| 81 | + <a href="/admin/settings" class=(tab_class(current, Tab::Settings))>(text(lang, A::NavSettings))</a> | |
| 82 | + <a href="/admin/keys" class=(tab_class(current, Tab::Keys))>(text(lang, A::NavKeys))</a> | |
| 83 | + <a href="/admin/audit" class=(tab_class(current, Tab::Audit))>(text(lang, A::NavAudit))</a> | |
| 84 | + <a href="/admin/health" class=(tab_class(current, Tab::Health))>(text(lang, A::NavHealth))</a> | |
| 85 | + </nav> | |
| 86 | + }) | |
| 87 | +} | |
| 88 | + | |
| 89 | +/// The CSS class of one tab: the current one is marked for the screen reader and the style. | |
| 90 | +fn tab_class(current: Tab, tab: Tab) -> &'static str { | |
| 91 | + if current == tab { "tab current" } else { "tab" } | |
| 92 | +} | |
| 93 | + | |
| 94 | +/// Notifies the admin pages that something they show has changed. Call it after the write commits. | |
| 95 | +pub fn changed(live: &LiveHub) { | |
| 96 | + live.bump(&Topic::Admin); | |
| 97 | +} | |
| 98 | + | |
| 99 | +/// The text of a success code, or `None` for an unknown code (which is then ignored). | |
| 100 | +pub fn notice_text(lang: Lang, code: &str) -> Option<&'static str> { | |
| 101 | + let key = match code { | |
| 102 | + "disabled" => A::NoticeDisabled, | |
| 103 | + "enabled" => A::NoticeEnabled, | |
| 104 | + "admin-granted" => A::NoticeAdminGranted, | |
| 105 | + "admin-removed" => A::NoticeAdminRemoved, | |
| 106 | + "2fa-reset" => A::NoticeTwoFactorReset, | |
| 107 | + "sessions-revoked" => A::NoticeSessionsRevoked, | |
| 108 | + "deleted" => A::NoticeDeleted, | |
| 109 | + "invite-revoked" => A::NoticeInviteRevoked, | |
| 110 | + "invite-resent" => A::NoticeInviteResent, | |
| 111 | + "invite-sent" => A::InviteQueued, | |
| 112 | + "client-saved" => A::ClientSaved, | |
| 113 | + "secret-rotated" => A::NoticeSecretRotated, | |
| 114 | + "client-disabled" => A::NoticeClientDisabled, | |
| 115 | + "mail-retried" => A::NoticeMailRetried, | |
| 116 | + "mail-abandoned" => A::NoticeMailAbandoned, | |
| 117 | + "test-queued" => A::NoticeTestQueued, | |
| 118 | + "settings-saved" => A::NoticeSettingsSaved, | |
| 119 | + "key-rotated" => A::NoticeKeyRotated, | |
| 120 | + "key-retired" => A::NoticeKeyRetired, | |
| 121 | + "file-value" => A::NoticeFileValue, | |
| 122 | + "message-sent" => A::NoticeMessageSent, | |
| 123 | + _ => return None, | |
| 124 | + }; | |
| 125 | + Some(text(lang, key)) | |
| 126 | +} | |
| 127 | + | |
| 128 | +/// The text of a refusal code, or `None` for an unknown code. | |
| 129 | +pub fn error_text(lang: Lang, code: &str) -> Option<&'static str> { | |
| 130 | + let key = match code { | |
| 131 | + "last-admin" => A::ErrLastAdmin, | |
| 132 | + "self-disable" => A::ErrSelfDisable, | |
| 133 | + "self-admin" => A::ErrSelfAdmin, | |
| 134 | + "self-delete" => A::ErrSelfDelete, | |
| 135 | + "self" => A::NoOwnAccountHere, | |
| 136 | + "confirm-email" => A::ErrConfirmEmail, | |
| 137 | + "mail-retry" => A::ErrMailNotRetryable, | |
| 138 | + "mail-abandon" => A::ErrMailNotAbandonable, | |
| 139 | + "message-empty" => A::ErrMessageEmpty, | |
| 140 | + "message-subject" => A::ErrMessageSubjectLong, | |
| 141 | + "message-body" => A::ErrMessageBodyLong, | |
| 142 | + "message-email" => A::ErrMessageEmailInvalid, | |
| 143 | + "rate-limited" => A::ErrMessageRateLimited, | |
| 144 | + "key-current" => A::ErrKeyNotRetirable, | |
| 145 | + "invite-gone" => A::ErrInviteGone, | |
| 146 | + "no-client" => A::ErrNoSuchClient, | |
| 147 | + "settings" => A::ErrSettingsInvalid, | |
| 148 | + "invite-taken" => A::ErrInviteTaken, | |
| 149 | + "email" => A::ErrInviteAddress, | |
| 150 | + "client-name" => A::ErrClientName, | |
| 151 | + "client-uri" => A::ErrUri, | |
| 152 | + "family-key" => A::ErrFamilyKey, | |
| 153 | + "family-taken" => A::ErrFamilyKeyTaken, | |
| 154 | + "public-url" => A::ErrPublicUrl, | |
| 155 | + "scopes" => A::ErrScopes, | |
| 156 | + _ => return None, | |
| 157 | + }; | |
| 158 | + Some(text(lang, key)) | |
| 159 | +} | |
| 160 | + | |
| 161 | +/// `path?error=<code>`, the redirect of a refused write. | |
| 162 | +pub fn refused(path: &str, code: &str) -> SeeOther { | |
| 163 | + see_other(format!("{path}?error={code}")) | |
| 164 | +} | |
| 165 | + | |
| 166 | +/// `path?notice=<code>`, the redirect of a successful write. | |
| 167 | +pub fn done(path: &str, code: &str) -> SeeOther { | |
| 168 | + see_other(format!("{path}?notice={code}")) | |
| 169 | +} | |
| 170 | + | |
| 171 | +/// The viewer's info and language for an admin page, after the admin check. | |
| 172 | +pub fn frame_info(cx: &Cx, viewer: &crate::auth::Viewer) -> (Lang, ViewerInfo) { | |
| 173 | + (page_lang(cx, Some(viewer)), ViewerInfo::of(viewer)) | |
| 174 | +} | |
| 175 | + | |
| 176 | +/// `GET /admin`: the first tab. Non-administrators get 404. | |
| 177 | +#[route(GET "/admin")] | |
| 178 | +async fn admin_root(cx: &Cx) -> Result<SeeOther> { | |
| 179 | + require_admin(cx).await?; | |
| 180 | + Ok(see_other("/admin/users")) | |
| 181 | +} | |
| 182 | + | |
| 183 | +/// `GET /admin/events`: the live stream of the admin pages. It sends one `changed` event for each admin | |
| 184 | +/// write, and the page fetches itself again. Non-administrators get 404. | |
| 185 | +#[route(GET "/admin/events")] | |
| 186 | +async fn admin_events(cx: &Cx) -> Result<Response> { | |
| 187 | + require_admin(cx).await?; | |
| 188 | + let state = app_context::<AppState>(cx); | |
| 189 | + let live = state.live.clone(); | |
| 190 | + stream_changes(cx, &state.live, &[Topic::Admin], move || { | |
| 191 | + let live = live.clone(); | |
| 192 | + async move { Ok(live.generation(&Topic::Admin).to_string()) } | |
| 193 | + }) | |
| 194 | + .await | |
| 195 | +} | |
| 196 | + | |
| 197 | +/// A form with one button, and the CSRF token. `on` is sent as a hidden field; it is empty for most actions. | |
| 198 | +#[component] | |
| 199 | +pub async fn action_button( | |
| 200 | + action: String, | |
| 201 | + csrf: String, | |
| 202 | + label: &'static str, | |
| 203 | + class: &'static str, | |
| 204 | + on: &'static str, | |
| 205 | +) -> Result<impl View> { | |
| 206 | + Ok(view! { | |
| 207 | + <form method="post" action=(action) class="inline-form"> | |
| 208 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 209 | + <input type="hidden" name="on" value=(on)> | |
| 210 | + <button type="submit" class=(class)>(label)</button> | |
| 211 | + </form> | |
| 212 | + }) | |
| 213 | +} | |
| 214 | + | |
| 215 | +/// The success notice and the alert of an admin page, drawn above its content. | |
| 216 | +#[component] | |
| 217 | +pub async fn flash_messages(success: Option<String>, problem: Option<String>) -> Result<impl View> { | |
| 218 | + Ok(view! { | |
| 219 | + if let Some(message) = success { | |
| 220 | + notice(message: message) | |
| 221 | + } | |
| 222 | + if let Some(message) = problem { | |
| 223 | + alert(message: message) | |
| 224 | + } | |
| 225 | + }) | |
| 226 | +} |
crates/im-web/src/pages/admin/settings.rsadded+348 -0
| @@ -0,0 +1,348 @@ | ||
| 1 | +//! `/admin/settings`: the policy values that an administrator can change without a restart. | |
| 2 | +//! | |
| 3 | +//! Each value comes from one of three places, and the page shows which: a value saved here (`UI`), the | |
| 4 | +//! configuration file (`file`), or the built-in default. A saved value is a `policy.<key>` setting; it wins | |
| 5 | +//! over the file. Reset removes the saved value, so the file value applies again. Every value is checked | |
| 6 | +//! with the same rules as the file before anything is written, so a bad form changes nothing. | |
| 7 | +//! | |
| 8 | +//! The file-only settings (base address, listen address, database, data directory, trusted proxies) are shown | |
| 9 | +//! read-only: they are used when the server starts, so changing them here would do nothing until a restart. | |
| 10 | + | |
| 11 | +use im_core::config::{POLICY_KEYS, PolicyConfig}; | |
| 12 | +use im_core::model::AuditAction; | |
| 13 | +use serde::Deserialize; | |
| 14 | +use serde_json::json; | |
| 15 | +use topcoat::Result; | |
| 16 | +use topcoat::context::{Cx, app_context}; | |
| 17 | +use topcoat::router::content::Form; | |
| 18 | +use topcoat::router::error::{SeeOther, not_found}; | |
| 19 | +use topcoat::router::{page, route}; | |
| 20 | +use topcoat::view::{View, component, view}; | |
| 21 | + | |
| 22 | +use crate::audit::{Actor, record}; | |
| 23 | +use crate::auth::{require_admin, require_admin_csrf}; | |
| 24 | +use crate::boot::effective_policy; | |
| 25 | +use crate::i18n::Lang; | |
| 26 | +use crate::i18n::admin::{A, text}; | |
| 27 | +use crate::pages::admin::{ | |
| 28 | + FlashQuery, Tab, changed, done, error_text, flash_messages, frame_info, notice_text, refused, | |
| 29 | + tabs, | |
| 30 | +}; | |
| 31 | +use crate::state::AppState; | |
| 32 | +use crate::views::{ViewerInfo, shell}; | |
| 33 | + | |
| 34 | +/// The form of the settings: one text field per policy key, and the CSRF token. | |
| 35 | +#[derive(Deserialize, Default)] | |
| 36 | +struct SettingsForm { | |
| 37 | + #[serde(default)] | |
| 38 | + csrf: String, | |
| 39 | + #[serde(default)] | |
| 40 | + require_2fa_for_admins: String, | |
| 41 | + #[serde(default)] | |
| 42 | + max_sessions: String, | |
| 43 | + #[serde(default)] | |
| 44 | + session_max_days: String, | |
| 45 | + #[serde(default)] | |
| 46 | + invite_days: String, | |
| 47 | + #[serde(default)] | |
| 48 | + reset_minutes: String, | |
| 49 | + #[serde(default)] | |
| 50 | + email_change_hours: String, | |
| 51 | +} | |
| 52 | + | |
| 53 | +impl SettingsForm { | |
| 54 | + /// Each key with the value typed for it, in the order of `POLICY_KEYS`. | |
| 55 | + fn values(&self) -> [(&'static str, &str); 6] { | |
| 56 | + [ | |
| 57 | + ("require_2fa_for_admins", &self.require_2fa_for_admins), | |
| 58 | + ("max_sessions", &self.max_sessions), | |
| 59 | + ("session_max_days", &self.session_max_days), | |
| 60 | + ("invite_days", &self.invite_days), | |
| 61 | + ("reset_minutes", &self.reset_minutes), | |
| 62 | + ("email_change_hours", &self.email_change_hours), | |
| 63 | + ] | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +/// The form of a reset: the key to reset, and the CSRF token. | |
| 68 | +#[derive(Deserialize, Default)] | |
| 69 | +struct ResetForm { | |
| 70 | + #[serde(default)] | |
| 71 | + csrf: String, | |
| 72 | + #[serde(default)] | |
| 73 | + key: String, | |
| 74 | +} | |
| 75 | + | |
| 76 | +/// The value of one policy key as text, the way the form shows and accepts it. | |
| 77 | +fn value_of(policy: &PolicyConfig, key: &str) -> String { | |
| 78 | + match key { | |
| 79 | + "require_2fa_for_admins" => policy.require_2fa_for_admins.to_string(), | |
| 80 | + "max_sessions" => policy.max_sessions.to_string(), | |
| 81 | + "session_max_days" => policy.session_max_days.to_string(), | |
| 82 | + "invite_days" => policy.invite_days.to_string(), | |
| 83 | + "reset_minutes" => policy.reset_minutes.to_string(), | |
| 84 | + "email_change_hours" => policy.email_change_hours.to_string(), | |
| 85 | + _ => String::new(), | |
| 86 | + } | |
| 87 | +} | |
| 88 | + | |
| 89 | +/// The labels and hints of a policy key. | |
| 90 | +fn labels(key: &str) -> (A, A) { | |
| 91 | + match key { | |
| 92 | + "require_2fa_for_admins" => (A::SettingLabelRequire2fa, A::SettingHintRequire2fa), | |
| 93 | + "max_sessions" => (A::SettingLabelMaxSessions, A::SettingHintMaxSessions), | |
| 94 | + "session_max_days" => (A::SettingLabelSessionDays, A::SettingHintSessionDays), | |
| 95 | + "invite_days" => (A::SettingLabelInviteDays, A::SettingHintInviteDays), | |
| 96 | + "reset_minutes" => (A::SettingLabelResetMinutes, A::SettingHintResetMinutes), | |
| 97 | + _ => (A::SettingLabelEmailHours, A::SettingHintEmailHours), | |
| 98 | + } | |
| 99 | +} | |
| 100 | + | |
| 101 | +/// One row of the settings table: the key, its value now, and where the value comes from. | |
| 102 | +struct SettingRow { | |
| 103 | + key: &'static str, | |
| 104 | + value: String, | |
| 105 | + source: Source, | |
| 106 | +} | |
| 107 | + | |
| 108 | +/// Where a policy value comes from. | |
| 109 | +#[derive(Clone, Copy, PartialEq, Eq)] | |
| 110 | +enum Source { | |
| 111 | + Ui, | |
| 112 | + File, | |
| 113 | + Default, | |
| 114 | +} | |
| 115 | + | |
| 116 | +/// `GET /admin/settings`. | |
| 117 | +#[page("/admin/settings")] | |
| 118 | +async fn settings_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> { | |
| 119 | + let viewer = require_admin(cx).await?; | |
| 120 | + let state = app_context::<AppState>(cx); | |
| 121 | + let (lang, info) = frame_info(cx, &viewer); | |
| 122 | + let policy = state.policy(); | |
| 123 | + let saved: Vec<String> = state | |
| 124 | + .store | |
| 125 | + .settings_with_prefix("policy.") | |
| 126 | + .await? | |
| 127 | + .into_iter() | |
| 128 | + .map(|(key, _)| key.trim_start_matches("policy.").to_owned()) | |
| 129 | + .collect(); | |
| 130 | + let rows: Vec<SettingRow> = POLICY_KEYS | |
| 131 | + .iter() | |
| 132 | + .map(|key| SettingRow { | |
| 133 | + key, | |
| 134 | + value: value_of(&policy, key), | |
| 135 | + source: if saved.iter().any(|name| name == key) { | |
| 136 | + Source::Ui | |
| 137 | + } else if state.config.explicit_policy.iter().any(|name| name == key) { | |
| 138 | + Source::File | |
| 139 | + } else { | |
| 140 | + Source::Default | |
| 141 | + }, | |
| 142 | + }) | |
| 143 | + .collect(); | |
| 144 | + let file = FileValues { | |
| 145 | + base_url: state.config.base_url.clone(), | |
| 146 | + listen: state.config.listen.to_string(), | |
| 147 | + database: state.config.database.display().to_string(), | |
| 148 | + data_dir: state.config.data_dir.display().to_string(), | |
| 149 | + trusted_proxies: state | |
| 150 | + .config | |
| 151 | + .trusted_proxies | |
| 152 | + .iter() | |
| 153 | + .map(ToString::to_string) | |
| 154 | + .collect::<Vec<_>>() | |
| 155 | + .join(", "), | |
| 156 | + }; | |
| 157 | + Ok(settings_view( | |
| 158 | + cx, | |
| 159 | + lang, | |
| 160 | + info, | |
| 161 | + viewer.session.csrf_token.clone(), | |
| 162 | + rows, | |
| 163 | + file, | |
| 164 | + notice_text(lang, &query.notice).map(str::to_owned), | |
| 165 | + error_text(lang, &query.error).map(str::to_owned), | |
| 166 | + )) | |
| 167 | +} | |
| 168 | + | |
| 169 | +/// `POST /admin/settings`: saves the values that changed. Every value is checked first; if one is wrong, | |
| 170 | +/// nothing is saved. | |
| 171 | +#[route(POST "/admin/settings")] | |
| 172 | +async fn save_settings(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<SeeOther> { | |
| 173 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 174 | + let state = app_context::<AppState>(cx); | |
| 175 | + let current = state.policy(); | |
| 176 | + let mut next = current.clone(); | |
| 177 | + let mut changed_keys: Vec<(&'static str, String)> = Vec::new(); | |
| 178 | + for (key, typed) in form.values() { | |
| 179 | + let typed = typed.trim(); | |
| 180 | + if typed == value_of(¤t, key) { | |
| 181 | + continue; | |
| 182 | + } | |
| 183 | + next = match next.set(key, typed) { | |
| 184 | + Ok(policy) => policy, | |
| 185 | + Err(_) => return Ok(refused("/admin/settings", "settings")), | |
| 186 | + }; | |
| 187 | + changed_keys.push((key, typed.to_owned())); | |
| 188 | + } | |
| 189 | + if changed_keys.is_empty() { | |
| 190 | + return Ok(done("/admin/settings", "settings-saved")); | |
| 191 | + } | |
| 192 | + for (key, value) in &changed_keys { | |
| 193 | + state | |
| 194 | + .store | |
| 195 | + .set_setting(&format!("policy.{key}"), value) | |
| 196 | + .await?; | |
| 197 | + } | |
| 198 | + state.set_policy(next); | |
| 199 | + let names: Vec<&str> = changed_keys.iter().map(|(key, _)| *key).collect(); | |
| 200 | + record( | |
| 201 | + cx, | |
| 202 | + Actor::User(&viewer.user.id), | |
| 203 | + AuditAction::SettingsChanged, | |
| 204 | + None, | |
| 205 | + json!({ "keys": names }), | |
| 206 | + ) | |
| 207 | + .await; | |
| 208 | + changed(&state.live); | |
| 209 | + Ok(done("/admin/settings", "settings-saved")) | |
| 210 | +} | |
| 211 | + | |
| 212 | +/// `POST /admin/settings/reset`: removes the saved value of one key, so the file value (or the default) | |
| 213 | +/// applies again. | |
| 214 | +#[route(POST "/admin/settings/reset")] | |
| 215 | +async fn reset_setting(cx: &Cx, Form(form): Form<ResetForm>) -> Result<SeeOther> { | |
| 216 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | |
| 217 | + let Some(key) = POLICY_KEYS.iter().find(|key| **key == form.key) else { | |
| 218 | + return Err(not_found().into()); | |
| 219 | + }; | |
| 220 | + let state = app_context::<AppState>(cx); | |
| 221 | + state.store.delete_setting(&format!("policy.{key}")).await?; | |
| 222 | + let policy = effective_policy(&state.config, &state.store).await?; | |
| 223 | + state.set_policy(policy); | |
| 224 | + record( | |
| 225 | + cx, | |
| 226 | + Actor::User(&viewer.user.id), | |
| 227 | + AuditAction::SettingsChanged, | |
| 228 | + None, | |
| 229 | + json!({ "reset": key }), | |
| 230 | + ) | |
| 231 | + .await; | |
| 232 | + changed(&state.live); | |
| 233 | + Ok(done("/admin/settings", "file-value")) | |
| 234 | +} | |
| 235 | + | |
| 236 | +/// The file-only settings as text. | |
| 237 | +struct FileValues { | |
| 238 | + base_url: String, | |
| 239 | + listen: String, | |
| 240 | + database: String, | |
| 241 | + data_dir: String, | |
| 242 | + trusted_proxies: String, | |
| 243 | +} | |
| 244 | + | |
| 245 | +/// The text of a source. | |
| 246 | +fn source_text(lang: Lang, source: Source) -> &'static str { | |
| 247 | + match source { | |
| 248 | + Source::Ui => text(lang, A::SourceUi), | |
| 249 | + Source::File => text(lang, A::SourceFile), | |
| 250 | + Source::Default => text(lang, A::SourceDefault), | |
| 251 | + } | |
| 252 | +} | |
| 253 | + | |
| 254 | +/// The settings page: the editable table, the reset buttons, and the file-only values. | |
| 255 | +#[allow(clippy::too_many_arguments)] | |
| 256 | +fn settings_view( | |
| 257 | + cx: &Cx, | |
| 258 | + lang: Lang, | |
| 259 | + info: ViewerInfo, | |
| 260 | + csrf: String, | |
| 261 | + rows: Vec<SettingRow>, | |
| 262 | + file: FileValues, | |
| 263 | + success: Option<String>, | |
| 264 | + problem: Option<String>, | |
| 265 | +) -> impl View { | |
| 266 | + let resets: Vec<(&'static str, &'static str)> = rows | |
| 267 | + .iter() | |
| 268 | + .filter(|row| row.source == Source::Ui) | |
| 269 | + .map(|row| (row.key, text(lang, labels(row.key).0))) | |
| 270 | + .collect(); | |
| 271 | + view! { cx => | |
| 272 | + shell(title: text(lang, A::SettingsTitle), lang: lang, viewer: Some(info), | |
| 273 | + tabs(lang: lang, current: Tab::Settings) | |
| 274 | + <section class="stack"> | |
| 275 | + <h1>(text(lang, A::SettingsTitle))</h1> | |
| 276 | + <p class="muted">(text(lang, A::SettingsIntro))</p> | |
| 277 | + flash_messages(success: success, problem: problem) | |
| 278 | + <form method="post" action="/admin/settings" class="stack"> | |
| 279 | + <input type="hidden" name="csrf" value=(csrf.clone())> | |
| 280 | + <table class="settings"> | |
| 281 | + <thead><tr> | |
| 282 | + <th>(text(lang, A::SettingName))</th> | |
| 283 | + <th>(text(lang, A::SettingValue))</th> | |
| 284 | + <th>(text(lang, A::SettingSource))</th> | |
| 285 | + </tr></thead> | |
| 286 | + <tbody> | |
| 287 | + for row in rows { | |
| 288 | + setting_row(lang: lang, row: row) | |
| 289 | + } | |
| 290 | + </tbody> | |
| 291 | + </table> | |
| 292 | + <button type="submit" class="button primary">(text(lang, A::Save))</button> | |
| 293 | + </form> | |
| 294 | + if !resets.is_empty() { | |
| 295 | + <h2>(text(lang, A::UseFileValue))</h2> | |
| 296 | + for (key, name) in resets { | |
| 297 | + reset_form(lang: lang, csrf: csrf.clone(), key: key, name: name) | |
| 298 | + } | |
| 299 | + } | |
| 300 | + <h2>(text(lang, A::FileOnlyTitle))</h2> | |
| 301 | + <p class="muted">(text(lang, A::FileOnlyIntro))</p> | |
| 302 | + <dl class="facts"> | |
| 303 | + <dt>(text(lang, A::FileBaseUrl))</dt><dd>(file.base_url.clone())</dd> | |
| 304 | + <dt>(text(lang, A::FileListen))</dt><dd>(file.listen.clone())</dd> | |
| 305 | + <dt>(text(lang, A::FileDatabase))</dt><dd>(file.database.clone())</dd> | |
| 306 | + <dt>(text(lang, A::FileDataDir))</dt><dd>(file.data_dir.clone())</dd> | |
| 307 | + <dt>(text(lang, A::FileTrustedProxies))</dt><dd>(file.trusted_proxies.clone())</dd> | |
| 308 | + </dl> | |
| 309 | + </section> | |
| 310 | + ) | |
| 311 | + } | |
| 312 | +} | |
| 313 | + | |
| 314 | +/// One policy key: its label, its input with the value now, its hint, and its source. | |
| 315 | +#[component] | |
| 316 | +async fn setting_row(lang: Lang, row: SettingRow) -> Result<impl View> { | |
| 317 | + let (label, hint) = labels(row.key); | |
| 318 | + let source = source_text(lang, row.source); | |
| 319 | + Ok(view! { | |
| 320 | + <tr> | |
| 321 | + <td> | |
| 322 | + <label for=(row.key)>(text(lang, label))</label> | |
| 323 | + <div class="hint">(text(lang, hint))</div> | |
| 324 | + </td> | |
| 325 | + <td><input id=(row.key) name=(row.key) type="text" autocomplete="off" value=(row.value.clone())></td> | |
| 326 | + <td class="muted">(source)</td> | |
| 327 | + </tr> | |
| 328 | + }) | |
| 329 | +} | |
| 330 | + | |
| 331 | +/// A form that removes the saved value of one key. It sits outside the settings form, because forms do | |
| 332 | +/// not nest. | |
| 333 | +#[component] | |
| 334 | +async fn reset_form( | |
| 335 | + lang: Lang, | |
| 336 | + csrf: String, | |
| 337 | + key: &'static str, | |
| 338 | + name: &'static str, | |
| 339 | +) -> Result<impl View> { | |
| 340 | + Ok(view! { | |
| 341 | + <form method="post" action="/admin/settings/reset" class="inline-form"> | |
| 342 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 343 | + <input type="hidden" name="key" value=(key)> | |
| 344 | + <span class="muted">(name)</span> | |
| 345 | + <button type="submit" class="button ghost">(text(lang, A::UseFileValue))</button> | |
| 346 | + </form> | |
| 347 | + }) | |
| 348 | +} |
crates/im-web/src/pages/admin/tests.rsadded+211 -0
| @@ -0,0 +1,211 @@ | ||
| 1 | +//! Router tests of the administrator area: a member gets the 404, a form without the CSRF token is refused | |
| 2 | +//! before anything changes, an administrator cannot disable themselves, and a hostile name is escaped on | |
| 3 | +//! the users page. | |
| 4 | + | |
| 5 | +use std::time::Duration; | |
| 6 | + | |
| 7 | +use http::header::{CONTENT_TYPE, COOKIE, LOCATION}; | |
| 8 | +use im_core::password::hash_password; | |
| 9 | +use im_core::store::sessions::{NewSession, SESSION_IDLE}; | |
| 10 | +use im_core::token::{generate_token, hash_token}; | |
| 11 | +use topcoat::router::{Body, to_bytes}; | |
| 12 | + | |
| 13 | +use crate::boot::{router, test_state}; | |
| 14 | +use crate::state::AppState; | |
| 15 | + | |
| 16 | +/// The cookie name the browser sends: the `__Host-` prefix is added by the jar. | |
| 17 | +const COOKIE_NAME: &str = "__Host-im_session"; | |
| 18 | + | |
| 19 | +/// A status, the `Location` header if any, and the body of a response. | |
| 20 | +struct Reply { | |
| 21 | + status: u16, | |
| 22 | + location: Option<String>, | |
| 23 | + body: String, | |
| 24 | +} | |
| 25 | + | |
| 26 | +/// Sends a request through the router and collects the reply. | |
| 27 | +async fn send(state: AppState, request: http::request::Builder, body: Body) -> Reply { | |
| 28 | + let request = request.body(body).expect("request"); | |
| 29 | + let response = router(state).handle(request).await; | |
| 30 | + let status = response.status().as_u16(); | |
| 31 | + let location = response | |
| 32 | + .headers() | |
| 33 | + .get(LOCATION) | |
| 34 | + .and_then(|value| value.to_str().ok()) | |
| 35 | + .map(str::to_owned); | |
| 36 | + let bytes = to_bytes(response.into_body(), 1024 * 1024) | |
| 37 | + .await | |
| 38 | + .expect("body"); | |
| 39 | + Reply { | |
| 40 | + status, | |
| 41 | + location, | |
| 42 | + body: String::from_utf8_lossy(&bytes).into_owned(), | |
| 43 | + } | |
| 44 | +} | |
| 45 | + | |
| 46 | +/// A GET with the session cookie. | |
| 47 | +async fn get(state: AppState, path: &str, cookie: &str) -> Reply { | |
| 48 | + let request = http::Request::get(path).header(COOKIE, format!("{COOKIE_NAME}={cookie}")); | |
| 49 | + send(state, request, Body::empty()).await | |
| 50 | +} | |
| 51 | + | |
| 52 | +/// A form POST with the session cookie. | |
| 53 | +async fn post(state: AppState, path: &str, cookie: &str, form: &str) -> Reply { | |
| 54 | + let request = http::Request::post(path) | |
| 55 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | |
| 56 | + .header(COOKIE, format!("{COOKIE_NAME}={cookie}")); | |
| 57 | + send(state, request, Body::from(form.to_owned())).await | |
| 58 | +} | |
| 59 | + | |
| 60 | +/// Creates a session for a user with a known CSRF token. Returns the cookie value and the CSRF token. | |
| 61 | +async fn session_for(state: &AppState, user_id: &str) -> (String, String) { | |
| 62 | + let token = generate_token(); | |
| 63 | + let csrf = generate_token(); | |
| 64 | + state | |
| 65 | + .store | |
| 66 | + .create_session( | |
| 67 | + &NewSession { | |
| 68 | + user_id, | |
| 69 | + token_hash: &hash_token(&token), | |
| 70 | + csrf_token: &csrf, | |
| 71 | + amr: "pwd", | |
| 72 | + ip: None, | |
| 73 | + user_agent: None, | |
| 74 | + idle: SESSION_IDLE, | |
| 75 | + max_age: Duration::from_secs(3600), | |
| 76 | + }, | |
| 77 | + 10, | |
| 78 | + ) | |
| 79 | + .await | |
| 80 | + .expect("session"); | |
| 81 | + (token, csrf) | |
| 82 | +} | |
| 83 | + | |
| 84 | +/// A state where administrators need no two-factor sign-in, so a test session reaches the admin pages. | |
| 85 | +async fn state_without_admin_two_factor() -> (tempfile::TempDir, AppState) { | |
| 86 | + let (dir, state) = test_state().await; | |
| 87 | + let mut policy = state.policy(); | |
| 88 | + policy.require_2fa_for_admins = false; | |
| 89 | + state.set_policy(policy); | |
| 90 | + (dir, state) | |
| 91 | +} | |
| 92 | + | |
| 93 | +#[tokio::test] | |
| 94 | +async fn a_member_gets_not_found_on_the_admin_users_page() { | |
| 95 | + let (_dir, state) = state_without_admin_two_factor().await; | |
| 96 | + let hash = hash_password("the current password").expect("hash"); | |
| 97 | + let member = state | |
| 98 | + .store | |
| 99 | + .create_user("member@example.com", "Mem", &hash, false) | |
| 100 | + .await | |
| 101 | + .expect("member"); | |
| 102 | + let (cookie, _) = session_for(&state, &member.id).await; | |
| 103 | + let reply = get(state, "/admin/users", &cookie).await; | |
| 104 | + assert_eq!(reply.status, 404); | |
| 105 | +} | |
| 106 | + | |
| 107 | +#[tokio::test] | |
| 108 | +async fn an_admin_form_without_the_csrf_token_is_forbidden_and_changes_nothing() { | |
| 109 | + let (_dir, state) = state_without_admin_two_factor().await; | |
| 110 | + let hash = hash_password("the current password").expect("hash"); | |
| 111 | + let admin = state | |
| 112 | + .store | |
| 113 | + .create_user("admin@example.com", "Ada", &hash, true) | |
| 114 | + .await | |
| 115 | + .expect("admin"); | |
| 116 | + let other = state | |
| 117 | + .store | |
| 118 | + .create_user("other@example.com", "Oto", &hash, false) | |
| 119 | + .await | |
| 120 | + .expect("other"); | |
| 121 | + let (cookie, _) = session_for(&state, &admin.id).await; | |
| 122 | + let reply = post( | |
| 123 | + state.clone(), | |
| 124 | + &format!("/admin/users/{}/disable", other.id), | |
| 125 | + &cookie, | |
| 126 | + "csrf=not-the-token&on=", | |
| 127 | + ) | |
| 128 | + .await; | |
| 129 | + assert_eq!(reply.status, 403); | |
| 130 | + let still = state | |
| 131 | + .store | |
| 132 | + .user_by_id(&other.id) | |
| 133 | + .await | |
| 134 | + .expect("query") | |
| 135 | + .expect("user"); | |
| 136 | + assert!(still.disabled_at.is_none()); | |
| 137 | +} | |
| 138 | + | |
| 139 | +#[tokio::test] | |
| 140 | +async fn an_administrator_cannot_disable_themselves() { | |
| 141 | + let (_dir, state) = state_without_admin_two_factor().await; | |
| 142 | + let hash = hash_password("the current password").expect("hash"); | |
| 143 | + let admin = state | |
| 144 | + .store | |
| 145 | + .create_user("admin@example.com", "Ada", &hash, true) | |
| 146 | + .await | |
| 147 | + .expect("admin"); | |
| 148 | + let other = state | |
| 149 | + .store | |
| 150 | + .create_user("other@example.com", "Oto", &hash, true) | |
| 151 | + .await | |
| 152 | + .expect("other"); | |
| 153 | + let (cookie, csrf) = session_for(&state, &admin.id).await; | |
| 154 | + let reply = post( | |
| 155 | + state.clone(), | |
| 156 | + &format!("/admin/users/{}/disable", admin.id), | |
| 157 | + &cookie, | |
| 158 | + &format!("csrf={csrf}&on="), | |
| 159 | + ) | |
| 160 | + .await; | |
| 161 | + assert_eq!(reply.status, 303); | |
| 162 | + assert!( | |
| 163 | + reply | |
| 164 | + .location | |
| 165 | + .as_deref() | |
| 166 | + .is_some_and(|location| location.contains("error=self-disable")), | |
| 167 | + "refused with the self-disable code, got {:?}", | |
| 168 | + reply.location | |
| 169 | + ); | |
| 170 | + let still = state | |
| 171 | + .store | |
| 172 | + .user_by_id(&admin.id) | |
| 173 | + .await | |
| 174 | + .expect("query") | |
| 175 | + .expect("user"); | |
| 176 | + assert!(still.disabled_at.is_none()); | |
| 177 | + assert!( | |
| 178 | + state | |
| 179 | + .store | |
| 180 | + .user_by_id(&other.id) | |
| 181 | + .await | |
| 182 | + .expect("query") | |
| 183 | + .is_some() | |
| 184 | + ); | |
| 185 | +} | |
| 186 | + | |
| 187 | +#[tokio::test] | |
| 188 | +async fn a_hostile_user_name_is_escaped_on_the_admin_users_page() { | |
| 189 | + let (_dir, state) = state_without_admin_two_factor().await; | |
| 190 | + let hash = hash_password("the current password").expect("hash"); | |
| 191 | + let admin = state | |
| 192 | + .store | |
| 193 | + .create_user("admin@example.com", "Ada", &hash, true) | |
| 194 | + .await | |
| 195 | + .expect("admin"); | |
| 196 | + state | |
| 197 | + .store | |
| 198 | + .create_user( | |
| 199 | + "mallory@example.com", | |
| 200 | + "<img src=x onerror=alert(1)>", | |
| 201 | + &hash, | |
| 202 | + false, | |
| 203 | + ) | |
| 204 | + .await | |
| 205 | + .expect("hostile user"); | |
| 206 | + let (cookie, _) = session_for(&state, &admin.id).await; | |
| 207 | + let reply = get(state, "/admin/users", &cookie).await; | |
| 208 | + assert_eq!(reply.status, 200); | |
| 209 | + assert!(!reply.body.contains("<img src=x onerror")); | |
| 210 | + assert!(reply.body.contains("<img src=x onerror=alert(1)>")); | |
| 211 | +} |
crates/im-web/src/pages/admin/users.rsadded+511 -0
| @@ -0,0 +1,511 @@ | ||
| 1 | +//! `/admin/users`: the list of accounts with search and keyset paging, and each account's page with the | |
| 2 | +//! administrator actions. | |
| 3 | +//! | |
| 4 | +//! The actions are disable and enable, make and remove administrator, reset two-factor sign-in, end every | |
| 5 | +//! session, and delete. Each POST checks the admin guard, then its CSRF token, then the rules of the | |
| 6 | +//! account: an administrator never acts on their own account here, and the last enabled administrator | |
| 7 | +//! cannot be disabled, demoted or deleted (the store refuses it in the same statement that would do it). | |
| 8 | +//! An action that changes what a person sees of their account bumps that account's live topic, so their | |
| 9 | +//! open pages refresh and a disabled or deleted person is signed out at once. | |
| 10 | + | |
| 11 | +use im_core::Error as CoreError; | |
| 12 | +use im_core::model::{AuditAction, User}; | |
| 13 | +use im_core::names::normalize_email; | |
| 14 | +use im_core::store::admin::AdminChange; | |
| 15 | +use im_core::store::backchannel::EndReason; | |
| 16 | +use serde::Deserialize; | |
| 17 | +use serde_json::json; | |
| 18 | +use topcoat::Result; | |
| 19 | +use topcoat::context::{Cx, app_context}; | |
| 20 | +use topcoat::router::content::Form; | |
| 21 | +use topcoat::router::error::{SeeOther, not_found}; | |
| 22 | +use topcoat::router::{page, route}; | |
| 23 | +use topcoat::view::{View, component, view}; | |
| 24 | + | |
| 25 | +use crate::audit::{Actor, record}; | |
| 26 | +use crate::auth::{Viewer, percent_encode, require_admin, require_admin_csrf}; | |
| 27 | +use crate::i18n::Lang; | |
| 28 | +use crate::i18n::admin::{A, text}; | |
| 29 | +use crate::live::Topic; | |
| 30 | +use crate::mail::{self, Notice}; | |
| 31 | +use crate::pages::admin::{ | |
| 32 | + FlashQuery, PAGE_SIZE, Tab, action_button, changed, done, error_text, flash_messages, | |
| 33 | + frame_info, notice_text, refused, tabs, | |
| 34 | +}; | |
| 35 | +use crate::pages::path_param; | |
| 36 | +use crate::state::AppState; | |
| 37 | +use crate::views::{ViewerInfo, page_lang, shell}; | |
| 38 | + | |
| 39 | +/// The query of the account list: the search, the cursor of the next page, and the flash codes. | |
| 40 | +#[derive(Deserialize, Default)] | |
| 41 | +struct UsersQuery { | |
| 42 | + #[serde(default)] | |
| 43 | + q: String, | |
| 44 | + /// `created_at|id` of the last account of the previous page. | |
| 45 | + #[serde(default)] | |
| 46 | + after: String, | |
| 47 | + #[serde(default)] | |
| 48 | + notice: String, | |
| 49 | + #[serde(default)] | |
| 50 | + error: String, | |
| 51 | +} | |
| 52 | + | |
| 53 | +/// The form of every account action. Only the fields the action needs are read. | |
| 54 | +#[derive(Deserialize, Default)] | |
| 55 | +struct ActionForm { | |
| 56 | + #[serde(default)] | |
| 57 | + csrf: String, | |
| 58 | + /// `1` makes the account an administrator, `0` removes the flag. | |
| 59 | + #[serde(default)] | |
| 60 | + on: String, | |
| 61 | + /// The email address typed to confirm a deletion. | |
| 62 | + #[serde(default)] | |
| 63 | + confirm: String, | |
| 64 | +} | |
| 65 | + | |
| 66 | +/// One row of the account list, with the text already resolved. | |
| 67 | +struct UserRow { | |
| 68 | + name: String, | |
| 69 | + email: String, | |
| 70 | + status: &'static str, | |
| 71 | + admin: bool, | |
| 72 | + created: String, | |
| 73 | + href: String, | |
| 74 | +} | |
| 75 | + | |
| 76 | +/// The account list. Newest first; `q` filters by part of the address or the name. | |
| 77 | +#[page("/admin/users")] | |
| 78 | +async fn users_page(cx: &Cx, Form(query): Form<UsersQuery>) -> Result<impl View> { | |
| 79 | + let viewer = require_admin(cx).await?; | |
| 80 | + let state = app_context::<AppState>(cx); | |
| 81 | + let (lang, info) = frame_info(cx, &viewer); | |
| 82 | + let search: String = query.q.trim().chars().take(100).collect(); | |
| 83 | + let cursor = query | |
| 84 | + .after | |
| 85 | + .split_once('|') | |
| 86 | + .filter(|(at, id)| !at.is_empty() && !id.is_empty()); | |
| 87 | + let mut users = state | |
| 88 | + .store | |
| 89 | + .list_users( | |
| 90 | + (!search.is_empty()).then_some(search.as_str()), | |
| 91 | + cursor, | |
| 92 | + PAGE_SIZE + 1, | |
| 93 | + ) | |
| 94 | + .await?; | |
| 95 | + let more = users.len() > PAGE_SIZE as usize; | |
| 96 | + users.truncate(PAGE_SIZE as usize); | |
| 97 | + let next = more | |
| 98 | + .then(|| users.last().map(|u| format!("{}|{}", u.created_at, u.id))) | |
| 99 | + .flatten() | |
| 100 | + .map(|cursor| { | |
| 101 | + format!( | |
| 102 | + "/admin/users?q={}&after={}", | |
| 103 | + percent_encode(&search), | |
| 104 | + percent_encode(&cursor) | |
| 105 | + ) | |
| 106 | + }); | |
| 107 | + let rows: Vec<UserRow> = users.iter().map(|user| row_of(lang, user)).collect(); | |
| 108 | + Ok(users_view( | |
| 109 | + cx, | |
| 110 | + lang, | |
| 111 | + info, | |
| 112 | + search, | |
| 113 | + rows, | |
| 114 | + next, | |
| 115 | + notice_text(lang, &query.notice).map(str::to_owned), | |
| 116 | + error_text(lang, &query.error).map(str::to_owned), | |
| 117 | + )) | |
| 118 | +} | |
| 119 | + | |
| 120 | +/// The list row of an account. | |
| 121 | +fn row_of(lang: Lang, user: &User) -> UserRow { | |
| 122 | + UserRow { | |
| 123 | + name: user.name.clone(), | |
| 124 | + email: user.email.clone(), | |
| 125 | + status: if user.is_disabled() { | |
| 126 | + text(lang, A::Disabled) | |
| 127 | + } else { | |
| 128 | + text(lang, A::Active) | |
| 129 | + }, | |
| 130 | + admin: user.is_admin, | |
| 131 | + created: user.created_at.clone(), | |
| 132 | + href: format!("/admin/users/{}", user.id), | |
| 133 | + } | |
| 134 | +} | |
| 135 | + | |
| 136 | +/// The account list page. | |
| 137 | +#[allow(clippy::too_many_arguments)] | |
| 138 | +fn users_view( | |
| 139 | + cx: &Cx, | |
| 140 | + lang: Lang, | |
| 141 | + info: ViewerInfo, | |
| 142 | + search: String, | |
| 143 | + rows: Vec<UserRow>, | |
| 144 | + next: Option<String>, | |
| 145 | + success: Option<String>, | |
| 146 | + problem: Option<String>, | |
| 147 | +) -> impl View { | |
| 148 | + view! { cx => | |
| 149 | + shell(title: text(lang, A::UsersTitle), lang: lang, viewer: Some(info), | |
| 150 | + tabs(lang: lang, current: Tab::Users) | |
| 151 | + <section class="stack" data-live="/admin/events"> | |
| 152 | + <h1>(text(lang, A::UsersTitle))</h1> | |
| 153 | + <p class="muted">(text(lang, A::UsersIntro))</p> | |
| 154 | + flash_messages(success: success, problem: problem) | |
| 155 | + <form method="get" action="/admin/users" class="row"> | |
| 156 | + <label class="field"> | |
| 157 | + <span class="field-label">(text(lang, A::SearchLabel))</span> | |
| 158 | + <input name="q" type="search" value=(search) spellcheck="false"> | |
| 159 | + </label> | |
| 160 | + <button type="submit" class="button ghost">(text(lang, A::Search))</button> | |
| 161 | + </form> | |
| 162 | + if rows.is_empty() { | |
| 163 | + <p class="muted">(text(lang, A::NoUsers))</p> | |
| 164 | + } else { | |
| 165 | + <table class="table"> | |
| 166 | + <thead><tr> | |
| 167 | + <th>(text(lang, A::Name))</th> | |
| 168 | + <th>(text(lang, A::Email))</th> | |
| 169 | + <th>(text(lang, A::Status))</th> | |
| 170 | + <th>(text(lang, A::Created))</th> | |
| 171 | + <th><span class="visually-hidden">(text(lang, A::Open))</span></th> | |
| 172 | + </tr></thead> | |
| 173 | + <tbody> | |
| 174 | + for row in rows { | |
| 175 | + user_row(lang: lang, row: row) | |
| 176 | + } | |
| 177 | + </tbody> | |
| 178 | + </table> | |
| 179 | + } | |
| 180 | + if let Some(href) = next { | |
| 181 | + <p><a class="button ghost" href=(href)>(text(lang, A::NextPage))</a></p> | |
| 182 | + } | |
| 183 | + </section> | |
| 184 | + ) | |
| 185 | + } | |
| 186 | +} | |
| 187 | + | |
| 188 | +/// One account in the list. | |
| 189 | +#[component] | |
| 190 | +async fn user_row(lang: Lang, row: UserRow) -> Result<impl View> { | |
| 191 | + Ok(view! { | |
| 192 | + <tr> | |
| 193 | + <td>(row.name.clone())</td> | |
| 194 | + <td>(row.email.clone())</td> | |
| 195 | + <td> | |
| 196 | + <span class="badge">(row.status)</span> | |
| 197 | + if row.admin { | |
| 198 | + <span class="badge accent">(text(lang, A::Administrator))</span> | |
| 199 | + } | |
| 200 | + </td> | |
| 201 | + <td>(row.created.clone())</td> | |
| 202 | + <td><a href=(row.href.clone())>(text(lang, A::Open))</a></td> | |
| 203 | + </tr> | |
| 204 | + }) | |
| 205 | +} | |
| 206 | + | |
| 207 | +/// One account's page: its facts and the actions on it. | |
| 208 | +#[page("/admin/users/{id}")] | |
| 209 | +async fn user_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> { | |
| 210 | + let viewer = require_admin(cx).await?; | |
| 211 | + let state = app_context::<AppState>(cx); | |
| 212 | + let (lang, info) = frame_info(cx, &viewer); | |
| 213 | + let Some(id) = path_param(cx, "id") else { | |
| 214 | + return Err(not_found().into()); | |
| 215 | + }; | |
| 216 | + let Some(user) = state.store.user_by_id(&id).await? else { | |
| 217 | + return Err(not_found().into()); | |
| 218 | + }; | |
| 219 | + let sessions = state.store.list_sessions(&user.id).await?.len(); | |
| 220 | + let is_self = user.id == viewer.user.id; | |
| 221 | + Ok(user_view( | |
| 222 | + cx, | |
| 223 | + lang, | |
| 224 | + info, | |
| 225 | + viewer.session.csrf_token.clone(), | |
| 226 | + user, | |
| 227 | + sessions, | |
| 228 | + is_self, | |
| 229 | + notice_text(lang, &query.notice).map(str::to_owned), | |
| 230 | + error_text(lang, &query.error).map(str::to_owned), | |
| 231 | + )) | |
| 232 | +} | |
| 233 | + | |
| 234 | +/// The markup of one account's page. The actions are shown only for other accounts. | |
| 235 | +#[allow(clippy::too_many_arguments)] | |
| 236 | +fn user_view( | |
| 237 | + cx: &Cx, | |
| 238 | + lang: Lang, | |
| 239 | + info: ViewerInfo, | |
| 240 | + csrf: String, | |
| 241 | + user: User, | |
| 242 | + sessions: usize, | |
| 243 | + is_self: bool, | |
| 244 | + success: Option<String>, | |
| 245 | + problem: Option<String>, | |
| 246 | +) -> impl View { | |
| 247 | + let base = format!("/admin/users/{}", user.id); | |
| 248 | + let status = if user.is_disabled() { | |
| 249 | + text(lang, A::Disabled) | |
| 250 | + } else { | |
| 251 | + text(lang, A::Active) | |
| 252 | + }; | |
| 253 | + let two_factor = if user.totp_enabled() { | |
| 254 | + text(lang, A::TwoFactorOn) | |
| 255 | + } else { | |
| 256 | + text(lang, A::TwoFactorOff) | |
| 257 | + }; | |
| 258 | + let admin_flag = if user.is_admin { | |
| 259 | + text(lang, A::RemoveAdmin) | |
| 260 | + } else { | |
| 261 | + text(lang, A::MakeAdmin) | |
| 262 | + }; | |
| 263 | + let admin_on = if user.is_admin { "0" } else { "1" }; | |
| 264 | + let admin_text = if user.is_admin { | |
| 265 | + text(lang, A::Yes) | |
| 266 | + } else { | |
| 267 | + text(lang, A::No) | |
| 268 | + }; | |
| 269 | + view! { cx => | |
| 270 | + shell(title: text(lang, A::UserTitle), lang: lang, viewer: Some(info), | |
| 271 | + tabs(lang: lang, current: Tab::Users) | |
| 272 | + <section class="stack" data-live="/admin/events"> | |
| 273 | + <p><a href="/admin/users">(text(lang, A::NavUsers))</a></p> | |
| 274 | + <h1>(user.name.clone())</h1> | |
| 275 | + flash_messages(success: success, problem: problem) | |
| 276 | + <dl class="facts"> | |
| 277 | + <dt>(text(lang, A::Email))</dt><dd>(user.email.clone())</dd> | |
| 278 | + <dt>(text(lang, A::Status))</dt><dd>(status)</dd> | |
| 279 | + <dt>(text(lang, A::Administrator))</dt><dd>(admin_text)</dd> | |
| 280 | + <dt>(text(lang, A::Created))</dt><dd>(user.created_at.clone())</dd> | |
| 281 | + <dt>(text(lang, A::SessionsLabel))</dt><dd>(sessions.to_string())</dd> | |
| 282 | + <dt>(text(lang, A::TwoFactor))</dt><dd>(two_factor)</dd> | |
| 283 | + </dl> | |
| 284 | + if is_self { | |
| 285 | + <p class="notice">(text(lang, A::YouLabel))". "(text(lang, A::NoOwnAccountHere))</p> | |
| 286 | + } else { | |
| 287 | + <div class="stack"> | |
| 288 | + if user.is_disabled() { | |
| 289 | + action_button(action: format!("{base}/enable"), csrf: csrf.clone(), label: text(lang, A::EnableAccount), class: "button primary", on: "") | |
| 290 | + } else { | |
| 291 | + action_button(action: format!("{base}/disable"), csrf: csrf.clone(), label: text(lang, A::DisableAccount), class: "button danger", on: "") | |
| 292 | + } | |
| 293 | + action_button(action: format!("{base}/admin"), csrf: csrf.clone(), label: admin_flag, class: "button ghost", on: admin_on) | |
| 294 | + action_button(action: format!("{base}/reset-2fa"), csrf: csrf.clone(), label: text(lang, A::ResetTwoFactor), class: "button ghost", on: "") | |
| 295 | + action_button(action: format!("{base}/revoke-sessions"), csrf: csrf.clone(), label: text(lang, A::RevokeSessions), class: "button ghost", on: "") | |
| 296 | + <form method="post" action=(format!("{base}/delete")) class="stack"> | |
| 297 | + <input type="hidden" name="csrf" value=(csrf.clone())> | |
| 298 | + <p class="hint">(text(lang, A::DeleteWarning))</p> | |
| 299 | + <label class="field"> | |
| 300 | + <span class="field-label">(text(lang, A::ConfirmEmail))</span> | |
| 301 | + <input name="confirm" type="email" autocomplete="off" spellcheck="false"> | |
| 302 | + </label> | |
| 303 | + <button type="submit" class="button danger">(text(lang, A::DeleteAccount))</button> | |
| 304 | + </form> | |
| 305 | + </div> | |
| 306 | + } | |
| 307 | + </section> | |
| 308 | + ) | |
| 309 | + } | |
| 310 | +} | |
| 311 | + | |
| 312 | +/// Checks the CSRF token and loads the account named by the path. A member gets 404 before the token is | |
| 313 | +/// read; a wrong token gets 403; a missing account gets 404. | |
| 314 | +async fn target(cx: &Cx, csrf: &str) -> Result<(Viewer, User)> { | |
| 315 | + let viewer = require_admin_csrf(cx, csrf).await?; | |
| 316 | + let state = app_context::<AppState>(cx); | |
| 317 | + let Some(id) = path_param(cx, "id") else { | |
| 318 | + return Err(not_found().into()); | |
| 319 | + }; | |
| 320 | + let Some(user) = state.store.user_by_id(&id).await? else { | |
| 321 | + return Err(not_found().into()); | |
| 322 | + }; | |
| 323 | + Ok((viewer, user)) | |
| 324 | +} | |
| 325 | + | |
| 326 | +/// `POST /admin/users/{id}/disable`. Ends the account's sessions and queues the back-channel logouts. | |
| 327 | +#[route(POST "/admin/users/{id}/disable")] | |
| 328 | +async fn disable(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> { | |
| 329 | + let (viewer, user) = target(cx, &form.csrf).await?; | |
| 330 | + let base = format!("/admin/users/{}", user.id); | |
| 331 | + if user.id == viewer.user.id { | |
| 332 | + return Ok(refused(&base, "self-disable")); | |
| 333 | + } | |
| 334 | + if user.is_disabled() { | |
| 335 | + return Ok(done(&base, "disabled")); | |
| 336 | + } | |
| 337 | + let state = app_context::<AppState>(cx); | |
| 338 | + if state.store.disable_user(&user.id).await? { | |
| 339 | + state.live.bump(&Topic::Account(user.id.clone())); | |
| 340 | + changed(&state.live); | |
| 341 | + record( | |
| 342 | + cx, | |
| 343 | + Actor::User(&viewer.user.id), | |
| 344 | + AuditAction::UserDisabled, | |
| 345 | + Some(("user", &user.id)), | |
| 346 | + json!({}), | |
| 347 | + ) | |
| 348 | + .await; | |
| 349 | + return Ok(done(&base, "disabled")); | |
| 350 | + } | |
| 351 | + // The store refused: the account is the last enabled administrator. | |
| 352 | + Ok(refused(&base, "last-admin")) | |
| 353 | +} | |
| 354 | + | |
| 355 | +/// `POST /admin/users/{id}/enable`. | |
| 356 | +#[route(POST "/admin/users/{id}/enable")] | |
| 357 | +async fn enable(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> { | |
| 358 | + let (viewer, user) = target(cx, &form.csrf).await?; | |
| 359 | + let base = format!("/admin/users/{}", user.id); | |
| 360 | + let state = app_context::<AppState>(cx); | |
| 361 | + if state.store.enable_user(&user.id).await? { | |
| 362 | + changed(&state.live); | |
| 363 | + state.live.bump(&Topic::Account(user.id.clone())); | |
| 364 | + record( | |
| 365 | + cx, | |
| 366 | + Actor::User(&viewer.user.id), | |
| 367 | + AuditAction::UserEnabled, | |
| 368 | + Some(("user", &user.id)), | |
| 369 | + json!({}), | |
| 370 | + ) | |
| 371 | + .await; | |
| 372 | + } | |
| 373 | + Ok(done(&base, "enabled")) | |
| 374 | +} | |
| 375 | + | |
| 376 | +/// `POST /admin/users/{id}/admin`. `on=1` makes the account an administrator, `on=0` removes the flag. | |
| 377 | +#[route(POST "/admin/users/{id}/admin")] | |
| 378 | +async fn set_admin_flag(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> { | |
| 379 | + let (viewer, user) = target(cx, &form.csrf).await?; | |
| 380 | + let base = format!("/admin/users/{}", user.id); | |
| 381 | + if user.id == viewer.user.id { | |
| 382 | + return Ok(refused(&base, "self-admin")); | |
| 383 | + } | |
| 384 | + let make = form.on == "1"; | |
| 385 | + let state = app_context::<AppState>(cx); | |
| 386 | + let outcome = state.store.set_admin(&user.id, make).await?; | |
| 387 | + let code = if make { | |
| 388 | + "admin-granted" | |
| 389 | + } else { | |
| 390 | + "admin-removed" | |
| 391 | + }; | |
| 392 | + match outcome { | |
| 393 | + AdminChange::LastAdmin => Ok(refused(&base, "last-admin")), | |
| 394 | + AdminChange::Unchanged => Ok(done(&base, code)), | |
| 395 | + AdminChange::Changed => { | |
| 396 | + state.live.bump(&Topic::Account(user.id.clone())); | |
| 397 | + changed(&state.live); | |
| 398 | + let action = if make { | |
| 399 | + AuditAction::AdminGranted | |
| 400 | + } else { | |
| 401 | + AuditAction::AdminRemoved | |
| 402 | + }; | |
| 403 | + record( | |
| 404 | + cx, | |
| 405 | + Actor::User(&viewer.user.id), | |
| 406 | + action, | |
| 407 | + Some(("user", &user.id)), | |
| 408 | + json!({}), | |
| 409 | + ) | |
| 410 | + .await; | |
| 411 | + Ok(done(&base, code)) | |
| 412 | + } | |
| 413 | + } | |
| 414 | +} | |
| 415 | + | |
| 416 | +/// `POST /admin/users/{id}/reset-2fa`. Clears the second factor and the recovery codes, and mails the | |
| 417 | +/// account's own address so the person knows. | |
| 418 | +#[route(POST "/admin/users/{id}/reset-2fa")] | |
| 419 | +async fn reset_two_factor(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> { | |
| 420 | + let (viewer, user) = target(cx, &form.csrf).await?; | |
| 421 | + let base = format!("/admin/users/{}", user.id); | |
| 422 | + if user.id == viewer.user.id { | |
| 423 | + return Ok(refused(&base, "self")); | |
| 424 | + } | |
| 425 | + let state = app_context::<AppState>(cx); | |
| 426 | + state.store.disable_totp(&user.id).await?; | |
| 427 | + state.live.bump(&Topic::Account(user.id.clone())); | |
| 428 | + changed(&state.live); | |
| 429 | + let request_lang = page_lang(cx, Some(&viewer)); | |
| 430 | + mail::notify( | |
| 431 | + &state.store, | |
| 432 | + &state.key, | |
| 433 | + &user, | |
| 434 | + request_lang, | |
| 435 | + Notice::TwoFactorOff, | |
| 436 | + ) | |
| 437 | + .await; | |
| 438 | + record( | |
| 439 | + cx, | |
| 440 | + Actor::User(&viewer.user.id), | |
| 441 | + AuditAction::AdminTwoFactorReset, | |
| 442 | + Some(("user", &user.id)), | |
| 443 | + json!({}), | |
| 444 | + ) | |
| 445 | + .await; | |
| 446 | + Ok(done(&base, "2fa-reset")) | |
| 447 | +} | |
| 448 | + | |
| 449 | +/// `POST /admin/users/{id}/revoke-sessions`. Ends every session of the account, with their logouts. | |
| 450 | +#[route(POST "/admin/users/{id}/revoke-sessions")] | |
| 451 | +async fn revoke_sessions(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> { | |
| 452 | + let (viewer, user) = target(cx, &form.csrf).await?; | |
| 453 | + let base = format!("/admin/users/{}", user.id); | |
| 454 | + if user.id == viewer.user.id { | |
| 455 | + return Ok(refused(&base, "self")); | |
| 456 | + } | |
| 457 | + let state = app_context::<AppState>(cx); | |
| 458 | + let ended = state | |
| 459 | + .store | |
| 460 | + .end_all_sessions(&user.id, EndReason::Revoked) | |
| 461 | + .await?; | |
| 462 | + if !ended.is_empty() { | |
| 463 | + state.live.bump(&Topic::Account(user.id.clone())); | |
| 464 | + changed(&state.live); | |
| 465 | + record( | |
| 466 | + cx, | |
| 467 | + Actor::User(&viewer.user.id), | |
| 468 | + AuditAction::AdminSessionsRevoked, | |
| 469 | + Some(("user", &user.id)), | |
| 470 | + json!({ "count": ended.len() }), | |
| 471 | + ) | |
| 472 | + .await; | |
| 473 | + } | |
| 474 | + Ok(done(&base, "sessions-revoked")) | |
| 475 | +} | |
| 476 | + | |
| 477 | +/// `POST /admin/users/{id}/delete`. The address must be typed again. Deletes the account, its sessions, | |
| 478 | +/// links and recovery codes, and then its photo file. The last enabled administrator cannot be deleted. | |
| 479 | +#[route(POST "/admin/users/{id}/delete")] | |
| 480 | +async fn delete_account(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> { | |
| 481 | + let (viewer, user) = target(cx, &form.csrf).await?; | |
| 482 | + let base = format!("/admin/users/{}", user.id); | |
| 483 | + if user.id == viewer.user.id { | |
| 484 | + return Ok(refused(&base, "self-delete")); | |
| 485 | + } | |
| 486 | + if normalize_email(&form.confirm) != user.email { | |
| 487 | + return Ok(refused(&base, "confirm-email")); | |
| 488 | + } | |
| 489 | + let state = app_context::<AppState>(cx); | |
| 490 | + match state.store.delete_user(&user.id).await { | |
| 491 | + Ok(true) => { | |
| 492 | + if let Err(error) = im_core::photo::remove_photo(&state.config.data_dir, &user.id) { | |
| 493 | + tracing::error!(error = %error, "photo of a deleted account not removed"); | |
| 494 | + } | |
| 495 | + state.live.bump(&Topic::Account(user.id.clone())); | |
| 496 | + changed(&state.live); | |
| 497 | + record( | |
| 498 | + cx, | |
| 499 | + Actor::User(&viewer.user.id), | |
| 500 | + AuditAction::UserDeleted, | |
| 501 | + Some(("user", &user.id)), | |
| 502 | + json!({}), | |
| 503 | + ) | |
| 504 | + .await; | |
| 505 | + Ok(done("/admin/users", "deleted")) | |
| 506 | + } | |
| 507 | + Ok(false) => Ok(done("/admin/users", "deleted")), | |
| 508 | + Err(CoreError::Conflict(_)) => Ok(refused(&base, "last-admin")), | |
| 509 | + Err(error) => Err(error.into()), | |
| 510 | + } | |
| 511 | +} |
crates/im-web/src/pages/email.rsmodified+1 -1
| @@ -137,7 +137,7 @@ async fn email_request_submit(cx: &Cx, Form(form): Form<EmailRequestForm>) -> Re | ||
| 137 | 137 | )); |
| 138 | 138 | } |
| 139 | 139 | |
| 140 | - let hours = state.config.policy.email_change_hours; | |
| 140 | + let hours = state.policy().email_change_hours; | |
| 141 | 141 | let old_token = generate_token(); |
| 142 | 142 | let new_token = generate_token(); |
| 143 | 143 | let expires = stamp_after(Duration::from_secs(u64::from(hours) * 60 * 60)); |
crates/im-web/src/pages/invite.rsmodified+6 -155
| @@ -4,14 +4,13 @@ | ||
| 4 | 4 | //! gets the styled not-found page, and so does an acceptance that the store refuses (the link was spent |
| 5 | 5 | //! meanwhile, or the address got an account). The acceptance itself is one conditional update in the |
| 6 | 6 | //! store, so parallel submissions create one account. `/admin/invites` is the minimal admin form that |
| 7 | -//! creates invitations; it answers 404 to anyone who is not an administrator. | |
| 7 | +//! is in `pages/admin/invites.rs`. | |
| 8 | 8 | |
| 9 | 9 | use im_core::model::{AuditAction, amr}; |
| 10 | -use im_core::names::{parse_display_name, parse_email}; | |
| 10 | +use im_core::names::parse_display_name; | |
| 11 | 11 | use im_core::password::{check_policy, hash_password_async}; |
| 12 | -use im_core::store::invites::{AcceptOutcome, invite_lifetime}; | |
| 13 | -use im_core::time::stamp_after; | |
| 14 | -use im_core::token::{generate_token, hash_token}; | |
| 12 | +use im_core::store::invites::AcceptOutcome; | |
| 13 | +use im_core::token::hash_token; | |
| 15 | 14 | use serde::Deserialize; |
| 16 | 15 | use serde_json::json; |
| 17 | 16 | use topcoat::Result; |
| @@ -22,17 +21,13 @@ use topcoat::router::page; | ||
| 22 | 21 | use topcoat::view::{View, view}; |
| 23 | 22 | |
| 24 | 23 | use crate::audit::{Actor, record}; |
| 25 | -use crate::auth::{ | |
| 26 | - after_sign_in, check_csrf, check_pre_csrf, clear_pre_csrf, pre_csrf_token, require_admin, | |
| 27 | - start_session, | |
| 28 | -}; | |
| 24 | +use crate::auth::{after_sign_in, check_pre_csrf, clear_pre_csrf, pre_csrf_token, start_session}; | |
| 29 | 25 | use crate::i18n::Lang; |
| 30 | 26 | use crate::i18n::account::{Txt, policy_problem, text}; |
| 31 | 27 | use crate::i18n::flows::{Flow, text as flow_text}; |
| 32 | -use crate::mail::{self, Mail, Recipient}; | |
| 33 | 28 | use crate::pages::path_param; |
| 34 | 29 | use crate::state::AppState; |
| 35 | -use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; | |
| 30 | +use crate::views::{alert, field, page_lang, shell}; | |
| 36 | 31 | |
| 37 | 32 | /// The invitation form. |
| 38 | 33 | #[derive(Deserialize, Default)] |
| @@ -47,24 +42,6 @@ struct InviteForm { | ||
| 47 | 42 | password_again: String, |
| 48 | 43 | } |
| 49 | 44 | |
| 50 | -/// The administrator's invitation form. The checkbox sends `on` when ticked. | |
| 51 | -#[derive(Deserialize, Default)] | |
| 52 | -struct AdminInviteForm { | |
| 53 | - #[serde(default)] | |
| 54 | - csrf: String, | |
| 55 | - #[serde(default)] | |
| 56 | - email: String, | |
| 57 | - #[serde(default)] | |
| 58 | - admin: String, | |
| 59 | -} | |
| 60 | - | |
| 61 | -/// The query of `GET /admin/invites`. | |
| 62 | -#[derive(Deserialize, Default)] | |
| 63 | -struct NoticeQuery { | |
| 64 | - #[serde(default)] | |
| 65 | - notice: String, | |
| 66 | -} | |
| 67 | - | |
| 68 | 45 | /// `GET /invite/{token}`. |
| 69 | 46 | #[page("/invite/{token}")] |
| 70 | 47 | async fn invite_form(cx: &Cx) -> Result<impl View> { |
| @@ -140,98 +117,6 @@ async fn invite_submit(cx: &Cx, Form(form): Form<InviteForm>) -> Result<impl Vie | ||
| 140 | 117 | Err(see_other(after_sign_in(state, &user, "/")).into()) |
| 141 | 118 | } |
| 142 | 119 | |
| 143 | -/// `GET /admin/invites`. Non-administrators get 404. | |
| 144 | -#[page("/admin/invites")] | |
| 145 | -async fn admin_invites_form(cx: &Cx, Form(query): Form<NoticeQuery>) -> Result<impl View> { | |
| 146 | - let viewer = require_admin(cx).await?; | |
| 147 | - let lang = page_lang(cx, Some(&viewer)); | |
| 148 | - Ok(admin_invites_view( | |
| 149 | - cx, | |
| 150 | - lang, | |
| 151 | - ViewerInfo::of(&viewer), | |
| 152 | - viewer.session.csrf_token.clone(), | |
| 153 | - query.notice == "sent", | |
| 154 | - None, | |
| 155 | - )) | |
| 156 | -} | |
| 157 | - | |
| 158 | -/// `POST /admin/invites`: creates the invitation and queues its mail. | |
| 159 | -#[page(POST "/admin/invites")] | |
| 160 | -async fn admin_invites_submit(cx: &Cx, Form(form): Form<AdminInviteForm>) -> Result<impl View> { | |
| 161 | - let viewer = require_admin(cx).await?; | |
| 162 | - if !check_csrf(&viewer.session, &form.csrf) { | |
| 163 | - return Err(forbidden().into()); | |
| 164 | - } | |
| 165 | - let state = app_context::<AppState>(cx); | |
| 166 | - let lang = page_lang(cx, Some(&viewer)); | |
| 167 | - let csrf = viewer.session.csrf_token.clone(); | |
| 168 | - let info = ViewerInfo::of(&viewer); | |
| 169 | - | |
| 170 | - let email = match parse_email(&form.email) { | |
| 171 | - Ok(email) => email, | |
| 172 | - Err(_) => { | |
| 173 | - let problem = text(lang, Txt::ErrEmailInvalid).to_owned(); | |
| 174 | - return Ok(admin_invites_view( | |
| 175 | - cx, | |
| 176 | - lang, | |
| 177 | - info, | |
| 178 | - csrf, | |
| 179 | - false, | |
| 180 | - Some(problem), | |
| 181 | - )); | |
| 182 | - } | |
| 183 | - }; | |
| 184 | - let is_admin = form.admin == "on"; | |
| 185 | - let days = state.config.policy.invite_days; | |
| 186 | - let token = generate_token(); | |
| 187 | - let expires = stamp_after(invite_lifetime(days)); | |
| 188 | - match state | |
| 189 | - .store | |
| 190 | - .create_invite( | |
| 191 | - &hash_token(&token), | |
| 192 | - &email, | |
| 193 | - is_admin, | |
| 194 | - &viewer.user.id, | |
| 195 | - &expires, | |
| 196 | - ) | |
| 197 | - .await | |
| 198 | - { | |
| 199 | - Ok(()) => {} | |
| 200 | - Err(im_core::Error::Conflict(_)) => { | |
| 201 | - let problem = flow_text(lang, Flow::InviteAddressTaken).to_owned(); | |
| 202 | - return Ok(admin_invites_view( | |
| 203 | - cx, | |
| 204 | - lang, | |
| 205 | - info, | |
| 206 | - csrf, | |
| 207 | - false, | |
| 208 | - Some(problem), | |
| 209 | - )); | |
| 210 | - } | |
| 211 | - Err(error) => return Err(error.into()), | |
| 212 | - } | |
| 213 | - | |
| 214 | - let link = format!("{}/invite/{token}", state.config.base_url); | |
| 215 | - match Recipient::new(None, &email) { | |
| 216 | - Ok(to) => { | |
| 217 | - let mail = Mail::Invite { link: &link, days }; | |
| 218 | - if let Err(error) = mail::queue(&state.store, &state.key, &to, lang, &mail).await { | |
| 219 | - tracing::error!(error = %error, "invitation mail not queued"); | |
| 220 | - } | |
| 221 | - } | |
| 222 | - Err(error) => tracing::error!(error, "invitation mail not queued"), | |
| 223 | - } | |
| 224 | - record( | |
| 225 | - cx, | |
| 226 | - Actor::User(&viewer.user.id), | |
| 227 | - AuditAction::InviteCreated, | |
| 228 | - None, | |
| 229 | - json!({ "admin": is_admin }), | |
| 230 | - ) | |
| 231 | - .await; | |
| 232 | - Err(see_other("/admin/invites?notice=sent").into()) | |
| 233 | -} | |
| 234 | - | |
| 235 | 120 | /// The invitation page: the address (read only), the name and the new password. |
| 236 | 121 | fn invite_view( |
| 237 | 122 | cx: &Cx, |
| @@ -266,37 +151,3 @@ fn invite_view( | ||
| 266 | 151 | ) |
| 267 | 152 | } |
| 268 | 153 | } |
| 269 | - | |
| 270 | -/// The administrator's invitation form, with the result of the last submission above it. | |
| 271 | -fn admin_invites_view( | |
| 272 | - cx: &Cx, | |
| 273 | - lang: Lang, | |
| 274 | - info: ViewerInfo, | |
| 275 | - csrf: String, | |
| 276 | - sent: bool, | |
| 277 | - problem: Option<String>, | |
| 278 | -) -> impl View { | |
| 279 | - view! { cx => | |
| 280 | - shell(title: flow_text(lang, Flow::AdminInvitesTitle), lang: lang, viewer: Some(info), | |
| 281 | - <section class="card narrow stack"> | |
| 282 | - <h1>(flow_text(lang, Flow::AdminInvitesTitle))</h1> | |
| 283 | - <p class="muted">(flow_text(lang, Flow::AdminInvitesIntro))</p> | |
| 284 | - if sent { | |
| 285 | - notice(message: flow_text(lang, Flow::InviteQueued).to_owned()) | |
| 286 | - } | |
| 287 | - if let Some(problem) = problem { | |
| 288 | - alert(message: problem) | |
| 289 | - } | |
| 290 | - <form method="post" action="/admin/invites" class="stack"> | |
| 291 | - <input type="hidden" name="csrf" value=(csrf)> | |
| 292 | - field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "off", value: String::new()) | |
| 293 | - <label class="check"> | |
| 294 | - <input type="checkbox" name="admin"> | |
| 295 | - <span>(flow_text(lang, Flow::InviteAsAdmin))</span> | |
| 296 | - </label> | |
| 297 | - <button type="submit" class="button primary">(flow_text(lang, Flow::InviteSend))</button> | |
| 298 | - </form> | |
| 299 | - </section> | |
| 300 | - ) | |
| 301 | - } | |
| 302 | -} |
crates/im-web/src/pages/mod.rsmodified+1 -0
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | //! The pages and the page-level layers. One file per page. |
| 2 | 2 | |
| 3 | +pub mod admin; | |
| 3 | 4 | pub mod email; |
| 4 | 5 | pub mod home; |
| 5 | 6 | pub mod invite; |
crates/im-web/src/pages/reset.rsmodified+1 -1
| @@ -110,7 +110,7 @@ async fn forgot_submit(cx: &Cx, Form(form): Form<ForgotForm>) -> Result<impl Vie | ||
| 110 | 110 | state.store.clone(), |
| 111 | 111 | state.key.clone(), |
| 112 | 112 | state.config.base_url.clone(), |
| 113 | - state.config.policy.reset_minutes, | |
| 113 | + state.policy().reset_minutes, | |
| 114 | 114 | user, |
| 115 | 115 | lang, |
| 116 | 116 | client.to_string(), |
crates/im-web/src/state.rsmodified+24 -2
| @@ -1,8 +1,8 @@ | ||
| 1 | 1 | //! The state shared by every route. Topcoat hands it to each handler through the app context. |
| 2 | 2 | |
| 3 | -use std::sync::Arc; | |
| 3 | +use std::sync::{Arc, PoisonError, RwLock}; | |
| 4 | 4 | |
| 5 | -use im_core::config::Config; | |
| 5 | +use im_core::config::{Config, PolicyConfig}; | |
| 6 | 6 | use im_core::store::Store; |
| 7 | 7 | use tokio::sync::watch; |
| 8 | 8 | |
| @@ -15,6 +15,10 @@ use crate::throttle::Throttle; | ||
| 15 | 15 | pub struct AppState { |
| 16 | 16 | /// The configuration the process booted with. |
| 17 | 17 | pub config: Arc<Config>, |
| 18 | + /// The sign-in policy in effect: the file values, with the settings saved in the admin UI layered on | |
| 19 | + /// top. Read it through [`AppState::policy`]; the admin settings page replaces it while the server | |
| 20 | + /// runs. | |
| 21 | + pub policy_live: Arc<RwLock<PolicyConfig>>, | |
| 18 | 22 | /// The database. Reads go to a pooled reader and writes to the single writer. |
| 19 | 23 | pub store: Store, |
| 20 | 24 | /// The instance key (`im.key`). Seals secrets at rest. |
| @@ -28,3 +32,21 @@ pub struct AppState { | ||
| 28 | 32 | /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain. |
| 29 | 33 | pub stop: watch::Receiver<bool>, |
| 30 | 34 | } |
| 35 | + | |
| 36 | +impl AppState { | |
| 37 | + /// A copy of the policy in effect now. Cheap: the policy is a handful of numbers. | |
| 38 | + pub fn policy(&self) -> PolicyConfig { | |
| 39 | + self.policy_live | |
| 40 | + .read() | |
| 41 | + .unwrap_or_else(PoisonError::into_inner) | |
| 42 | + .clone() | |
| 43 | + } | |
| 44 | + | |
| 45 | + /// Replaces the policy in effect. Used when an administrator saves the settings page. | |
| 46 | + pub fn set_policy(&self, policy: PolicyConfig) { | |
| 47 | + *self | |
| 48 | + .policy_live | |
| 49 | + .write() | |
| 50 | + .unwrap_or_else(PoisonError::into_inner) = policy; | |
| 51 | + } | |
| 52 | +} |
deploy/ferron.kdladded+6 -0
| @@ -0,0 +1,6 @@ | ||
| 1 | +// Example Ferron site for `im`. Ferron terminates TLS and forwards to the loopback listener of `im`. | |
| 2 | +// Check the directive names against the Ferron version you run; this file shows the shape, it has not been | |
| 3 | +// run against a live Ferron here. `base_url` in im.toml must be this same origin. | |
| 4 | +im.example.com { | |
| 5 | + proxy http://127.0.0.1:7650 | |
| 6 | +} |
deploy/im.serviceadded+47 -0
| @@ -0,0 +1,47 @@ | ||
| 1 | +[Unit] | |
| 2 | +Description=im: the family's sign-in provider (OpenID Connect) | |
| 3 | +After=network-online.target | |
| 4 | +Wants=network-online.target | |
| 5 | +StartLimitIntervalSec=60 | |
| 6 | +StartLimitBurst=5 | |
| 7 | + | |
| 8 | +[Service] | |
| 9 | +Type=simple | |
| 10 | +User=im | |
| 11 | +Group=im | |
| 12 | +Environment=IM_CONFIG=/etc/im/im.toml | |
| 13 | +ExecStart=/usr/local/bin/im serve | |
| 14 | +WorkingDirectory=/var/lib/im | |
| 15 | +Restart=on-failure | |
| 16 | +RestartSec=2 | |
| 17 | +LimitNOFILE=65536 | |
| 18 | + | |
| 19 | +# Hardening. The service writes only to its state directory: database, data_dir (instance key, photos) and | |
| 20 | +# the backup dir. If [backup] dir is set outside /var/lib/im, add that path to ReadWritePaths. | |
| 21 | +NoNewPrivileges=yes | |
| 22 | +ProtectSystem=strict | |
| 23 | +ProtectHome=yes | |
| 24 | +ReadWritePaths=/var/lib/im | |
| 25 | +PrivateTmp=yes | |
| 26 | +PrivateDevices=yes | |
| 27 | +PrivateUsers=yes | |
| 28 | +ProtectKernelTunables=yes | |
| 29 | +ProtectKernelModules=yes | |
| 30 | +ProtectKernelLogs=yes | |
| 31 | +ProtectControlGroups=yes | |
| 32 | +ProtectClock=yes | |
| 33 | +ProtectHostname=yes | |
| 34 | +RestrictSUIDSGID=yes | |
| 35 | +RestrictRealtime=yes | |
| 36 | +RestrictNamespaces=yes | |
| 37 | +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 | |
| 38 | +LockPersonality=yes | |
| 39 | +MemoryDenyWriteExecute=yes | |
| 40 | +SystemCallArchitectures=native | |
| 41 | +SystemCallFilter=@system-service | |
| 42 | +CapabilityBoundingSet= | |
| 43 | +AmbientCapabilities= | |
| 44 | +UMask=0077 | |
| 45 | + | |
| 46 | +[Install] | |
| 47 | +WantedBy=multi-user.target |