Settings and admin pages, audit, family switcher, backups (prune only manifest-holding sets), export/fsck/restore/quota CLI, systemd unit, Ferron example, README
Browse files at this commit60b492cca28a9e72c5ef07c1ebaf380256a93f66Parent: 53cbc6b- feat
- settings and admin pages, audit, family switcher, backups (prune only manifest-holding sets), export/fsck/restore/quota CLI, systemd unit, Ferron example, README
48 changed files +3839 -136
- Cargo.lock +15 -0
- Cargo.toml +2 -0
- README.md +148 -0
- config/in.example.toml +9 -0
- crates/in-core/src/backup.rs +403 -0
- crates/in-core/src/blob/mod.rs +26 -0
- crates/in-core/src/config.rs +21 -0
- crates/in-core/src/export.rs +246 -0
- crates/in-core/src/fsck.rs +183 -0
- crates/in-core/src/lib.rs +4 -0
- crates/in-core/src/settings.rs +256 -0
- crates/in-core/src/store/audit.rs +164 -0
- crates/in-core/src/store/members.rs +20 -0
- crates/in-core/src/store/mod.rs +1 -0
- crates/in-core/src/store/objects.rs +20 -0
- crates/in-core/src/store/settings.rs +9 -0
- crates/in-web/Cargo.toml +2 -0
- crates/in-web/src/api/machine_auth.rs +7 -6
- crates/in-web/src/api/upload.rs +7 -14
- crates/in-web/src/audit.rs +50 -0
- crates/in-web/src/auth.rs +10 -2
- crates/in-web/src/backup.rs +68 -0
- crates/in-web/src/boot.rs +69 -2
- crates/in-web/src/cli.rs +210 -0
- crates/in-web/src/directory.rs +8 -2
- crates/in-web/src/family.rs +149 -0
- crates/in-web/src/health.rs +3 -3
- crates/in-web/src/i18n/admin.rs +297 -0
- crates/in-web/src/i18n/mod.rs +2 -0
- crates/in-web/src/i18n/settings.rs +95 -0
- crates/in-web/src/live.rs +5 -4
- crates/in-web/src/main.rs +15 -59
- crates/in-web/src/pages/admin.rs +947 -0
- crates/in-web/src/pages/drive.rs +5 -3
- crates/in-web/src/pages/files.rs +1 -1
- crates/in-web/src/pages/links.rs +65 -16
- crates/in-web/src/pages/mod.rs +2 -0
- crates/in-web/src/pages/settings.rs +176 -0
- crates/in-web/src/pages/share_dialog.rs +1 -1
- crates/in-web/src/pages/shared.rs +1 -1
- crates/in-web/src/pages/sign_in.rs +9 -3
- crates/in-web/src/pages/trash.rs +1 -1
- crates/in-web/src/pages/view.rs +1 -1
- crates/in-web/src/state.rs +3 -0
- crates/in-web/src/sweeper.rs +7 -11
- crates/in-web/src/views/mod.rs +43 -6
- deploy/ferron.kdl +6 -0
- deploy/in.service +47 -0
Cargo.lockmodified+15 -0
| @@ -588,6 +588,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 588 | checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" | 588 | checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" |
| 589 | dependencies = [ | 589 | dependencies = [ |
| 590 | "clap_builder", | 590 | "clap_builder", |
| 591 | + "clap_derive", | ||
| 591 | ] | 592 | ] |
| 592 | 593 | ||
| 593 | [[package]] | 594 | [[package]] |
| @@ -602,6 +603,18 @@ dependencies = [ | |||
| 602 | "strsim", | 603 | "strsim", |
| 603 | ] | 604 | ] |
| 604 | 605 | ||
| 606 | +[[package]] | ||
| 607 | +name = "clap_derive" | ||
| 608 | +version = "4.6.7" | ||
| 609 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 610 | +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" | ||
| 611 | +dependencies = [ | ||
| 612 | + "heck", | ||
| 613 | + "proc-macro2", | ||
| 614 | + "quote", | ||
| 615 | + "syn 3.0.9", | ||
| 616 | +] | ||
| 617 | + | ||
| 605 | [[package]] | 618 | [[package]] |
| 606 | name = "clap_lex" | 619 | name = "clap_lex" |
| 607 | version = "1.1.1" | 620 | version = "1.1.1" |
| @@ -1968,6 +1981,7 @@ name = "in-web" | |||
| 1968 | version = "0.1.0" | 1981 | version = "0.1.0" |
| 1969 | dependencies = [ | 1982 | dependencies = [ |
| 1970 | "base64 0.23.1", | 1983 | "base64 0.23.1", |
| 1984 | + "clap", | ||
| 1971 | "ed25519-dalek", | 1985 | "ed25519-dalek", |
| 1972 | "futures-util", | 1986 | "futures-util", |
| 1973 | "grass", | 1987 | "grass", |
| @@ -1979,6 +1993,7 @@ dependencies = [ | |||
| 1979 | "jsonwebtoken", | 1993 | "jsonwebtoken", |
| 1980 | "rand 0.10.3", | 1994 | "rand 0.10.3", |
| 1981 | "reqwest", | 1995 | "reqwest", |
| 1996 | + "rustix 1.1.6", | ||
| 1982 | "serde", | 1997 | "serde", |
| 1983 | "serde_json", | 1998 | "serde_json", |
| 1984 | "serde_urlencoded", | 1999 | "serde_urlencoded", |
Cargo.tomlmodified+2 -0
| @@ -44,6 +44,7 @@ argon2 = "0.6.0" | |||
| 44 | async-trait = "0.1.92" | 44 | async-trait = "0.1.92" |
| 45 | base64 = "0.23.1" | 45 | base64 = "0.23.1" |
| 46 | bytes = "1.12.1" | 46 | bytes = "1.12.1" |
| 47 | +clap = { version = "4.6.7", features = ["derive"] } | ||
| 47 | chacha20poly1305 = "0.11.0" | 48 | chacha20poly1305 = "0.11.0" |
| 48 | ed25519-dalek = "2.1.1" | 49 | ed25519-dalek = "2.1.1" |
| 49 | futures-util = "0.3.34" | 50 | futures-util = "0.3.34" |
| @@ -59,6 +60,7 @@ ipnet = "2.12.2" | |||
| 59 | jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] } | 60 | jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] } |
| 60 | object_store = { version = "0.14.2", features = ["aws"] } | 61 | object_store = { version = "0.14.2", features = ["aws"] } |
| 61 | rand = "0.10.3" | 62 | rand = "0.10.3" |
| 63 | +rustix = { version = "1.1.6", default-features = false, features = ["fs"] } | ||
| 62 | reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls", "stream"] } | 64 | reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls", "stream"] } |
| 63 | serde = "1.0.229" | 65 | serde = "1.0.229" |
| 64 | serde_json = "1.0.154" | 66 | serde_json = "1.0.154" |
README.mdadded+148 -0
| @@ -0,0 +1,148 @@ | |||
| 1 | +# in | ||
| 2 | + | ||
| 3 | +`in` is the family's file drive. It keeps folders and files, resumable uploads, previews and thumbnails, a | ||
| 4 | +trash, sharing with people and by link, and per-person quotas. It also stores bytes for the other family | ||
| 5 | +apps through a machine API. It is one binary, `in`, with the web UI, the API, the background workers and the | ||
| 6 | +operator commands. Files are plain files in a blob tree, and `in export` writes them out as an ordinary folder | ||
| 7 | +tree that needs no `in` to read. | ||
| 8 | + | ||
| 9 | +`in` depends on `im` for sign-in (OpenID Connect) and the people directory. Once a person is signed in, their | ||
| 10 | +files keep working while `im` is down. The shared contracts are in `docs/contracts.md`; the design is in | ||
| 11 | +`docs/architecture.md`; the code rules are in `docs/conventions.md`. | ||
| 12 | + | ||
| 13 | +## Build | ||
| 14 | + | ||
| 15 | +You need Rust stable (edition 2024). The stylesheet is compiled from `style/` at build time, so there is no | ||
| 16 | +Node step. | ||
| 17 | + | ||
| 18 | +```sh | ||
| 19 | +cargo build --release -p in-web # binary: target/release/in | ||
| 20 | +cargo test --workspace | ||
| 21 | +``` | ||
| 22 | + | ||
| 23 | +Install the binary and the unit: | ||
| 24 | + | ||
| 25 | +```sh | ||
| 26 | +sudo install -m 0755 target/release/in /usr/local/bin/in | ||
| 27 | +sudo useradd --system --home-dir /var/lib/in --shell /usr/sbin/nologin in | ||
| 28 | +sudo install -d -o in -g in -m 0700 /var/lib/in | ||
| 29 | +sudo install -d -m 0755 /etc/in | ||
| 30 | +sudo install -m 0644 deploy/in.service /etc/systemd/system/in.service | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +Do not enable the unit until the configuration and the `im` client below are in place. | ||
| 34 | + | ||
| 35 | +## Configuration | ||
| 36 | + | ||
| 37 | +`in` reads `--config <path>`, then `IN_CONFIG`, then `config/in.toml`. A missing file is created from | ||
| 38 | +`config/in.example.toml` on first run. Unknown keys are an error, so a typo fails at start-up. | ||
| 39 | + | ||
| 40 | +The file holds no secrets. The OIDC client secret and the S3 keys are read from files that only the service | ||
| 41 | +user can read: | ||
| 42 | + | ||
| 43 | +| Key | Meaning | | ||
| 44 | +|---|---| | ||
| 45 | +| `database`, `data_dir` | Database file and data directory (blobs, staging, `in.key`, `in.lock`). The data directory is created with mode 0700. | | ||
| 46 | +| `listen` | Address to bind. Keep it on loopback and put the reverse proxy in front. | | ||
| 47 | +| `base_url` | Public origin with no trailing slash. An `https` origin turns on `Secure` cookies and HSTS. | | ||
| 48 | +| `trusted_proxies` | Proxies whose `X-Forwarded-For` is believed. | | ||
| 49 | +| `[oidc]` | `issuer` (the `im` origin), `client_id` (`in`), `client_secret_file`. | | ||
| 50 | +| `[storage]` | `backend = "local"` (default) or `"s3"` with `[storage.s3]`. | | ||
| 51 | +| `[backup]` | Optional. `dir`, `interval_hours`, `keep`, `healthcheck_url`. See *Backups*. | | ||
| 52 | +| `[limits]` | Optional defaults the admin page may override: quotas, purge days, upload size, link length. | | ||
| 53 | + | ||
| 54 | +The admin page at `/admin` shows, next to each runtime value, whether it was set there, comes from the file, or | ||
| 55 | +is the built-in default. A blank field on that page removes the page's value again. | ||
| 56 | + | ||
| 57 | +## First run | ||
| 58 | + | ||
| 59 | +1. Start the server once to create the configuration and the instance key, then stop it: | ||
| 60 | + | ||
| 61 | + ```sh | ||
| 62 | + IN_CONFIG=/etc/in/in.toml in serve | ||
| 63 | + ``` | ||
| 64 | + | ||
| 65 | +2. Register `in` as a client of `im` (run on the `im` host, where its data directory is). Replace `<base>` with | ||
| 66 | + the value of `base_url`: | ||
| 67 | + | ||
| 68 | + ```sh | ||
| 69 | + im client add --name in \ | ||
| 70 | + --redirect-uri "<base>/auth/callback" \ | ||
| 71 | + --post-logout-uri "<base>/" \ | ||
| 72 | + --backchannel-uri "<base>/auth/backchannel-logout" \ | ||
| 73 | + --family-key in | ||
| 74 | + ``` | ||
| 75 | + | ||
| 76 | + `im` prints the client id and its secret once. Save the secret to the file named by `client_secret_file` | ||
| 77 | + (`/var/lib/in/oidc_client_secret`, mode 0600, owned by `in`). The default scopes (`openid profile email`) are | ||
| 78 | + what `in` needs; the family's `directory.read` scope is granted to every family client by default. | ||
| 79 | + | ||
| 80 | +3. Put the reverse proxy in front (see `deploy/ferron.kdl`, an example for Ferron that proxies | ||
| 81 | + `https://in.example.com` to `127.0.0.1:7655`). Ferron must not buffer responses: the live update stream | ||
| 82 | + depends on it. | ||
| 83 | + | ||
| 84 | +4. Start the service: | ||
| 85 | + | ||
| 86 | + ```sh | ||
| 87 | + sudo systemctl enable --now in | ||
| 88 | + curl -s http://127.0.0.1:7655/healthz # ok <build> | ||
| 89 | + ``` | ||
| 90 | + | ||
| 91 | + The first person who signs in becomes a member. Administrators are the people `im` marks as admins. | ||
| 92 | + | ||
| 93 | +The service unit runs `in serve` as the `in` user with systemd hardening (read-only system, no capabilities, | ||
| 94 | +a system-call filter). Its writable paths are the state directory and, when `[backup]` is set, the backup | ||
| 95 | +directory, which you add to `ReadWritePaths`. | ||
| 96 | + | ||
| 97 | +## Backups | ||
| 98 | + | ||
| 99 | +With `[backup]` set, `in serve` writes a backup set every `interval_hours`, keeps the newest `keep` sets, and | ||
| 100 | +pings `healthcheck_url` after each good run (a failed ping is logged and nothing else). | ||
| 101 | + | ||
| 102 | +A set is a directory `set-<time>` in `dir`, holding: | ||
| 103 | + | ||
| 104 | +- `in.db`: a consistent snapshot of the database (`VACUUM INTO`, checkpointed to one file). | ||
| 105 | +- `manifest.json`: the snapshot's size and SHA-256, and every blob with its key, size and SHA-256. | ||
| 106 | + | ||
| 107 | +Blob bytes are not copied. Keep the blob tree (`data_dir/blobs`) under its own backup, or use an S3 bucket | ||
| 108 | +with its own versioning. The manifest is what lets `in fsck --hash` and a restore check what should be there. | ||
| 109 | + | ||
| 110 | +### Restore | ||
| 111 | + | ||
| 112 | +1. Stop the service. `in restore` refuses to run while the server holds the data-directory lock. | ||
| 113 | +2. Run the restore with the set you want: | ||
| 114 | + | ||
| 115 | + ```sh | ||
| 116 | + in --config /etc/in/in.toml restore --from /var/lib/in/backups/set-2026-10-28T09-00-00-000000000Z | ||
| 117 | + ``` | ||
| 118 | + | ||
| 119 | + It checks the manifest format, the snapshot's size and hash, and the snapshot's integrity before it changes | ||
| 120 | + anything. A set that fails a check is refused and nothing is replaced. The database it replaces is moved to | ||
| 121 | + `data_dir/restore-<time>/` and is not deleted. | ||
| 122 | +3. Run `in fsck` to see whether every row has its blob. Blobs listed in the manifest but missing from the blob | ||
| 123 | + tree are reported by the restore; they were deleted after the set was written. | ||
| 124 | +4. Start the service. | ||
| 125 | + | ||
| 126 | +The database must lie inside `data_dir`. Restore does not replace anything outside it. | ||
| 127 | + | ||
| 128 | +## Command line | ||
| 129 | + | ||
| 130 | +| Command | What it does | | ||
| 131 | +|---|---| | ||
| 132 | +| `in serve` | Runs the server. A bare `in` does the same. | | ||
| 133 | +| `in export --member <sub or email> --out <dir>` | Copies one person's live files into `<dir>` as a folder tree with their names. Names are sanitized so nothing is written outside `<dir>`. Each file is hashed as it is copied and checked against its row. | | ||
| 134 | +| `in fsck [--hash]` | Checks `PRAGMA integrity_check`, that every file, ready thumbnail and object has a blob of the recorded size, and with `--hash` the SHA-256 of every blob. Lists orphan blobs. Changes nothing. Exit status 1 when a problem is found. | | ||
| 135 | +| `in restore --from <set>` | Replaces the database with the one in a backup set, after verification (see *Restore*). | | ||
| 136 | +| `in quota recompute` | Recomputes every person's used bytes from their files and prints the ones that were wrong. | | ||
| 137 | + | ||
| 138 | +The commands other than `serve` take the data-directory lock. While the server runs they stop with | ||
| 139 | +`in is running on this data directory. Stop the server first, then run the command again.` | ||
| 140 | + | ||
| 141 | +## Layout | ||
| 142 | + | ||
| 143 | +``` | ||
| 144 | +crates/in-core/ domain, store, migrations, config, settings, blobs, backup, export, fsck | ||
| 145 | +crates/in-web/ the `in` binary: pages, sign-in, machine API, workers, CLI | ||
| 146 | +deploy/ systemd unit and reverse-proxy example | ||
| 147 | +docs/ contracts, architecture, conventions | ||
| 148 | +``` | ||
config/in.example.tomlmodified+9 -0
| @@ -31,6 +31,15 @@ backend = "local" | |||
| 31 | # access_key_id_file = "/etc/in/s3_access_key_id" | 31 | # access_key_id_file = "/etc/in/s3_access_key_id" |
| 32 | # secret_access_key_file = "/etc/in/s3_secret_access_key" | 32 | # secret_access_key_file = "/etc/in/s3_secret_access_key" |
| 33 | 33 | ||
| 34 | +# Defaults the admin page may override at run time. Each value is optional; an absent one uses the built-in | ||
| 35 | +# default. The admin page shows where each value comes from: set there, set here, or the built-in default. | ||
| 36 | +# [limits] | ||
| 37 | +# default_quota_bytes = 10737418240 # quota of a new person (10 GiB) | ||
| 38 | +# default_service_quota_bytes = 10737418240 # quota of a new service (10 GiB) | ||
| 39 | +# purge_after_days = 30 # days before trash is purged | ||
| 40 | +# max_upload_bytes = 53687091200 # largest upload (50 GiB) | ||
| 41 | +# link_max_days = 365 # longest share link | ||
| 42 | + | ||
| 34 | # Optional scheduled backups (a snapshot plus a blob manifest). Omit this table to disable them. | 43 | # Optional scheduled backups (a snapshot plus a blob manifest). Omit this table to disable them. |
| 35 | # [backup] | 44 | # [backup] |
| 36 | # dir = "data/backups" | 45 | # dir = "data/backups" |
crates/in-core/src/backup.rsadded+403 -0
| @@ -0,0 +1,403 @@ | |||
| 1 | +//! Backup sets and restore. | ||
| 2 | +//! | ||
| 3 | +//! A set is a directory `set-<stamp>` under the backup root, made of `in.db` (a consistent snapshot of the | ||
| 4 | +//! database, see `store/snapshot.rs`) and `manifest.json`. The manifest names the snapshot with its size | ||
| 5 | +//! and SHA-256, and lists every blob with its size and SHA-256. Blob bytes are not copied: the blob tree | ||
| 6 | +//! stays where it is, and the manifest is how a later check knows what should be there. A set is written | ||
| 7 | +//! under a temporary name and renamed into place only when its manifest is complete, so a half-written | ||
| 8 | +//! set is never mistaken for a good one. | ||
| 9 | +//! | ||
| 10 | +//! Restore verifies before it changes anything: the manifest format, the snapshot's size and hash, and | ||
| 11 | +//! the snapshot's `integrity_check` on a scratch copy. Only then does it move the current database aside | ||
| 12 | +//! (into `data_dir/restore-<stamp>/`, not deleted) and put the snapshot in its place. It only replaces a | ||
| 13 | +//! database that lies inside the data directory. Restore must run with the server stopped; the CLI takes | ||
| 14 | +//! the data-directory lock first. | ||
| 15 | + | ||
| 16 | +use std::fs::OpenOptions; | ||
| 17 | +use std::io::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::blob::{self, BlobStore}; | ||
| 26 | +use crate::error::{Error, Result}; | ||
| 27 | +use crate::store::{Store, 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 file inside a set. | ||
| 32 | +pub const DB_FILE: &str = "in.db"; | ||
| 33 | +/// Name of the manifest file inside a set. | ||
| 34 | +pub const MANIFEST_FILE: &str = "manifest.json"; | ||
| 35 | +/// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix. | ||
| 36 | +pub const SET_PREFIX: &str = "set-"; | ||
| 37 | + | ||
| 38 | +/// The snapshot entry of a manifest. | ||
| 39 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 40 | +pub struct DbEntry { | ||
| 41 | + /// File name inside the set. Always [`DB_FILE`]. | ||
| 42 | + pub file: String, | ||
| 43 | + /// Size in bytes. | ||
| 44 | + pub size: u64, | ||
| 45 | + /// Lower-case hex SHA-256 of the file. | ||
| 46 | + pub sha256: String, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// One blob entry of a manifest. | ||
| 50 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 51 | +pub struct BlobRecord { | ||
| 52 | + /// The blob key. | ||
| 53 | + pub key: String, | ||
| 54 | + /// Size in bytes. | ||
| 55 | + pub size: u64, | ||
| 56 | + /// Lower-case hex SHA-256 of the bytes. | ||
| 57 | + pub sha256: String, | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +/// The manifest of a set. | ||
| 61 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 62 | +pub struct Manifest { | ||
| 63 | + /// Format number; see [`FORMAT`]. | ||
| 64 | + pub format: u32, | ||
| 65 | + /// When the set was written, UTC. | ||
| 66 | + pub created_at: String, | ||
| 67 | + /// The snapshot. | ||
| 68 | + pub database: DbEntry, | ||
| 69 | + /// Every blob that existed when the set was written. | ||
| 70 | + pub blobs: Vec<BlobRecord>, | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// What a restore did. | ||
| 74 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 75 | +pub struct RestoreOutcome { | ||
| 76 | + /// Blobs the manifest lists. | ||
| 77 | + pub blobs_listed: usize, | ||
| 78 | + /// Blobs the manifest lists that are not in the blob tree now (for example, deleted after the set). | ||
| 79 | + pub blobs_missing: usize, | ||
| 80 | + /// Where the database it replaced was moved to, if there was one. | ||
| 81 | + pub previous: Option<PathBuf>, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// Creates a directory that only this user may enter. | ||
| 85 | +fn private_dir(path: &Path) -> Result<()> { | ||
| 86 | + std::fs::DirBuilder::new() | ||
| 87 | + .mode(0o700) | ||
| 88 | + .create(path) | ||
| 89 | + .map_err(Error::from) | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +/// Writes a complete set under `root` and returns its directory. `stamp` names it, and must be safe in a | ||
| 93 | +/// file name: callers pass a time stamp with `:` and `.` replaced. | ||
| 94 | +pub async fn write_set( | ||
| 95 | + store: &Store, | ||
| 96 | + blobs: &dyn BlobStore, | ||
| 97 | + root: &Path, | ||
| 98 | + stamp: &str, | ||
| 99 | +) -> Result<PathBuf> { | ||
| 100 | + std::fs::create_dir_all(root)?; | ||
| 101 | + let tmp = root.join(format!(".tmp-{stamp}")); | ||
| 102 | + let final_dir = root.join(format!("{SET_PREFIX}{stamp}")); | ||
| 103 | + if std::fs::symlink_metadata(&final_dir).is_ok() { | ||
| 104 | + return Err(Error::Conflict(format!("set {stamp} already exists"))); | ||
| 105 | + } | ||
| 106 | + private_dir(&tmp)?; | ||
| 107 | + let outcome = write_into(store, blobs, &tmp).await; | ||
| 108 | + match outcome { | ||
| 109 | + Ok(()) => { | ||
| 110 | + std::fs::rename(&tmp, &final_dir)?; | ||
| 111 | + Ok(final_dir) | ||
| 112 | + } | ||
| 113 | + Err(error) => { | ||
| 114 | + // A failed set is removed whole; it is ours, and it was never a complete set. | ||
| 115 | + let _ = std::fs::remove_dir_all(&tmp); | ||
| 116 | + Err(error) | ||
| 117 | + } | ||
| 118 | + } | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// Fills `dir` with the snapshot and the manifest, then fsyncs the directory. | ||
| 122 | +async fn write_into(store: &Store, blobs: &dyn BlobStore, dir: &Path) -> Result<()> { | ||
| 123 | + let db_path = dir.join(DB_FILE); | ||
| 124 | + store.snapshot_to(&db_path).await?; | ||
| 125 | + let (db_size, db_sha) = file_digest(&db_path)?; | ||
| 126 | + let mut records = Vec::new(); | ||
| 127 | + for (key, _, _) in blobs.list("").await? { | ||
| 128 | + // A blob deleted between the listing and the read is not part of the set, so `None` is skipped. | ||
| 129 | + if let Some((size, sha256)) = blob::digest(blobs, &key).await? { | ||
| 130 | + records.push(BlobRecord { key, size, sha256 }); | ||
| 131 | + } | ||
| 132 | + } | ||
| 133 | + let manifest = Manifest { | ||
| 134 | + format: FORMAT, | ||
| 135 | + created_at: crate::time::now_stamp(), | ||
| 136 | + database: DbEntry { | ||
| 137 | + file: DB_FILE.to_owned(), | ||
| 138 | + size: db_size, | ||
| 139 | + sha256: db_sha, | ||
| 140 | + }, | ||
| 141 | + blobs: records, | ||
| 142 | + }; | ||
| 143 | + let text = serde_json::to_string_pretty(&manifest) | ||
| 144 | + .map_err(|e| Error::Invalid(format!("manifest: {e}")))?; | ||
| 145 | + let mut file = OpenOptions::new() | ||
| 146 | + .write(true) | ||
| 147 | + .create_new(true) | ||
| 148 | + .mode(0o600) | ||
| 149 | + .open(dir.join(MANIFEST_FILE))?; | ||
| 150 | + file.write_all(text.as_bytes())?; | ||
| 151 | + file.sync_all()?; | ||
| 152 | + std::fs::File::open(dir)?.sync_all()?; | ||
| 153 | + Ok(()) | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// Size and SHA-256 of a file, read in chunks. | ||
| 157 | +fn file_digest(path: &Path) -> Result<(u64, String)> { | ||
| 158 | + let mut file = std::fs::File::open(path)?; | ||
| 159 | + let mut hasher = Sha256::new(); | ||
| 160 | + let mut size = 0u64; | ||
| 161 | + let mut buf = vec![0u8; 1 << 20]; | ||
| 162 | + loop { | ||
| 163 | + let n = std::io::Read::read(&mut file, &mut buf)?; | ||
| 164 | + if n == 0 { | ||
| 165 | + break; | ||
| 166 | + } | ||
| 167 | + size += n as u64; | ||
| 168 | + hasher.update(&buf[..n]); | ||
| 169 | + } | ||
| 170 | + Ok((size, hex::encode(hasher.finalize()))) | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// Removes the oldest sets under `root` until `keep` remain. Only real directories (not links) named | ||
| 174 | +/// `set-*` that hold a manifest file are touched, so a wrong `root` cannot cost unrelated data. | ||
| 175 | +/// Returns how many were removed. | ||
| 176 | +pub fn prune(root: &Path, keep: usize) -> Result<usize> { | ||
| 177 | + let is_set = |p: &Path| { | ||
| 178 | + let named = p | ||
| 179 | + .file_name() | ||
| 180 | + .and_then(|n| n.to_str()) | ||
| 181 | + .is_some_and(|n| n.starts_with(SET_PREFIX)); | ||
| 182 | + let real_dir = std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_dir()); | ||
| 183 | + let manifest = | ||
| 184 | + std::fs::symlink_metadata(p.join(MANIFEST_FILE)).is_ok_and(|m| m.file_type().is_file()); | ||
| 185 | + named && real_dir && manifest | ||
| 186 | + }; | ||
| 187 | + let mut sets: Vec<PathBuf> = match std::fs::read_dir(root) { | ||
| 188 | + Ok(entries) => entries | ||
| 189 | + .filter_map(|e| e.ok().map(|e| e.path())) | ||
| 190 | + .filter(|p| is_set(p)) | ||
| 191 | + .collect(), | ||
| 192 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0), | ||
| 193 | + Err(e) => return Err(e.into()), | ||
| 194 | + }; | ||
| 195 | + // Names carry fixed-width UTC stamps, so name order is time order. | ||
| 196 | + sets.sort(); | ||
| 197 | + let excess = sets.len().saturating_sub(keep); | ||
| 198 | + for old in sets.iter().take(excess) { | ||
| 199 | + std::fs::remove_dir_all(old)?; | ||
| 200 | + } | ||
| 201 | + Ok(excess) | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +/// Reads and checks the manifest of a set: parses it, and refuses a format it does not know or a snapshot | ||
| 205 | +/// name that is not [`DB_FILE`]. | ||
| 206 | +pub fn read_manifest(set: &Path) -> Result<Manifest> { | ||
| 207 | + let text = std::fs::read_to_string(set.join(MANIFEST_FILE)) | ||
| 208 | + .map_err(|_| Error::Invalid("backup_manifest_missing".into()))?; | ||
| 209 | + let manifest: Manifest = | ||
| 210 | + serde_json::from_str(&text).map_err(|_| Error::Invalid("backup_manifest_bad".into()))?; | ||
| 211 | + if manifest.format != FORMAT || manifest.database.file != DB_FILE { | ||
| 212 | + return Err(Error::Invalid("backup_manifest_bad".into())); | ||
| 213 | + } | ||
| 214 | + Ok(manifest) | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +/// Restores the database from `set` into `database`, which must lie inside `data_dir`. Verifies the | ||
| 218 | +/// manifest, the snapshot's size and hash, and its integrity before replacing anything. The previous | ||
| 219 | +/// database, with its sidecar files, is moved into `data_dir/restore-<stamp>/`. | ||
| 220 | +pub async fn restore( | ||
| 221 | + data_dir: &Path, | ||
| 222 | + database: &Path, | ||
| 223 | + set: &Path, | ||
| 224 | + blobs: &dyn BlobStore, | ||
| 225 | + stamp: &str, | ||
| 226 | +) -> Result<RestoreOutcome> { | ||
| 227 | + let manifest = read_manifest(set)?; | ||
| 228 | + let source = set.join(DB_FILE); | ||
| 229 | + let (size, sha256) = | ||
| 230 | + file_digest(&source).map_err(|_| Error::Invalid("backup_snapshot_missing".into()))?; | ||
| 231 | + if size != manifest.database.size || sha256 != manifest.database.sha256 { | ||
| 232 | + return Err(Error::Invalid("backup_hash".into())); | ||
| 233 | + } | ||
| 234 | + | ||
| 235 | + let data_dir = std::fs::canonicalize(data_dir)?; | ||
| 236 | + let parent = database | ||
| 237 | + .parent() | ||
| 238 | + .filter(|p| !p.as_os_str().is_empty()) | ||
| 239 | + .unwrap_or(Path::new(".")); | ||
| 240 | + let parent = std::fs::canonicalize(parent)?; | ||
| 241 | + if !parent.starts_with(&data_dir) { | ||
| 242 | + return Err(Error::Config( | ||
| 243 | + "restore only replaces a database inside data_dir".into(), | ||
| 244 | + )); | ||
| 245 | + } | ||
| 246 | + | ||
| 247 | + // The scratch copy lives in the data directory's temp area and is checked before it is used. | ||
| 248 | + let scratch_dir = data_dir.join(crate::staging::TMP_DIR); | ||
| 249 | + std::fs::create_dir_all(&scratch_dir)?; | ||
| 250 | + let scratch = scratch_dir.join(format!("restore-{stamp}.db")); | ||
| 251 | + std::fs::copy(&source, &scratch)?; | ||
| 252 | + let check = integrity_of(&scratch).await; | ||
| 253 | + remove_sidecars(&scratch)?; | ||
| 254 | + std::fs::remove_file(&scratch)?; | ||
| 255 | + match check? { | ||
| 256 | + true => {} | ||
| 257 | + false => return Err(Error::Invalid("backup_integrity".into())), | ||
| 258 | + } | ||
| 259 | + | ||
| 260 | + // Keep the database we replace: move it aside, then move the verified copy into place. | ||
| 261 | + let previous = if database.exists() { | ||
| 262 | + let keep_dir = data_dir.join(format!("restore-{stamp}")); | ||
| 263 | + private_dir(&keep_dir)?; | ||
| 264 | + let kept = keep_dir.join(DB_FILE); | ||
| 265 | + std::fs::rename(database, &kept)?; | ||
| 266 | + for suffix in ["-wal", "-shm"] { | ||
| 267 | + let side = sidecar(database, suffix); | ||
| 268 | + if side.exists() { | ||
| 269 | + std::fs::rename(&side, sidecar(&kept, suffix))?; | ||
| 270 | + } | ||
| 271 | + } | ||
| 272 | + Some(kept) | ||
| 273 | + } else { | ||
| 274 | + None | ||
| 275 | + }; | ||
| 276 | + let staged = scratch_dir.join(format!("restore-{stamp}-final.db")); | ||
| 277 | + std::fs::copy(&source, &staged)?; | ||
| 278 | + std::fs::rename(&staged, database)?; | ||
| 279 | + std::fs::File::open(&parent)?.sync_all()?; | ||
| 280 | + | ||
| 281 | + let mut missing = 0usize; | ||
| 282 | + for record in &manifest.blobs { | ||
| 283 | + if blobs.size(&record.key).await?.is_none() { | ||
| 284 | + missing += 1; | ||
| 285 | + } | ||
| 286 | + } | ||
| 287 | + Ok(RestoreOutcome { | ||
| 288 | + blobs_listed: manifest.blobs.len(), | ||
| 289 | + blobs_missing: missing, | ||
| 290 | + previous, | ||
| 291 | + }) | ||
| 292 | +} | ||
| 293 | + | ||
| 294 | +/// Whether the database at `path` passes `PRAGMA integrity_check`. Opening it may create sidecar files, | ||
| 295 | +/// which the caller removes. | ||
| 296 | +async fn integrity_of(path: &Path) -> Result<bool> { | ||
| 297 | + let text = path | ||
| 298 | + .to_str() | ||
| 299 | + .ok_or_else(|| Error::Config("scratch path is not UTF-8".into()))?; | ||
| 300 | + let db = Builder::new_local(text).build().await.map_err(db_err)?; | ||
| 301 | + let conn = db.connect().map_err(db_err)?; | ||
| 302 | + let rows = fetch_all(&conn, "PRAGMA integrity_check", (), |row| col_text(row, 0)).await?; | ||
| 303 | + Ok(rows == ["ok"]) | ||
| 304 | +} | ||
| 305 | + | ||
| 306 | +/// The path of a database's `-wal` or `-shm` sidecar. | ||
| 307 | +fn sidecar(path: &Path, suffix: &str) -> PathBuf { | ||
| 308 | + let mut name = path.as_os_str().to_owned(); | ||
| 309 | + name.push(suffix); | ||
| 310 | + PathBuf::from(name) | ||
| 311 | +} | ||
| 312 | + | ||
| 313 | +/// Removes the sidecars of a scratch file that this module created. | ||
| 314 | +fn remove_sidecars(path: &Path) -> Result<()> { | ||
| 315 | + for suffix in ["-wal", "-shm"] { | ||
| 316 | + let side = sidecar(path, suffix); | ||
| 317 | + if side.exists() { | ||
| 318 | + std::fs::remove_file(side)?; | ||
| 319 | + } | ||
| 320 | + } | ||
| 321 | + Ok(()) | ||
| 322 | +} | ||
| 323 | + | ||
| 324 | +#[cfg(test)] | ||
| 325 | +mod tests { | ||
| 326 | + use super::*; | ||
| 327 | + use crate::blob::local::LocalBlobs; | ||
| 328 | + use crate::store::test_support::store_with_member; | ||
| 329 | + | ||
| 330 | + /// A store with one setting and one blob, a backup set of it, and the blob store. | ||
| 331 | + async fn source_with_set() -> (tempfile::TempDir, Store, LocalBlobs, PathBuf) { | ||
| 332 | + let (dir, store) = store_with_member("ann").await; | ||
| 333 | + store.set_setting("probe", "kept").await.unwrap(); | ||
| 334 | + let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); | ||
| 335 | + let src = dir.path().join("src.bin"); | ||
| 336 | + std::fs::write(&src, b"bytes").unwrap(); | ||
| 337 | + blobs.put_file("files/ab/one", &src).await.unwrap(); | ||
| 338 | + let root = dir.path().join("backups"); | ||
| 339 | + let set = write_set(&store, &blobs, &root, "2026-10-28T00-00-00-000000000Z") | ||
| 340 | + .await | ||
| 341 | + .unwrap(); | ||
| 342 | + (dir, store, blobs, set) | ||
| 343 | + } | ||
| 344 | + | ||
| 345 | + #[tokio::test] | ||
| 346 | + async fn restore_refuses_a_manifest_with_a_wrong_hash() { | ||
| 347 | + let (dir, _store, blobs, set) = source_with_set().await; | ||
| 348 | + let manifest_path = set.join(MANIFEST_FILE); | ||
| 349 | + let mut manifest = read_manifest(&set).unwrap(); | ||
| 350 | + manifest.database.sha256 = "0".repeat(64); | ||
| 351 | + std::fs::write(&manifest_path, serde_json::to_string(&manifest).unwrap()).unwrap(); | ||
| 352 | + | ||
| 353 | + let data = dir.path().join("data"); | ||
| 354 | + std::fs::create_dir_all(&data).unwrap(); | ||
| 355 | + let database = data.join("in.db"); | ||
| 356 | + let refused = restore(&data, &database, &set, &blobs, "20261028T000000Z").await; | ||
| 357 | + assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_hash")); | ||
| 358 | + assert!( | ||
| 359 | + !database.exists(), | ||
| 360 | + "nothing is written when verification fails" | ||
| 361 | + ); | ||
| 362 | + } | ||
| 363 | + | ||
| 364 | + #[tokio::test] | ||
| 365 | + async fn restore_replaces_the_database_and_keeps_the_old_one() { | ||
| 366 | + let (dir, store, blobs, set) = source_with_set().await; | ||
| 367 | + drop(store); | ||
| 368 | + let data = dir.path().join("data"); | ||
| 369 | + std::fs::create_dir_all(&data).unwrap(); | ||
| 370 | + let database = data.join("in.db"); | ||
| 371 | + std::fs::write(&database, b"not a database").unwrap(); | ||
| 372 | + | ||
| 373 | + let outcome = restore(&data, &database, &set, &blobs, "20261028T000001Z") | ||
| 374 | + .await | ||
| 375 | + .unwrap(); | ||
| 376 | + assert_eq!(outcome.blobs_listed, 1); | ||
| 377 | + assert_eq!(outcome.blobs_missing, 0); | ||
| 378 | + assert!(outcome.previous.unwrap().exists()); | ||
| 379 | + let restored = Store::open(&database).await.unwrap(); | ||
| 380 | + assert_eq!( | ||
| 381 | + restored.get_setting("probe").await.unwrap().as_deref(), | ||
| 382 | + Some("kept") | ||
| 383 | + ); | ||
| 384 | + } | ||
| 385 | + | ||
| 386 | + #[test] | ||
| 387 | + fn prune_keeps_the_newest_sets_and_leaves_other_directories_alone() { | ||
| 388 | + let dir = tempfile::tempdir().unwrap(); | ||
| 389 | + for stamp in ["a", "b", "c"] { | ||
| 390 | + let set = dir.path().join(format!("{SET_PREFIX}{stamp}")); | ||
| 391 | + std::fs::create_dir(&set).unwrap(); | ||
| 392 | + std::fs::write(set.join(MANIFEST_FILE), "{}").unwrap(); | ||
| 393 | + } | ||
| 394 | + std::fs::create_dir(dir.path().join("keep-me")).unwrap(); | ||
| 395 | + // Named like a set but holding no manifest: not ours, never removed. | ||
| 396 | + std::fs::create_dir(dir.path().join("set-0-not-a-backup")).unwrap(); | ||
| 397 | + assert_eq!(prune(dir.path(), 2).unwrap(), 1); | ||
| 398 | + assert!(dir.path().join("set-0-not-a-backup").exists()); | ||
| 399 | + assert!(!dir.path().join("set-a").exists()); | ||
| 400 | + assert!(dir.path().join("set-c").exists()); | ||
| 401 | + assert!(dir.path().join("keep-me").exists()); | ||
| 402 | + } | ||
| 403 | +} | ||
crates/in-core/src/blob/mod.rsmodified+26 -0
| @@ -73,6 +73,32 @@ pub fn validate_key(key: &str) -> Result<()> { | |||
| 73 | Ok(()) | 73 | Ok(()) |
| 74 | } | 74 | } |
| 75 | 75 | ||
| 76 | +/// The size and lower-case hex SHA-256 of the blob at `key`, read frame by frame. `None` when the key is | ||
| 77 | +/// absent. Used by `fsck`, the backup manifest and the export, so no caller buffers a whole file. | ||
| 78 | +pub async fn digest(blobs: &dyn BlobStore, key: &str) -> Result<Option<(u64, String)>> { | ||
| 79 | + use futures_util::StreamExt; | ||
| 80 | + use sha2::{Digest, Sha256}; | ||
| 81 | + | ||
| 82 | + let Some(size) = blobs.size(key).await? else { | ||
| 83 | + return Ok(None); | ||
| 84 | + }; | ||
| 85 | + let mut stream = blobs.open_range(key, 0, size).await?; | ||
| 86 | + let mut hasher = Sha256::new(); | ||
| 87 | + let mut seen = 0u64; | ||
| 88 | + while let Some(frame) = stream.next().await { | ||
| 89 | + let frame = frame?; | ||
| 90 | + seen += frame.len() as u64; | ||
| 91 | + hasher.update(&frame); | ||
| 92 | + } | ||
| 93 | + if seen != size { | ||
| 94 | + return Err(Error::Io(std::io::Error::new( | ||
| 95 | + std::io::ErrorKind::UnexpectedEof, | ||
| 96 | + format!("blob {key} is {seen} bytes, expected {size}"), | ||
| 97 | + ))); | ||
| 98 | + } | ||
| 99 | + Ok(Some((size, hex::encode(hasher.finalize())))) | ||
| 100 | +} | ||
| 101 | + | ||
| 76 | /// Splits a buffer into frames of at most [`FRAME_BYTES`]. Shared by both backends. | 102 | /// Splits a buffer into frames of at most [`FRAME_BYTES`]. Shared by both backends. |
| 77 | pub(crate) fn frames(bytes: Bytes) -> impl Iterator<Item = Bytes> { | 103 | pub(crate) fn frames(bytes: Bytes) -> impl Iterator<Item = Bytes> { |
| 78 | (0..bytes.len()) | 104 | (0..bytes.len()) |
crates/in-core/src/config.rsmodified+21 -0
| @@ -35,6 +35,8 @@ pub struct Config { | |||
| 35 | pub storage: Storage, | 35 | pub storage: Storage, |
| 36 | /// Scheduled backups. Absent means no scheduled backups. | 36 | /// Scheduled backups. Absent means no scheduled backups. |
| 37 | pub backup: Option<Backup>, | 37 | pub backup: Option<Backup>, |
| 38 | + /// Defaults the admin page may override at run time. See `settings.rs` for the precedence rule. | ||
| 39 | + pub limits: Limits, | ||
| 38 | } | 40 | } |
| 39 | 41 | ||
| 40 | impl Default for Config { | 42 | impl Default for Config { |
| @@ -48,6 +50,7 @@ impl Default for Config { | |||
| 48 | oidc: None, | 50 | oidc: None, |
| 49 | storage: Storage::default(), | 51 | storage: Storage::default(), |
| 50 | backup: None, | 52 | backup: None, |
| 53 | + limits: Limits::default(), | ||
| 51 | } | 54 | } |
| 52 | } | 55 | } |
| 53 | } | 56 | } |
| @@ -64,6 +67,23 @@ pub struct Oidc { | |||
| 64 | pub client_secret_file: PathBuf, | 67 | pub client_secret_file: PathBuf, |
| 65 | } | 68 | } |
| 66 | 69 | ||
| 70 | +/// The `[limits]` table: file-level values of the settings the admin page can override. A value that is | ||
| 71 | +/// absent here falls back to the built-in default. Each one is checked by `settings::check_file`. | ||
| 72 | +#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)] | ||
| 73 | +#[serde(deny_unknown_fields, default)] | ||
| 74 | +pub struct Limits { | ||
| 75 | + /// Quota of a person who first appears, in bytes. | ||
| 76 | + pub default_quota_bytes: Option<i64>, | ||
| 77 | + /// Quota of a service namespace that makes its first call, in bytes. | ||
| 78 | + pub default_service_quota_bytes: Option<i64>, | ||
| 79 | + /// Days a trashed item waits before it is purged. | ||
| 80 | + pub purge_after_days: Option<i64>, | ||
| 81 | + /// Largest upload accepted, in bytes. | ||
| 82 | + pub max_upload_bytes: Option<i64>, | ||
| 83 | + /// Longest a share link may last, in days. | ||
| 84 | + pub link_max_days: Option<i64>, | ||
| 85 | +} | ||
| 86 | + | ||
| 67 | /// The `[storage]` table. | 87 | /// The `[storage]` table. |
| 68 | #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)] | 88 | #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)] |
| 69 | #[serde(deny_unknown_fields, default)] | 89 | #[serde(deny_unknown_fields, default)] |
| @@ -170,6 +190,7 @@ impl Config { | |||
| 170 | } | 190 | } |
| 171 | } | 191 | } |
| 172 | self.storage.validate()?; | 192 | self.storage.validate()?; |
| 193 | + crate::settings::check_file(&self.limits)?; | ||
| 173 | if let Some(backup) = &self.backup { | 194 | if let Some(backup) = &self.backup { |
| 174 | backup.validate()?; | 195 | backup.validate()?; |
| 175 | } | 196 | } |
crates/in-core/src/export.rsadded+246 -0
| @@ -0,0 +1,246 @@ | |||
| 1 | +//! `in export --member <sub> --out <dir>`: copies one person's live files into a plain folder tree. | ||
| 2 | +//! | ||
| 3 | +//! The tree uses the names people gave their folders and files, so it needs no `in` to read. Every | ||
| 4 | +//! destination is built from one sanitized name per path component, so no name can climb out of the | ||
| 5 | +//! output directory: a separator or control character becomes `_`, and `.` and `..` are never used as | ||
| 6 | +//! a name. Each file is created with `create_new`, so an existing file or a planted symlink is never | ||
| 7 | +//! written through. Bytes are hashed while they are copied and checked against the database row; a | ||
| 8 | +//! mismatch removes the partial file and is reported. Trashed items are not exported. | ||
| 9 | + | ||
| 10 | +use std::io::Write; | ||
| 11 | +use std::path::{Path, PathBuf}; | ||
| 12 | + | ||
| 13 | +use futures_util::StreamExt; | ||
| 14 | +use sha2::{Digest, Sha256}; | ||
| 15 | + | ||
| 16 | +use crate::blob::BlobStore; | ||
| 17 | +use crate::error::{Error, Result}; | ||
| 18 | +use crate::names; | ||
| 19 | +use crate::store::Store; | ||
| 20 | +use crate::store::folders::Folder; | ||
| 21 | + | ||
| 22 | +/// Longest name written, in bytes. Longer names are cut at a character boundary. | ||
| 23 | +const MAX_NAME_BYTES: usize = 200; | ||
| 24 | + | ||
| 25 | +/// What an export wrote, and what it could not. | ||
| 26 | +#[derive(Debug, Default, Clone, PartialEq, Eq)] | ||
| 27 | +pub struct ExportReport { | ||
| 28 | + /// Folders created. | ||
| 29 | + pub folders: u64, | ||
| 30 | + /// Files written and verified. | ||
| 31 | + pub files: u64, | ||
| 32 | + /// Bytes written. | ||
| 33 | + pub bytes: u64, | ||
| 34 | + /// Files whose bytes did not match their row, or whose blob was missing. Each is named. | ||
| 35 | + pub failed: Vec<String>, | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// One path component made safe to write: no separators, no control characters, not `.` or `..`, not empty, | ||
| 39 | +/// and at most [`MAX_NAME_BYTES`] bytes. The result is always a single component. | ||
| 40 | +pub fn safe_component(name: &str) -> String { | ||
| 41 | + let replaced: String = name | ||
| 42 | + .chars() | ||
| 43 | + .map(|c| { | ||
| 44 | + if c == '/' || c == '\\' || c.is_control() { | ||
| 45 | + '_' | ||
| 46 | + } else { | ||
| 47 | + c | ||
| 48 | + } | ||
| 49 | + }) | ||
| 50 | + .collect(); | ||
| 51 | + let trimmed = replaced.trim(); | ||
| 52 | + let mut out = match trimmed { | ||
| 53 | + "" => "Untitled".to_owned(), | ||
| 54 | + "." | ".." => format!("_{trimmed}"), | ||
| 55 | + other => other.to_owned(), | ||
| 56 | + }; | ||
| 57 | + while out.len() > MAX_NAME_BYTES { | ||
| 58 | + out.pop(); | ||
| 59 | + } | ||
| 60 | + out | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +/// A path under `dir` named `name` that does not exist yet. Clashes get ` (2)`, ` (3)` and so on before | ||
| 64 | +/// the extension, as the drive does. `is_file` tells the postfix rule where the extension starts. | ||
| 65 | +fn free_path(dir: &Path, name: &str, is_file: bool) -> Result<PathBuf> { | ||
| 66 | + let mut candidate = dir.join(name); | ||
| 67 | + let mut n = 2u32; | ||
| 68 | + while std::fs::symlink_metadata(&candidate).is_ok() { | ||
| 69 | + if n > crate::store::MAX_POSTFIX_TRIES { | ||
| 70 | + return Err(Error::Conflict("too_many_names".into())); | ||
| 71 | + } | ||
| 72 | + candidate = dir.join(safe_component(&names::postfix(name, n, is_file))); | ||
| 73 | + n += 1; | ||
| 74 | + } | ||
| 75 | + Ok(candidate) | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// Exports every live file and folder of `sub` under `out`. `out` is created if needed. Returns what was | ||
| 79 | +/// written. A failed file is reported, not fatal, so one bad blob does not stop the rest. | ||
| 80 | +pub async fn export_member( | ||
| 81 | + store: &Store, | ||
| 82 | + blobs: &dyn BlobStore, | ||
| 83 | + sub: &str, | ||
| 84 | + out: &Path, | ||
| 85 | +) -> Result<ExportReport> { | ||
| 86 | + std::fs::create_dir_all(out)?; | ||
| 87 | + let root = std::fs::canonicalize(out)?; | ||
| 88 | + let mut report = ExportReport::default(); | ||
| 89 | + // Work list of (folder id, the directory it goes into). | ||
| 90 | + let mut pending: Vec<(Option<String>, PathBuf)> = vec![(None, root.clone())]; | ||
| 91 | + while let Some((folder, dir)) = pending.pop() { | ||
| 92 | + let listing = store.list_children(sub, folder.as_deref()).await?; | ||
| 93 | + for Folder { id, name, .. } in listing.folders { | ||
| 94 | + let path = free_path(&dir, &safe_component(&name), false)?; | ||
| 95 | + std::fs::create_dir(&path)?; | ||
| 96 | + ensure_inside(&root, &path)?; | ||
| 97 | + report.folders += 1; | ||
| 98 | + pending.push((Some(id), path)); | ||
| 99 | + } | ||
| 100 | + for file in listing.files { | ||
| 101 | + let path = free_path(&dir, &safe_component(&file.name), true)?; | ||
| 102 | + ensure_inside(&root, &path)?; | ||
| 103 | + match copy_file(blobs, &file.blob_key, &file.sha256, file.size, &path).await { | ||
| 104 | + Ok(bytes) => { | ||
| 105 | + report.files += 1; | ||
| 106 | + report.bytes += bytes; | ||
| 107 | + } | ||
| 108 | + Err(reason) => { | ||
| 109 | + tracing::warn!(file = %file.id, reason = %reason, "export: a file did not verify"); | ||
| 110 | + report.failed.push(file.id.clone()); | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | + Ok(report) | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +/// Refuses a destination that is not inside the output directory. Every path is built from safe | ||
| 119 | +/// components, so this is a second, independent check. | ||
| 120 | +fn ensure_inside(root: &Path, path: &Path) -> Result<()> { | ||
| 121 | + let parent = path | ||
| 122 | + .parent() | ||
| 123 | + .ok_or_else(|| Error::Invalid("export_path".into()))?; | ||
| 124 | + let parent = std::fs::canonicalize(parent)?; | ||
| 125 | + if !parent.starts_with(root) { | ||
| 126 | + return Err(Error::Forbidden("export_path".into())); | ||
| 127 | + } | ||
| 128 | + Ok(()) | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +/// Copies one blob to a new file at `path` and checks its size and hash. Returns the bytes written, or | ||
| 132 | +/// the reason it failed (the file is then removed). | ||
| 133 | +async fn copy_file( | ||
| 134 | + blobs: &dyn BlobStore, | ||
| 135 | + key: &str, | ||
| 136 | + sha256: &str, | ||
| 137 | + size: i64, | ||
| 138 | + path: &Path, | ||
| 139 | +) -> std::result::Result<u64, String> { | ||
| 140 | + let size = u64::try_from(size).map_err(|_| "negative size".to_owned())?; | ||
| 141 | + let stored = blobs | ||
| 142 | + .size(key) | ||
| 143 | + .await | ||
| 144 | + .map_err(|e| e.to_string())? | ||
| 145 | + .ok_or_else(|| "blob missing".to_owned())?; | ||
| 146 | + if stored != size { | ||
| 147 | + return Err("blob size differs from the row".into()); | ||
| 148 | + } | ||
| 149 | + let mut file = std::fs::OpenOptions::new() | ||
| 150 | + .write(true) | ||
| 151 | + .create_new(true) | ||
| 152 | + .open(path) | ||
| 153 | + .map_err(|e| e.to_string())?; | ||
| 154 | + let outcome = write_verified(blobs, key, size, sha256, &mut file).await; | ||
| 155 | + match outcome { | ||
| 156 | + Ok(()) => { | ||
| 157 | + file.sync_all().map_err(|e| e.to_string())?; | ||
| 158 | + Ok(size) | ||
| 159 | + } | ||
| 160 | + Err(reason) => { | ||
| 161 | + drop(file); | ||
| 162 | + // The file was created by this call, so removing it touches nothing else. | ||
| 163 | + let _ = std::fs::remove_file(path); | ||
| 164 | + Err(reason) | ||
| 165 | + } | ||
| 166 | + } | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +/// Streams the blob into `file` while hashing it, and fails when the hash differs from `sha256`. | ||
| 170 | +async fn write_verified( | ||
| 171 | + blobs: &dyn BlobStore, | ||
| 172 | + key: &str, | ||
| 173 | + size: u64, | ||
| 174 | + sha256: &str, | ||
| 175 | + file: &mut std::fs::File, | ||
| 176 | +) -> std::result::Result<(), String> { | ||
| 177 | + let mut stream = blobs | ||
| 178 | + .open_range(key, 0, size) | ||
| 179 | + .await | ||
| 180 | + .map_err(|e| e.to_string())?; | ||
| 181 | + let mut hasher = Sha256::new(); | ||
| 182 | + while let Some(frame) = stream.next().await { | ||
| 183 | + let frame = frame.map_err(|e| e.to_string())?; | ||
| 184 | + hasher.update(&frame); | ||
| 185 | + file.write_all(&frame).map_err(|e| e.to_string())?; | ||
| 186 | + } | ||
| 187 | + if hex::encode(hasher.finalize()) != sha256 { | ||
| 188 | + return Err("hash differs from the row".into()); | ||
| 189 | + } | ||
| 190 | + Ok(()) | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +#[cfg(test)] | ||
| 194 | +mod tests { | ||
| 195 | + use super::*; | ||
| 196 | + use crate::blob::local::LocalBlobs; | ||
| 197 | + use crate::store::files::{NewFile, files_blob_key}; | ||
| 198 | + use crate::store::test_support::store_with_member; | ||
| 199 | + | ||
| 200 | + #[test] | ||
| 201 | + fn components_never_contain_separators_or_dot_names() { | ||
| 202 | + assert_eq!(safe_component("../../evil"), ".._.._evil"); | ||
| 203 | + assert_eq!(safe_component(".."), "_.."); | ||
| 204 | + assert_eq!(safe_component("."), "_."); | ||
| 205 | + assert_eq!(safe_component(""), "Untitled"); | ||
| 206 | + assert_eq!(safe_component("a\0b\nc"), "a_b_c"); | ||
| 207 | + assert!(!safe_component("x/y\\z").contains(['/', '\\'])); | ||
| 208 | + assert!(safe_component(&"é".repeat(300)).len() <= MAX_NAME_BYTES); | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + #[tokio::test] | ||
| 212 | + async fn export_never_writes_outside_the_output_directory() { | ||
| 213 | + let (dir, store) = store_with_member("ann").await; | ||
| 214 | + let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); | ||
| 215 | + let src = dir.path().join("src.bin"); | ||
| 216 | + std::fs::write(&src, b"hello").unwrap(); | ||
| 217 | + let id = "01hzexportfile0000000000001".to_owned(); | ||
| 218 | + blobs.put_file(&files_blob_key(&id), &src).await.unwrap(); | ||
| 219 | + let sha = hex::encode(Sha256::digest(b"hello")); | ||
| 220 | + store | ||
| 221 | + .insert_file(NewFile { | ||
| 222 | + id, | ||
| 223 | + owner: "ann".into(), | ||
| 224 | + folder: None, | ||
| 225 | + name: "../../evil".into(), | ||
| 226 | + mime: "text/plain".into(), | ||
| 227 | + size: 5, | ||
| 228 | + sha256: sha, | ||
| 229 | + staged_claims: 0, | ||
| 230 | + }) | ||
| 231 | + .await | ||
| 232 | + .unwrap(); | ||
| 233 | + | ||
| 234 | + let out = dir.path().join("out"); | ||
| 235 | + let report = export_member(&store, &blobs, "ann", &out).await.unwrap(); | ||
| 236 | + assert_eq!(report.files, 1); | ||
| 237 | + assert!(report.failed.is_empty()); | ||
| 238 | + // The drive's name rules already reduced `../../evil` to `evil`; the export must keep it inside `out`. | ||
| 239 | + assert!(!dir.path().join("evil").exists()); | ||
| 240 | + let written: Vec<_> = std::fs::read_dir(&out) | ||
| 241 | + .unwrap() | ||
| 242 | + .map(|e| e.unwrap().file_name()) | ||
| 243 | + .collect(); | ||
| 244 | + assert_eq!(written, vec![std::ffi::OsString::from("evil")]); | ||
| 245 | + } | ||
| 246 | +} | ||
crates/in-core/src/fsck.rsadded+183 -0
| @@ -0,0 +1,183 @@ | |||
| 1 | +//! `in fsck`: checks that the database and the blob tree agree, and reports what does not. | ||
| 2 | +//! | ||
| 3 | +//! It reads only. Every row that names a blob (a file's bytes, a ready thumbnail, an object's bytes) must | ||
| 4 | +//! find a blob of the recorded size; with `verify_hash` the bytes are also hashed and compared with the | ||
| 5 | +//! row's SHA-256. A blob that no row names is an orphan, which is reported and never removed here: the | ||
| 6 | +//! sweeper decides about orphans, and only after they are a day old. `PRAGMA integrity_check` runs first. | ||
| 7 | +//! The run needs the server stopped, because the database must not change under it. | ||
| 8 | + | ||
| 9 | +use std::collections::HashSet; | ||
| 10 | + | ||
| 11 | +use crate::blob::{self, BlobStore}; | ||
| 12 | +use crate::error::Result; | ||
| 13 | +use crate::store::files::thumb_blob_key; | ||
| 14 | +use crate::store::{Store, col_int, col_text, fetch_all}; | ||
| 15 | + | ||
| 16 | +/// How many keys of each kind the report lists. The counts are always exact. | ||
| 17 | +const LISTED: usize = 50; | ||
| 18 | + | ||
| 19 | +/// What `fsck` found. | ||
| 20 | +#[derive(Debug, Default, Clone, PartialEq, Eq)] | ||
| 21 | +pub struct Report { | ||
| 22 | + /// Result of `PRAGMA integrity_check`, joined by newlines. `ok` when the database is sound. | ||
| 23 | + pub integrity: String, | ||
| 24 | + /// Rows whose blob is absent (files, ready thumbnails and objects). | ||
| 25 | + pub rows_checked: u64, | ||
| 26 | + /// Keys of rows whose blob is missing, the first [`LISTED`]. | ||
| 27 | + pub missing: Vec<String>, | ||
| 28 | + /// Number of rows whose blob is missing. | ||
| 29 | + pub missing_count: u64, | ||
| 30 | + /// Keys whose blob size differs from the row. | ||
| 31 | + pub size_mismatch: Vec<String>, | ||
| 32 | + /// Keys whose bytes hash differently from the row (only with `verify_hash`). | ||
| 33 | + pub hash_mismatch: Vec<String>, | ||
| 34 | + /// Blobs that no row names, the first [`LISTED`]. | ||
| 35 | + pub orphans: Vec<String>, | ||
| 36 | + /// Number of orphan blobs. | ||
| 37 | + pub orphan_count: u64, | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +impl Report { | ||
| 41 | + /// True when the database is sound and every row has a blob of the right size (and hash, when it was | ||
| 42 | + /// checked). Orphans do not make a report unclean: they waste space but lose nothing. | ||
| 43 | + pub fn is_clean(&self) -> bool { | ||
| 44 | + self.integrity == "ok" | ||
| 45 | + && self.missing_count == 0 | ||
| 46 | + && self.size_mismatch.is_empty() | ||
| 47 | + && self.hash_mismatch.is_empty() | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// Runs the checks. `verify_hash` reads every blob, which can take a long time on a large store. | ||
| 52 | +pub async fn check(store: &Store, blobs: &dyn BlobStore, verify_hash: bool) -> Result<Report> { | ||
| 53 | + let mut report = Report { | ||
| 54 | + integrity: integrity(store).await?, | ||
| 55 | + ..Report::default() | ||
| 56 | + }; | ||
| 57 | + | ||
| 58 | + // Files: the bytes, and the thumbnail when it is ready. | ||
| 59 | + let files = store_rows( | ||
| 60 | + store, | ||
| 61 | + "SELECT id, blob_key, size, sha256, thumb_state FROM files", | ||
| 62 | + ) | ||
| 63 | + .await?; | ||
| 64 | + for (id, key, size, sha256, thumb_state) in files { | ||
| 65 | + check_blob(&mut report, blobs, &key, size, &sha256, verify_hash).await?; | ||
| 66 | + if thumb_state == "ready" { | ||
| 67 | + let thumb = thumb_blob_key(&id); | ||
| 68 | + if blobs.size(&thumb).await?.is_none() { | ||
| 69 | + note_missing(&mut report, &thumb); | ||
| 70 | + } | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + // Objects: the bytes of each object, under the service's key. | ||
| 75 | + let objects = store_rows( | ||
| 76 | + store, | ||
| 77 | + "SELECT service, blob_key, size, sha256, external_id FROM objects", | ||
| 78 | + ) | ||
| 79 | + .await?; | ||
| 80 | + for (_, key, size, sha256, _) in objects { | ||
| 81 | + check_blob(&mut report, blobs, &key, size, &sha256, verify_hash).await?; | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + // Orphans: blobs that no row names. | ||
| 85 | + let referenced: HashSet<String> = store.referenced_blob_keys().await?.into_iter().collect(); | ||
| 86 | + for (key, _, _) in blobs.list("").await? { | ||
| 87 | + if !referenced.contains(&key) { | ||
| 88 | + report.orphan_count += 1; | ||
| 89 | + if report.orphans.len() < LISTED { | ||
| 90 | + report.orphans.push(key); | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | + Ok(report) | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// Runs `PRAGMA integrity_check` and joins its rows. | ||
| 98 | +async fn integrity(store: &Store) -> Result<String> { | ||
| 99 | + let conn = store.read_conn().await; | ||
| 100 | + let rows = fetch_all(&conn, "PRAGMA integrity_check", (), |row| col_text(row, 0)).await?; | ||
| 101 | + Ok(rows.join("\n")) | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// Rows of text-and-number columns used by the checks: `(text, text, number, text, text)` in the order | ||
| 105 | +/// of the query. The caller names the columns it selects. | ||
| 106 | +async fn store_rows( | ||
| 107 | + store: &Store, | ||
| 108 | + sql: &str, | ||
| 109 | +) -> Result<Vec<(String, String, i64, String, String)>> { | ||
| 110 | + let conn = store.read_conn().await; | ||
| 111 | + fetch_all(&conn, sql, (), |row| { | ||
| 112 | + Ok(( | ||
| 113 | + col_text(row, 0)?, | ||
| 114 | + col_text(row, 1)?, | ||
| 115 | + col_int(row, 2)?, | ||
| 116 | + col_text(row, 3)?, | ||
| 117 | + col_text(row, 4)?, | ||
| 118 | + )) | ||
| 119 | + }) | ||
| 120 | + .await | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// Checks one row's blob: present, the recorded size, and with `verify_hash` the recorded hash. | ||
| 124 | +async fn check_blob( | ||
| 125 | + report: &mut Report, | ||
| 126 | + blobs: &dyn BlobStore, | ||
| 127 | + key: &str, | ||
| 128 | + size: i64, | ||
| 129 | + sha256: &str, | ||
| 130 | + verify_hash: bool, | ||
| 131 | +) -> Result<()> { | ||
| 132 | + report.rows_checked += 1; | ||
| 133 | + let Some(actual) = blobs.size(key).await? else { | ||
| 134 | + note_missing(report, key); | ||
| 135 | + return Ok(()); | ||
| 136 | + }; | ||
| 137 | + if i64::try_from(actual).ok() != Some(size) { | ||
| 138 | + report.size_mismatch.push(key.to_owned()); | ||
| 139 | + return Ok(()); | ||
| 140 | + } | ||
| 141 | + if verify_hash { | ||
| 142 | + match blob::digest(blobs, key).await? { | ||
| 143 | + Some((_, hash)) if hash == sha256 => {} | ||
| 144 | + Some(_) => report.hash_mismatch.push(key.to_owned()), | ||
| 145 | + None => note_missing(report, key), | ||
| 146 | + } | ||
| 147 | + } | ||
| 148 | + Ok(()) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// Records a missing blob: counted always, listed up to the limit. | ||
| 152 | +fn note_missing(report: &mut Report, key: &str) { | ||
| 153 | + report.missing_count += 1; | ||
| 154 | + if report.missing.len() < LISTED { | ||
| 155 | + report.missing.push(key.to_owned()); | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +#[cfg(test)] | ||
| 160 | +mod tests { | ||
| 161 | + use super::*; | ||
| 162 | + use crate::blob::local::LocalBlobs; | ||
| 163 | + use crate::store::test_support::store_with_member; | ||
| 164 | + | ||
| 165 | + #[tokio::test] | ||
| 166 | + async fn a_clean_store_is_clean_and_an_unnamed_blob_is_an_orphan() { | ||
| 167 | + let (dir, store) = store_with_member("ann").await; | ||
| 168 | + let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); | ||
| 169 | + let report = check(&store, &blobs, true).await.unwrap(); | ||
| 170 | + assert_eq!(report.integrity, "ok"); | ||
| 171 | + assert!(report.is_clean()); | ||
| 172 | + | ||
| 173 | + let stray = dir.path().join("stray.bin"); | ||
| 174 | + std::fs::write(&stray, b"nobody names me").unwrap(); | ||
| 175 | + blobs.put_file("files/zz/stray", &stray).await.unwrap(); | ||
| 176 | + let report = check(&store, &blobs, false).await.unwrap(); | ||
| 177 | + assert_eq!(report.orphan_count, 1); | ||
| 178 | + assert!( | ||
| 179 | + report.is_clean(), | ||
| 180 | + "orphans alone do not make a report unclean" | ||
| 181 | + ); | ||
| 182 | + } | ||
| 183 | +} | ||
crates/in-core/src/lib.rsmodified+4 -0
| @@ -3,13 +3,17 @@ | |||
| 3 | //! here serves HTTP; `in-web` builds on it. | 3 | //! here serves HTTP; `in-web` builds on it. |
| 4 | 4 | ||
| 5 | pub mod authz; | 5 | pub mod authz; |
| 6 | +pub mod backup; | ||
| 6 | pub mod blob; | 7 | pub mod blob; |
| 7 | pub mod config; | 8 | pub mod config; |
| 8 | pub mod error; | 9 | pub mod error; |
| 10 | +pub mod export; | ||
| 11 | +pub mod fsck; | ||
| 9 | pub mod names; | 12 | pub mod names; |
| 10 | pub mod password; | 13 | pub mod password; |
| 11 | pub mod quota; | 14 | pub mod quota; |
| 12 | pub mod secret; | 15 | pub mod secret; |
| 16 | +pub mod settings; | ||
| 13 | pub mod sniff; | 17 | pub mod sniff; |
| 14 | pub mod staging; | 18 | pub mod staging; |
| 15 | pub mod store; | 19 | pub mod store; |
crates/in-core/src/settings.rsadded+256 -0
| @@ -0,0 +1,256 @@ | |||
| 1 | +//! Runtime settings: the operator's values that change without a restart, and where each one comes from. | ||
| 2 | +//! | ||
| 3 | +//! The precedence is fixed: a UI override (a row of the `settings` table, written by the admin page), then | ||
| 4 | +//! the file (`[limits]` in the configuration), then the built-in default. [`resolve`] returns the value | ||
| 5 | +//! together with the layer it came from, so the admin page can show the source beside each value. Every | ||
| 6 | +//! caller reads through [`resolve`], so the rule is written once. Nothing here changes the database. | ||
| 7 | + | ||
| 8 | +use crate::config::Limits; | ||
| 9 | +use crate::error::{Error, Result}; | ||
| 10 | +use crate::quota::DEFAULT_MEMBER_QUOTA; | ||
| 11 | +use crate::store::Store; | ||
| 12 | +use crate::store::objects::DEFAULT_SERVICE_QUOTA; | ||
| 13 | + | ||
| 14 | +/// Settings key of the quota a new person gets, in bytes. | ||
| 15 | +pub const DEFAULT_QUOTA_KEY: &str = "default_quota_bytes"; | ||
| 16 | +/// Settings key of the quota a new service namespace gets, in bytes. | ||
| 17 | +pub const DEFAULT_SERVICE_QUOTA_KEY: &str = "default_service_quota_bytes"; | ||
| 18 | +/// Settings key of the days trash waits before a purge. | ||
| 19 | +pub const PURGE_KEY: &str = "purge_after_days"; | ||
| 20 | +/// Settings key of the largest upload, in bytes. | ||
| 21 | +pub const MAX_UPLOAD_KEY: &str = "max_upload_bytes"; | ||
| 22 | +/// Settings key of the longest share link, in days. | ||
| 23 | +pub const LINK_MAX_DAYS_KEY: &str = "link_max_days"; | ||
| 24 | + | ||
| 25 | +/// One GiB in bytes. | ||
| 26 | +const GIB: i64 = 1024 * 1024 * 1024; | ||
| 27 | +/// One MiB in bytes. | ||
| 28 | +const MIB: i64 = 1024 * 1024; | ||
| 29 | +/// One TiB in bytes: the upper bound of every byte value, far above any real quota. | ||
| 30 | +const TIB: i64 = 1024 * GIB; | ||
| 31 | + | ||
| 32 | +/// Default purge delay: 30 days. | ||
| 33 | +pub const DEFAULT_PURGE_AFTER_DAYS: i64 = 30; | ||
| 34 | +/// Default largest upload: 50 GiB. | ||
| 35 | +pub const DEFAULT_MAX_UPLOAD: i64 = 50 * GIB; | ||
| 36 | +/// Default longest share link: a year. | ||
| 37 | +pub const DEFAULT_LINK_MAX_DAYS: i64 = 365; | ||
| 38 | + | ||
| 39 | +/// How a field may change. Shown on the admin page next to the value. | ||
| 40 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 41 | +pub enum Mode { | ||
| 42 | + /// The next request that reads the value uses the new one. | ||
| 43 | + Live, | ||
| 44 | + /// Takes effect after a restart of the process. | ||
| 45 | + Restart, | ||
| 46 | + /// Set in the file only, and shown but not editable. | ||
| 47 | + ReadOnly, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// The layer a value came from. | ||
| 51 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 52 | +pub enum Source { | ||
| 53 | + /// Set on the admin page. | ||
| 54 | + Ui, | ||
| 55 | + /// Set in the configuration file. | ||
| 56 | + File, | ||
| 57 | + /// The built-in default. | ||
| 58 | + Default, | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// A value and the layer it came from. | ||
| 62 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 63 | +pub struct Resolved { | ||
| 64 | + /// The value in the field's unit. | ||
| 65 | + pub value: i64, | ||
| 66 | + /// Which layer supplied it. | ||
| 67 | + pub source: Source, | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// One field the admin page can show or change: its key, default, the bounds a value must meet, and its | ||
| 71 | +/// mode. Byte fields are in bytes and day fields in days. | ||
| 72 | +#[derive(Debug)] | ||
| 73 | +pub struct Field { | ||
| 74 | + /// The settings key, also the key in the file's `[limits]` table. | ||
| 75 | + pub key: &'static str, | ||
| 76 | + /// The built-in default. | ||
| 77 | + pub default: i64, | ||
| 78 | + /// Smallest value accepted. | ||
| 79 | + pub min: i64, | ||
| 80 | + /// Largest value accepted. | ||
| 81 | + pub max: i64, | ||
| 82 | + /// How the value may change. | ||
| 83 | + pub mode: Mode, | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// Every field of the admin page's defaults section, in display order. | ||
| 87 | +pub const FIELDS: [Field; 5] = [ | ||
| 88 | + Field { | ||
| 89 | + key: DEFAULT_QUOTA_KEY, | ||
| 90 | + default: DEFAULT_MEMBER_QUOTA, | ||
| 91 | + min: 0, | ||
| 92 | + max: TIB, | ||
| 93 | + mode: Mode::Live, | ||
| 94 | + }, | ||
| 95 | + Field { | ||
| 96 | + key: DEFAULT_SERVICE_QUOTA_KEY, | ||
| 97 | + default: DEFAULT_SERVICE_QUOTA, | ||
| 98 | + min: 0, | ||
| 99 | + max: TIB, | ||
| 100 | + mode: Mode::Live, | ||
| 101 | + }, | ||
| 102 | + Field { | ||
| 103 | + key: PURGE_KEY, | ||
| 104 | + default: DEFAULT_PURGE_AFTER_DAYS, | ||
| 105 | + min: 1, | ||
| 106 | + max: 3650, | ||
| 107 | + mode: Mode::Live, | ||
| 108 | + }, | ||
| 109 | + Field { | ||
| 110 | + key: MAX_UPLOAD_KEY, | ||
| 111 | + default: DEFAULT_MAX_UPLOAD, | ||
| 112 | + min: MIB, | ||
| 113 | + max: TIB, | ||
| 114 | + mode: Mode::Live, | ||
| 115 | + }, | ||
| 116 | + Field { | ||
| 117 | + key: LINK_MAX_DAYS_KEY, | ||
| 118 | + default: DEFAULT_LINK_MAX_DAYS, | ||
| 119 | + min: 1, | ||
| 120 | + max: 3650, | ||
| 121 | + mode: Mode::Live, | ||
| 122 | + }, | ||
| 123 | +]; | ||
| 124 | + | ||
| 125 | +/// The field with this key, if it is one of [`FIELDS`]. | ||
| 126 | +pub fn field(key: &str) -> Option<&'static Field> { | ||
| 127 | + FIELDS.iter().find(|field| field.key == key) | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +/// The file value of `key`, when the `[limits]` table sets it. | ||
| 131 | +pub fn file_value(limits: &Limits, key: &str) -> Option<i64> { | ||
| 132 | + match key { | ||
| 133 | + DEFAULT_QUOTA_KEY => limits.default_quota_bytes, | ||
| 134 | + DEFAULT_SERVICE_QUOTA_KEY => limits.default_service_quota_bytes, | ||
| 135 | + PURGE_KEY => limits.purge_after_days, | ||
| 136 | + MAX_UPLOAD_KEY => limits.max_upload_bytes, | ||
| 137 | + LINK_MAX_DAYS_KEY => limits.link_max_days, | ||
| 138 | + _ => None, | ||
| 139 | + } | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// Checks a value against the field's bounds. The refusal word is the key with `_range`, which the | ||
| 143 | +/// admin page turns into a sentence. | ||
| 144 | +pub fn check(field: &Field, value: i64) -> Result<i64> { | ||
| 145 | + if value < field.min || value > field.max { | ||
| 146 | + return Err(Error::Invalid(format!("{}_range", field.key))); | ||
| 147 | + } | ||
| 148 | + Ok(value) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// Parses the text of an admin form for `key`. Blank means "no override": `Ok(None)`. Anything else | ||
| 152 | +/// must be an integer within the field's bounds. | ||
| 153 | +pub fn parse_ui(key: &str, text: &str) -> Result<Option<i64>> { | ||
| 154 | + let field = field(key).ok_or_else(|| Error::Invalid("unknown_setting".into()))?; | ||
| 155 | + let text = text.trim(); | ||
| 156 | + if text.is_empty() { | ||
| 157 | + return Ok(None); | ||
| 158 | + } | ||
| 159 | + let value: i64 = text | ||
| 160 | + .parse() | ||
| 161 | + .map_err(|_| Error::Invalid(format!("{}_range", field.key)))?; | ||
| 162 | + check(field, value).map(Some) | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/// Checks every value the file sets. Called by `Config::validate`, so a bad file fails at boot. | ||
| 166 | +pub fn check_file(limits: &Limits) -> Result<()> { | ||
| 167 | + for field in &FIELDS { | ||
| 168 | + if let Some(value) = file_value(limits, field.key) { | ||
| 169 | + check(field, value).map_err(|_| { | ||
| 170 | + Error::Config(format!( | ||
| 171 | + "limits.{} must be between {} and {}", | ||
| 172 | + field.key, field.min, field.max | ||
| 173 | + )) | ||
| 174 | + })?; | ||
| 175 | + } | ||
| 176 | + } | ||
| 177 | + Ok(()) | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// The effective value of `key`: the UI override when one is stored and valid, else the file value, else | ||
| 181 | +/// the default. A stored override that is out of bounds (possible only by hand-editing the database) is | ||
| 182 | +/// ignored and the next layer is used. | ||
| 183 | +pub async fn resolve(store: &Store, limits: &Limits, key: &str) -> Result<Resolved> { | ||
| 184 | + let field = field(key).ok_or_else(|| Error::Invalid("unknown_setting".into()))?; | ||
| 185 | + if let Some(text) = store.get_setting(key).await? | ||
| 186 | + && let Some(value) = text | ||
| 187 | + .trim() | ||
| 188 | + .parse::<i64>() | ||
| 189 | + .ok() | ||
| 190 | + .filter(|v| check(field, *v).is_ok()) | ||
| 191 | + { | ||
| 192 | + return Ok(Resolved { | ||
| 193 | + value, | ||
| 194 | + source: Source::Ui, | ||
| 195 | + }); | ||
| 196 | + } | ||
| 197 | + if let Some(value) = file_value(limits, key) { | ||
| 198 | + return Ok(Resolved { | ||
| 199 | + value, | ||
| 200 | + source: Source::File, | ||
| 201 | + }); | ||
| 202 | + } | ||
| 203 | + Ok(Resolved { | ||
| 204 | + value: field.default, | ||
| 205 | + source: Source::Default, | ||
| 206 | + }) | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +/// The word the admin page shows for a source: `ui`, `file` or `default`. The page translates it. | ||
| 210 | +pub fn source_word(source: Source) -> &'static str { | ||
| 211 | + match source { | ||
| 212 | + Source::Ui => "ui", | ||
| 213 | + Source::File => "file", | ||
| 214 | + Source::Default => "default", | ||
| 215 | + } | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +#[cfg(test)] | ||
| 219 | +mod tests { | ||
| 220 | + use super::*; | ||
| 221 | + use crate::store::Store; | ||
| 222 | + | ||
| 223 | + #[test] | ||
| 224 | + fn blank_clears_and_bounds_are_enforced() { | ||
| 225 | + assert_eq!(parse_ui(PURGE_KEY, " ").unwrap(), None); | ||
| 226 | + assert_eq!(parse_ui(PURGE_KEY, "30").unwrap(), Some(30)); | ||
| 227 | + assert!(parse_ui(PURGE_KEY, "0").is_err()); | ||
| 228 | + assert!(parse_ui(PURGE_KEY, "3651").is_err()); | ||
| 229 | + assert!(parse_ui(PURGE_KEY, "soon").is_err()); | ||
| 230 | + assert!(parse_ui("nope", "1").is_err()); | ||
| 231 | + } | ||
| 232 | + | ||
| 233 | + #[tokio::test] | ||
| 234 | + async fn ui_beats_file_beats_default() { | ||
| 235 | + let dir = tempfile::tempdir().unwrap(); | ||
| 236 | + let store = Store::open(&dir.path().join("in.db")).await.unwrap(); | ||
| 237 | + let limits = Limits { | ||
| 238 | + purge_after_days: Some(7), | ||
| 239 | + ..Limits::default() | ||
| 240 | + }; | ||
| 241 | + let from_file = resolve(&store, &limits, PURGE_KEY).await.unwrap(); | ||
| 242 | + assert_eq!(from_file.value, 7); | ||
| 243 | + assert_eq!(from_file.source, Source::File); | ||
| 244 | + | ||
| 245 | + store.set_setting(PURGE_KEY, "14").await.unwrap(); | ||
| 246 | + let from_ui = resolve(&store, &limits, PURGE_KEY).await.unwrap(); | ||
| 247 | + assert_eq!(from_ui.value, 14); | ||
| 248 | + assert_eq!(from_ui.source, Source::Ui); | ||
| 249 | + | ||
| 250 | + let default = resolve(&store, &Limits::default(), LINK_MAX_DAYS_KEY) | ||
| 251 | + .await | ||
| 252 | + .unwrap(); | ||
| 253 | + assert_eq!(default.value, DEFAULT_LINK_MAX_DAYS); | ||
| 254 | + assert_eq!(default.source, Source::Default); | ||
| 255 | + } | ||
| 256 | +} | ||
crates/in-core/src/store/audit.rsadded+164 -0
| @@ -0,0 +1,164 @@ | |||
| 1 | +//! The audit log: an append-only record of changes, written after the change commits. | ||
| 2 | +//! | ||
| 3 | +//! Rows are never updated or deleted here. Reads page by keyset on `(at, id)`, newest first, so a page | ||
| 4 | +//! does not shift when new rows arrive. `data` is JSON text that must never carry a secret; the writer | ||
| 5 | +//! in `in-web` is the only caller and it keeps that rule. | ||
| 6 | + | ||
| 7 | +use turso::Row; | ||
| 8 | + | ||
| 9 | +use crate::error::Result; | ||
| 10 | +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, new_id}; | ||
| 11 | +use crate::time::now_stamp; | ||
| 12 | + | ||
| 13 | +/// Column list for [`map_audit`]. Keep the two in step. | ||
| 14 | +const AUDIT_COLS: &str = "id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data"; | ||
| 15 | + | ||
| 16 | +/// One entry to append. | ||
| 17 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 18 | +pub struct NewAudit { | ||
| 19 | + /// The person, service or link that acted; `None` for the system. | ||
| 20 | + pub actor_id: Option<String>, | ||
| 21 | + /// `member`, `service`, `link` or `system`. | ||
| 22 | + pub actor_kind: &'static str, | ||
| 23 | + /// Dotted verb such as `quota.set`. | ||
| 24 | + pub action: String, | ||
| 25 | + /// What kind of thing changed, such as `member` or `setting`. | ||
| 26 | + pub target_kind: String, | ||
| 27 | + /// The changed thing's id, if it has one. | ||
| 28 | + pub target_id: Option<String>, | ||
| 29 | + /// Client address, when known. | ||
| 30 | + pub ip: Option<String>, | ||
| 31 | + /// JSON object text with the details. Never a secret. | ||
| 32 | + pub data: String, | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// One stored entry. | ||
| 36 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 37 | +pub struct AuditRow { | ||
| 38 | + /// Id (a lower-case ULID). | ||
| 39 | + pub id: String, | ||
| 40 | + /// When it was written, UTC. | ||
| 41 | + pub at: String, | ||
| 42 | + /// Who acted. | ||
| 43 | + pub actor_id: Option<String>, | ||
| 44 | + /// `member`, `service`, `link` or `system`. | ||
| 45 | + pub actor_kind: String, | ||
| 46 | + /// The verb. | ||
| 47 | + pub action: String, | ||
| 48 | + /// The kind of target. | ||
| 49 | + pub target_kind: String, | ||
| 50 | + /// The target's id. | ||
| 51 | + pub target_id: Option<String>, | ||
| 52 | + /// Client address. | ||
| 53 | + pub ip: Option<String>, | ||
| 54 | + /// The details as JSON text. | ||
| 55 | + pub data: String, | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// A page request: exact-match filters (empty means "any") and the keyset cursor of the last row seen. | ||
| 59 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 60 | +pub struct AuditQuery { | ||
| 61 | + /// Exact action, or empty. | ||
| 62 | + pub action: String, | ||
| 63 | + /// Exact actor id, or empty. | ||
| 64 | + pub actor_id: String, | ||
| 65 | + /// Exact target kind, or empty. | ||
| 66 | + pub target_kind: String, | ||
| 67 | + /// `(at, id)` of the last row of the previous page; `None` for the first page. | ||
| 68 | + pub before: Option<(String, String)>, | ||
| 69 | + /// Rows wanted. The caller asks for one more than it shows, to learn whether a next page exists. | ||
| 70 | + pub limit: usize, | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Maps a row selected with [`AUDIT_COLS`]. | ||
| 74 | +fn map_audit(row: &Row) -> Result<AuditRow> { | ||
| 75 | + Ok(AuditRow { | ||
| 76 | + id: col_text(row, 0)?, | ||
| 77 | + at: col_text(row, 1)?, | ||
| 78 | + actor_id: col_opt_text(row, 2)?, | ||
| 79 | + actor_kind: col_text(row, 3)?, | ||
| 80 | + action: col_text(row, 4)?, | ||
| 81 | + target_kind: col_text(row, 5)?, | ||
| 82 | + target_id: col_opt_text(row, 6)?, | ||
| 83 | + ip: col_opt_text(row, 7)?, | ||
| 84 | + data: col_text(row, 8)?, | ||
| 85 | + }) | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +impl Store { | ||
| 89 | + /// Appends one entry, stamped now. Uses the writer, so it is ordered with the writes around it. | ||
| 90 | + pub async fn insert_audit(&self, new: NewAudit) -> Result<AuditRow> { | ||
| 91 | + let row = AuditRow { | ||
| 92 | + id: new_id(), | ||
| 93 | + at: now_stamp(), | ||
| 94 | + actor_id: new.actor_id, | ||
| 95 | + actor_kind: new.actor_kind.to_owned(), | ||
| 96 | + action: new.action, | ||
| 97 | + target_kind: new.target_kind, | ||
| 98 | + target_id: new.target_id, | ||
| 99 | + ip: new.ip, | ||
| 100 | + data: new.data, | ||
| 101 | + }; | ||
| 102 | + let conn = self.inner.conn.lock().await; | ||
| 103 | + conn.execute( | ||
| 104 | + "INSERT INTO audit_log (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data) \ | ||
| 105 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | ||
| 106 | + ( | ||
| 107 | + row.id.clone(), | ||
| 108 | + row.at.clone(), | ||
| 109 | + row.actor_id.clone(), | ||
| 110 | + row.actor_kind.clone(), | ||
| 111 | + row.action.clone(), | ||
| 112 | + row.target_kind.clone(), | ||
| 113 | + row.target_id.clone(), | ||
| 114 | + row.ip.clone(), | ||
| 115 | + row.data.clone(), | ||
| 116 | + ), | ||
| 117 | + ) | ||
| 118 | + .await | ||
| 119 | + .map_err(db_err)?; | ||
| 120 | + Ok(row) | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + /// One page of the log, newest first, after the cursor in `query`. | ||
| 124 | + pub async fn audit_page(&self, query: &AuditQuery) -> Result<Vec<AuditRow>> { | ||
| 125 | + let conn = self.read_conn().await; | ||
| 126 | + let (before_at, before_id) = query.before.clone().unwrap_or_default(); | ||
| 127 | + let has_cursor = i64::from(query.before.is_some()); | ||
| 128 | + let limit = i64::try_from(query.limit).unwrap_or(i64::MAX); | ||
| 129 | + fetch_all( | ||
| 130 | + &conn, | ||
| 131 | + &format!( | ||
| 132 | + "SELECT {AUDIT_COLS} FROM audit_log \ | ||
| 133 | + WHERE (?1 = '' OR action = ?1) AND (?2 = '' OR actor_id = ?2) \ | ||
| 134 | + AND (?3 = '' OR target_kind = ?3) \ | ||
| 135 | + AND (?4 = 0 OR at < ?5 OR (at = ?5 AND id < ?6)) \ | ||
| 136 | + ORDER BY at DESC, id DESC LIMIT ?7" | ||
| 137 | + ), | ||
| 138 | + ( | ||
| 139 | + query.action.clone(), | ||
| 140 | + query.actor_id.clone(), | ||
| 141 | + query.target_kind.clone(), | ||
| 142 | + has_cursor, | ||
| 143 | + before_at, | ||
| 144 | + before_id, | ||
| 145 | + limit, | ||
| 146 | + ), | ||
| 147 | + map_audit, | ||
| 148 | + ) | ||
| 149 | + .await | ||
| 150 | + } | ||
| 151 | + | ||
| 152 | + /// The id of the newest entry, or `None` for an empty log. The live page uses it as its fingerprint. | ||
| 153 | + pub async fn latest_audit_id(&self) -> Result<Option<String>> { | ||
| 154 | + let conn = self.read_conn().await; | ||
| 155 | + let rows = fetch_all( | ||
| 156 | + &conn, | ||
| 157 | + "SELECT id FROM audit_log ORDER BY at DESC, id DESC LIMIT 1", | ||
| 158 | + (), | ||
| 159 | + |row| col_text(row, 0), | ||
| 160 | + ) | ||
| 161 | + .await?; | ||
| 162 | + Ok(rows.into_iter().next()) | ||
| 163 | + } | ||
| 164 | +} | ||
crates/in-core/src/store/members.rsmodified+20 -0
| @@ -298,6 +298,26 @@ impl Store { | |||
| 298 | finish(tx, outcome).await | 298 | finish(tx, outcome).await |
| 299 | } | 299 | } |
| 300 | 300 | ||
| 301 | + /// Sets or clears the language a person chose in `in`. `None` follows the language from `im`. Only | ||
| 302 | + /// `en` and `tr` are accepted. | ||
| 303 | + pub async fn set_locale_override(&self, sub: &str, locale: Option<&str>) -> Result<()> { | ||
| 304 | + if locale.is_some_and(|code| code != "en" && code != "tr") { | ||
| 305 | + return Err(Error::Invalid("bad_language".into())); | ||
| 306 | + } | ||
| 307 | + let conn = self.inner.conn.lock().await; | ||
| 308 | + let changed = conn | ||
| 309 | + .execute( | ||
| 310 | + "UPDATE members SET locale_override = ?2 WHERE sub = ?1", | ||
| 311 | + (sub.to_string(), locale.map(str::to_owned)), | ||
| 312 | + ) | ||
| 313 | + .await | ||
| 314 | + .map_err(db_err)?; | ||
| 315 | + if changed == 0 { | ||
| 316 | + return Err(Error::NotFound); | ||
| 317 | + } | ||
| 318 | + Ok(()) | ||
| 319 | + } | ||
| 320 | + | ||
| 301 | /// Sets a member's theme. Only `system`, `light` and `dark` are accepted. | 321 | /// Sets a member's theme. Only `system`, `light` and `dark` are accepted. |
| 302 | pub async fn set_theme(&self, sub: &str, theme: &str) -> Result<()> { | 322 | pub async fn set_theme(&self, sub: &str, theme: &str) -> Result<()> { |
| 303 | if !THEMES.contains(&theme) { | 323 | if !THEMES.contains(&theme) { |
crates/in-core/src/store/mod.rsmodified+1 -0
| @@ -4,6 +4,7 @@ | |||
| 4 | //! Every connection gets the same pragmas (WAL, `synchronous = FULL`, foreign keys, a 5 s busy | 4 | //! Every connection gets the same pragmas (WAL, `synchronous = FULL`, foreign keys, a 5 s busy |
| 5 | //! timeout). The helpers at the bottom of this file are shared by every table module. | 5 | //! timeout). The helpers at the bottom of this file are shared by every table module. |
| 6 | 6 | ||
| 7 | +pub mod audit; | ||
| 7 | pub mod files; | 8 | pub mod files; |
| 8 | pub mod folders; | 9 | pub mod folders; |
| 9 | pub mod links; | 10 | pub mod links; |
crates/in-core/src/store/objects.rsmodified+20 -0
| @@ -263,6 +263,26 @@ impl Store { | |||
| 263 | self.service(key).await?.ok_or_else(missing_row) | 263 | self.service(key).await?.ok_or_else(missing_row) |
| 264 | } | 264 | } |
| 265 | 265 | ||
| 266 | + /// Sets a service's quota in bytes. Lowering it below the current use is allowed: the service then | ||
| 267 | + /// cannot store more until it frees space. | ||
| 268 | + pub async fn set_service_quota(&self, key: &str, bytes: i64) -> Result<()> { | ||
| 269 | + if bytes < 0 { | ||
| 270 | + return Err(Error::Invalid("quota_negative".into())); | ||
| 271 | + } | ||
| 272 | + let conn = self.inner.conn.lock().await; | ||
| 273 | + let changed = conn | ||
| 274 | + .execute( | ||
| 275 | + "UPDATE services SET quota_bytes = ?2 WHERE key = ?1", | ||
| 276 | + (key.to_owned(), bytes), | ||
| 277 | + ) | ||
| 278 | + .await | ||
| 279 | + .map_err(db_err)?; | ||
| 280 | + if changed == 0 { | ||
| 281 | + return Err(Error::NotFound); | ||
| 282 | + } | ||
| 283 | + Ok(()) | ||
| 284 | + } | ||
| 285 | + | ||
| 266 | /// The usage of a service: quota, bytes used and the object count. A service that does not exist has | 286 | /// The usage of a service: quota, bytes used and the object count. A service that does not exist has |
| 267 | /// none, so the answer is `NotFound`. | 287 | /// none, so the answer is `NotFound`. |
| 268 | pub async fn service_usage(&self, service: &str) -> Result<Usage> { | 288 | pub async fn service_usage(&self, service: &str) -> Result<Usage> { |
crates/in-core/src/store/settings.rsmodified+9 -0
| @@ -19,6 +19,15 @@ impl Store { | |||
| 19 | .await | 19 | .await |
| 20 | } | 20 | } |
| 21 | 21 | ||
| 22 | + /// Removes the UI override of `key`, so the file value or the default applies again. | ||
| 23 | + pub async fn clear_setting(&self, key: &str) -> Result<()> { | ||
| 24 | + let conn = self.inner.conn.lock().await; | ||
| 25 | + conn.execute("DELETE FROM settings WHERE key = ?1", (key.to_string(),)) | ||
| 26 | + .await | ||
| 27 | + .map_err(db_err)?; | ||
| 28 | + Ok(()) | ||
| 29 | + } | ||
| 30 | + | ||
| 22 | /// Stores `value` for `key`, replacing any earlier value. | 31 | /// Stores `value` for `key`, replacing any earlier value. |
| 23 | pub async fn set_setting(&self, key: &str, value: &str) -> Result<()> { | 32 | pub async fn set_setting(&self, key: &str, value: &str) -> Result<()> { |
| 24 | let conn = self.inner.conn.lock().await; | 33 | let conn = self.inner.conn.lock().await; |
crates/in-web/Cargo.tomlmodified+2 -0
| @@ -12,6 +12,7 @@ path = "src/main.rs" | |||
| 12 | 12 | ||
| 13 | [dependencies] | 13 | [dependencies] |
| 14 | base64.workspace = true | 14 | base64.workspace = true |
| 15 | +clap.workspace = true | ||
| 15 | futures-util.workspace = true | 16 | futures-util.workspace = true |
| 16 | http.workspace = true | 17 | http.workspace = true |
| 17 | http-body.workspace = true | 18 | http-body.workspace = true |
| @@ -19,6 +20,7 @@ http-body-util.workspace = true | |||
| 19 | in-core.workspace = true | 20 | in-core.workspace = true |
| 20 | jsonwebtoken.workspace = true | 21 | jsonwebtoken.workspace = true |
| 21 | rand.workspace = true | 22 | rand.workspace = true |
| 23 | +rustix.workspace = true | ||
| 22 | reqwest.workspace = true | 24 | reqwest.workspace = true |
| 23 | serde = { workspace = true, features = ["derive"] } | 25 | serde = { workspace = true, features = ["derive"] } |
| 24 | serde_json.workspace = true | 26 | serde_json.workspace = true |
crates/in-web/src/api/machine_auth.rsmodified+7 -6
| @@ -21,7 +21,6 @@ | |||
| 21 | 21 | ||
| 22 | use http::header::{AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, WWW_AUTHENTICATE}; | 22 | use http::header::{AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, WWW_AUTHENTICATE}; |
| 23 | use http::{HeaderValue, StatusCode}; | 23 | use http::{HeaderValue, StatusCode}; |
| 24 | -use in_core::store::objects::{DEFAULT_SERVICE_QUOTA, SERVICE_QUOTA_SETTING}; | ||
| 25 | use serde_json::{Value, json}; | 24 | use serde_json::{Value, json}; |
| 26 | use topcoat::Result; | 25 | use topcoat::Result; |
| 27 | use topcoat::context::{Cx, app_context}; | 26 | use topcoat::context::{Cx, app_context}; |
| @@ -111,11 +110,13 @@ pub fn bearer_token(headers: &HeaderMap) -> Option<&str> { | |||
| 111 | /// The default quota of a new service: the `default_service_quota_bytes` setting when it holds a positive | 110 | /// The default quota of a new service: the `default_service_quota_bytes` setting when it holds a positive |
| 112 | /// number, else [`DEFAULT_SERVICE_QUOTA`]. | 111 | /// number, else [`DEFAULT_SERVICE_QUOTA`]. |
| 113 | async fn default_service_quota(state: &AppState) -> Result<i64> { | 112 | async fn default_service_quota(state: &AppState) -> Result<i64> { |
| 114 | - let setting = state.store.get_setting(SERVICE_QUOTA_SETTING).await?; | 113 | + let resolved = in_core::settings::resolve( |
| 115 | - Ok(setting | 114 | + &state.store, |
| 116 | - .and_then(|text| text.trim().parse::<i64>().ok()) | 115 | + &state.config.limits, |
| 117 | - .filter(|quota| *quota > 0) | 116 | + in_core::settings::DEFAULT_SERVICE_QUOTA_KEY, |
| 118 | - .unwrap_or(DEFAULT_SERVICE_QUOTA)) | 117 | + ) |
| 118 | + .await?; | ||
| 119 | + Ok(resolved.value) | ||
| 119 | } | 120 | } |
| 120 | 121 | ||
| 121 | /// Checks the bearer token of the request in `cx` and returns the caller, or the refusal to send. | 122 | /// Checks the bearer token of the request in `cx` and returns the caller, or the refusal to send. |
crates/in-web/src/api/upload.rsmodified+7 -14
| @@ -56,12 +56,6 @@ const CSRF_HEADER: &str = "x-csrf-token"; | |||
| 56 | /// How long an open upload may wait for its next chunk: 24 hours. Every chunk restarts the count. | 56 | /// How long an open upload may wait for its next chunk: 24 hours. Every chunk restarts the count. |
| 57 | pub const UPLOAD_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60); | 57 | pub const UPLOAD_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60); |
| 58 | 58 | ||
| 59 | -/// The default largest upload: 50 GiB. The `max_upload_bytes` setting overrides it. | ||
| 60 | -pub const DEFAULT_MAX_UPLOAD: u64 = 50 * 1024 * 1024 * 1024; | ||
| 61 | - | ||
| 62 | -/// The settings key of the largest upload, in bytes. | ||
| 63 | -pub const MAX_UPLOAD_SETTING: &str = "max_upload_bytes"; | ||
| 64 | - | ||
| 65 | /// Largest body the create route reads. Its JSON is a few hundred bytes. | 59 | /// Largest body the create route reads. Its JSON is a few hundred bytes. |
| 66 | const CREATE_BODY_LIMIT: usize = 4096; | 60 | const CREATE_BODY_LIMIT: usize = 4096; |
| 67 | 61 | ||
| @@ -138,14 +132,13 @@ async fn open_upload( | |||
| 138 | 132 | ||
| 139 | /// The largest upload the settings allow, in bytes. A stored value that is not a number is ignored. | 133 | /// The largest upload the settings allow, in bytes. A stored value that is not a number is ignored. |
| 140 | pub async fn max_upload_bytes(state: &AppState) -> Result<i64> { | 134 | pub async fn max_upload_bytes(state: &AppState) -> Result<i64> { |
| 141 | - let limit = state | 135 | + let resolved = in_core::settings::resolve( |
| 142 | - .store | 136 | + &state.store, |
| 143 | - .get_setting(MAX_UPLOAD_SETTING) | 137 | + &state.config.limits, |
| 144 | - .await? | 138 | + in_core::settings::MAX_UPLOAD_KEY, |
| 145 | - .and_then(|value| value.trim().parse::<u64>().ok()) | 139 | + ) |
| 146 | - .unwrap_or(DEFAULT_MAX_UPLOAD) | 140 | + .await?; |
| 147 | - .clamp(1, i64::MAX as u64); | 141 | + Ok(resolved.value.max(1)) |
| 148 | - Ok(i64::try_from(limit).unwrap_or(i64::MAX)) | ||
| 149 | } | 142 | } |
| 150 | 143 | ||
| 151 | /// The indexes of the chunks that are on disk. A missing directory has none. | 144 | /// The indexes of the chunks that are on disk. A missing directory has none. |
crates/in-web/src/audit.rsadded+50 -0
| @@ -0,0 +1,50 @@ | |||
| 1 | +//! The audit writer of the web layer: appends one entry for each admin write, after the change commits. | ||
| 2 | +//! | ||
| 3 | +//! A failed append is logged and never fails the request that made the change, because the change has | ||
| 4 | +//! already happened and the person asking should not see an error for it. A successful append wakes the | ||
| 5 | +//! open admin pages. `data` is built by the callers from ids and values only; secrets never go in it. | ||
| 6 | + | ||
| 7 | +use in_core::store::audit::NewAudit; | ||
| 8 | + | ||
| 9 | +use crate::live::Topic; | ||
| 10 | +use crate::state::AppState; | ||
| 11 | + | ||
| 12 | +/// What one audit entry records: who acted, what they did, and to what. | ||
| 13 | +pub struct Entry<'a> { | ||
| 14 | + /// The acting person's sub, or `None` for the system. | ||
| 15 | + pub actor: Option<&'a str>, | ||
| 16 | + /// Dotted verb, such as `quota.set`. | ||
| 17 | + pub action: &'a str, | ||
| 18 | + /// Kind of the changed thing, such as `member`. | ||
| 19 | + pub target_kind: &'a str, | ||
| 20 | + /// Id of the changed thing. | ||
| 21 | + pub target_id: Option<&'a str>, | ||
| 22 | + /// Details as a JSON object. Never a secret. | ||
| 23 | + pub data: serde_json::Value, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// Appends `entry`. Never fails: a failure is logged with the verb, and the caller carries on. | ||
| 27 | +pub async fn record(state: &AppState, entry: Entry<'_>) { | ||
| 28 | + let data = entry.data.to_string(); | ||
| 29 | + let new = NewAudit { | ||
| 30 | + actor_id: entry.actor.map(str::to_owned), | ||
| 31 | + actor_kind: if entry.actor.is_some() { | ||
| 32 | + "member" | ||
| 33 | + } else { | ||
| 34 | + "system" | ||
| 35 | + }, | ||
| 36 | + action: entry.action.to_owned(), | ||
| 37 | + target_kind: entry.target_kind.to_owned(), | ||
| 38 | + target_id: entry.target_id.map(str::to_owned), | ||
| 39 | + ip: None, | ||
| 40 | + data, | ||
| 41 | + }; | ||
| 42 | + match state.store.insert_audit(new).await { | ||
| 43 | + Ok(_) => state.live.bump(&Topic::AdminAudit), | ||
| 44 | + Err(error) => tracing::error!( | ||
| 45 | + action = entry.action, | ||
| 46 | + error = %error, | ||
| 47 | + "audit: an entry could not be written; the change itself stands" | ||
| 48 | + ), | ||
| 49 | + } | ||
| 50 | +} | ||
crates/in-web/src/auth.rsmodified+10 -2
| @@ -154,7 +154,6 @@ pub async fn require_member(cx: &Cx) -> Result<Viewer> { | |||
| 154 | 154 | ||
| 155 | /// A signed-in administrator. A signed-in member who is not one gets `404`, so the admin pages do not | 155 | /// A signed-in administrator. A signed-in member who is not one gets `404`, so the admin pages do not |
| 156 | /// reveal that they exist. | 156 | /// reveal that they exist. |
| 157 | -#[allow(dead_code)] // The admin pages that come next are the first callers. | ||
| 158 | pub async fn require_admin(cx: &Cx) -> Result<Viewer> { | 157 | pub async fn require_admin(cx: &Cx) -> Result<Viewer> { |
| 159 | let viewer = require_member(cx).await?; | 158 | let viewer = require_member(cx).await?; |
| 160 | if !viewer.member.is_admin { | 159 | if !viewer.member.is_admin { |
| @@ -170,9 +169,18 @@ pub fn csrf_matches(session: &Session, submitted: &str) -> bool { | |||
| 170 | && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) | 169 | && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) |
| 171 | } | 170 | } |
| 172 | 171 | ||
| 172 | +/// The signed-in administrator, after the CSRF check of an admin form. A member who is not an administrator | ||
| 173 | +/// gets `404` before the token is looked at, so the admin forms do not reveal themselves either. | ||
| 174 | +pub async fn require_admin_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> { | ||
| 175 | + let viewer = require_admin(cx).await?; | ||
| 176 | + if !csrf_matches(&viewer.session, submitted) { | ||
| 177 | + return Err(forbidden().into()); | ||
| 178 | + } | ||
| 179 | + Ok(viewer) | ||
| 180 | +} | ||
| 181 | + | ||
| 173 | /// The signed-in person, after the CSRF check of a state-changing form. A missing session redirects to | 182 | /// The signed-in person, after the CSRF check of a state-changing form. A missing session redirects to |
| 174 | /// sign-in; a wrong or missing token is `403`. Run it before any side effect. | 183 | /// sign-in; a wrong or missing token is `403`. Run it before any side effect. |
| 175 | -#[allow(dead_code)] // The first state-changing form that is not logout calls it. | ||
| 176 | pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> { | 184 | pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> { |
| 177 | let viewer = require_member(cx).await?; | 185 | let viewer = require_member(cx).await?; |
| 178 | if !csrf_matches(&viewer.session, submitted) { | 186 | if !csrf_matches(&viewer.session, submitted) { |
crates/in-web/src/backup.rsadded+68 -0
| @@ -0,0 +1,68 @@ | |||
| 1 | +//! The scheduled backup worker: writes a backup set (snapshot and blob manifest, see `in-core` `backup.rs`) | ||
| 2 | +//! every `interval_hours`, keeps the newest `keep` sets, and pings the dead-man URL after each good run. | ||
| 3 | +//! | ||
| 4 | +//! A failed run is logged and the next one is tried at the next interval; a failed ping is logged and nothing | ||
| 5 | +//! else. The ping URL carries a secret, so it is never logged. The worker is not started without a `[backup]` | ||
| 6 | +//! table. | ||
| 7 | + | ||
| 8 | +use std::time::Duration; | ||
| 9 | + | ||
| 10 | +use in_core::backup; | ||
| 11 | +use in_core::config::Backup; | ||
| 12 | +use in_core::time::now_stamp; | ||
| 13 | +use tokio::sync::watch; | ||
| 14 | + | ||
| 15 | +use crate::state::AppState; | ||
| 16 | + | ||
| 17 | +/// How long the dead-man ping may take. | ||
| 18 | +pub const PING_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 19 | + | ||
| 20 | +/// Runs one backup now and returns the new set's directory. | ||
| 21 | +async fn run_once(state: &AppState, config: &Backup) -> in_core::error::Result<std::path::PathBuf> { | ||
| 22 | + // The stamp names the set; `:` and `.` are not wanted in file names. | ||
| 23 | + let stamp = now_stamp().replace([':', '.'], "-"); | ||
| 24 | + let set = backup::write_set(&state.store, state.blobs.as_ref(), &config.dir, &stamp).await?; | ||
| 25 | + let removed = backup::prune(&config.dir, config.keep as usize)?; | ||
| 26 | + tracing::info!(set = %set.display(), pruned = removed, "backup: set written"); | ||
| 27 | + Ok(set) | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/// Pings the dead-man URL once. Only failures are logged, and the URL itself never is. | ||
| 31 | +async fn ping(url: &str) { | ||
| 32 | + let client = match reqwest::Client::builder().timeout(PING_TIMEOUT).build() { | ||
| 33 | + Ok(client) => client, | ||
| 34 | + Err(error) => { | ||
| 35 | + tracing::warn!(error = %error, "backup: could not prepare the dead-man ping"); | ||
| 36 | + return; | ||
| 37 | + } | ||
| 38 | + }; | ||
| 39 | + match client.get(url).send().await { | ||
| 40 | + Ok(response) if response.status().is_success() => {} | ||
| 41 | + Ok(response) => { | ||
| 42 | + tracing::warn!(status = %response.status(), "backup: dead-man ping was not accepted") | ||
| 43 | + } | ||
| 44 | + Err(error) => tracing::warn!(error = %error.without_url(), "backup: dead-man ping failed"), | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// Runs backups every interval until the stop flag is set. The first run happens at start-up. | ||
| 49 | +pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) { | ||
| 50 | + let Some(config) = state.config.backup.clone() else { | ||
| 51 | + return; | ||
| 52 | + }; | ||
| 53 | + let every = Duration::from_secs(u64::from(config.interval_hours) * 60 * 60); | ||
| 54 | + loop { | ||
| 55 | + match run_once(&state, &config).await { | ||
| 56 | + Ok(_) => { | ||
| 57 | + if let Some(url) = &config.healthcheck_url { | ||
| 58 | + ping(url).await; | ||
| 59 | + } | ||
| 60 | + } | ||
| 61 | + Err(error) => tracing::error!(error = %error, "backup: the run failed"), | ||
| 62 | + } | ||
| 63 | + tokio::select! { | ||
| 64 | + _ = stop.wait_for(|stopped| *stopped) => return, | ||
| 65 | + () = tokio::time::sleep(every) => {} | ||
| 66 | + } | ||
| 67 | + } | ||
| 68 | +} | ||
crates/in-web/src/boot.rsmodified+69 -2
| @@ -6,7 +6,7 @@ | |||
| 6 | //! the listener, and serve until SIGTERM or Ctrl-C. Stored UI overrides are not layered on the file | 6 | //! the listener, and serve until SIGTERM or Ctrl-C. Stored UI overrides are not layered on the file |
| 7 | //! yet, because no page writes them. | 7 | //! yet, because no page writes them. |
| 8 | 8 | ||
| 9 | -use std::os::unix::fs::PermissionsExt; | 9 | +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; |
| 10 | use std::path::Path; | 10 | use std::path::Path; |
| 11 | use std::sync::Arc; | 11 | use std::sync::Arc; |
| 12 | 12 | ||
| @@ -23,7 +23,10 @@ use tokio::sync::watch; | |||
| 23 | use topcoat::cookie::RouterBuilderCookieExt; | 23 | use topcoat::cookie::RouterBuilderCookieExt; |
| 24 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; | 24 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; |
| 25 | 25 | ||
| 26 | +use crate::backup; | ||
| 26 | use crate::directory; | 27 | use crate::directory; |
| 28 | +use crate::family; | ||
| 29 | +use crate::family::FamilyCache; | ||
| 27 | use crate::live::LiveHub; | 30 | use crate::live::LiveHub; |
| 28 | use crate::oidc::OidcClient; | 31 | use crate::oidc::OidcClient; |
| 29 | use crate::pages::files; | 32 | use crate::pages::files; |
| @@ -37,18 +40,80 @@ use crate::thumbs_worker; | |||
| 37 | /// Name of the instance key file inside the data directory. | 40 | /// Name of the instance key file inside the data directory. |
| 38 | const KEY_FILE: &str = "in.key"; | 41 | const KEY_FILE: &str = "in.key"; |
| 39 | 42 | ||
| 43 | +/// Name of the lock file inside the data directory. A running server holds it; the operator commands take it | ||
| 44 | +/// too, so they refuse to run beside a server. | ||
| 45 | +const LOCK_FILE: &str = "in.lock"; | ||
| 46 | + | ||
| 40 | /// Directory under the data directory that holds the local blob tree. | 47 | /// Directory under the data directory that holds the local blob tree. |
| 41 | -const BLOB_DIR: &str = "blobs"; | 48 | +pub const BLOB_DIR: &str = "blobs"; |
| 49 | + | ||
| 50 | +/// Takes the data directory's lock. The file is created with mode 0600 inside the 0700 directory. The lock | ||
| 51 | +/// is held for as long as the returned file lives; a second holder gets a conflict that says what to do. | ||
| 52 | +pub fn lock_data_dir(data_dir: &Path) -> Result<std::fs::File> { | ||
| 53 | + std::fs::create_dir_all(data_dir)?; | ||
| 54 | + std::fs::set_permissions(data_dir, std::fs::Permissions::from_mode(0o700))?; | ||
| 55 | + let file = std::fs::OpenOptions::new() | ||
| 56 | + .create(true) | ||
| 57 | + .truncate(false) | ||
| 58 | + .write(true) | ||
| 59 | + .mode(0o600) | ||
| 60 | + .open(data_dir.join(LOCK_FILE))?; | ||
| 61 | + match file.try_lock() { | ||
| 62 | + Ok(()) => Ok(file), | ||
| 63 | + Err(std::fs::TryLockError::WouldBlock) => Err(Error::Conflict( | ||
| 64 | + "in is running on this data directory. Stop the server first, then run the command again.".into(), | ||
| 65 | + )), | ||
| 66 | + Err(std::fs::TryLockError::Error(error)) => Err(error.into()), | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// What an operator command needs: the configuration, the database, the blob store, and the lock that keeps a | ||
| 71 | +/// server out. Opened without the OpenID client, so the commands run even when `im` is not configured. | ||
| 72 | +pub struct Offline { | ||
| 73 | + /// The database. | ||
| 74 | + pub store: Store, | ||
| 75 | + /// The blob store the configuration names. | ||
| 76 | + pub blobs: Arc<dyn BlobStore>, | ||
| 77 | + /// The data-directory lock. Dropping it lets a server start again. | ||
| 78 | + _lock: std::fs::File, | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// Opens an [`Offline`] view of the instance. Refuses while a server holds the lock. | ||
| 82 | +pub async fn open_offline(config_path: &Path) -> Result<Offline> { | ||
| 83 | + let config = Config::load(config_path)?; | ||
| 84 | + let lock = lock_data_dir(&config.data_dir)?; | ||
| 85 | + let data_dir = config.data_dir.canonicalize()?; | ||
| 86 | + if let Some(parent) = config | ||
| 87 | + .database | ||
| 88 | + .parent() | ||
| 89 | + .filter(|p| !p.as_os_str().is_empty()) | ||
| 90 | + { | ||
| 91 | + std::fs::create_dir_all(parent)?; | ||
| 92 | + } | ||
| 93 | + let store = Store::open(&config.database).await?; | ||
| 94 | + let blobs = open_blobs(&config, &data_dir)?; | ||
| 95 | + Ok(Offline { | ||
| 96 | + store, | ||
| 97 | + blobs, | ||
| 98 | + _lock: lock, | ||
| 99 | + }) | ||
| 100 | +} | ||
| 42 | 101 | ||
| 43 | /// Runs the server until a stop signal arrives. Returns once every connection has finished. | 102 | /// Runs the server until a stop signal arrives. Returns once every connection has finished. |
| 44 | pub async fn serve(config_path: &Path) -> Result<()> { | 103 | pub async fn serve(config_path: &Path) -> Result<()> { |
| 45 | let config = Config::load(config_path)?; | 104 | let config = Config::load(config_path)?; |
| 46 | let listen = config.listen; | 105 | let listen = config.listen; |
| 106 | + // Held until the server stops: an operator command started now refuses instead of racing the server. | ||
| 107 | + let _lock = lock_data_dir(&config.data_dir)?; | ||
| 47 | let state = open_state(config).await?; | 108 | let state = open_state(config).await?; |
| 48 | // One stop flag. The signal task sets it; the server and every worker watch it and then drain. | 109 | // One stop flag. The signal task sets it; the server and every worker watch it and then drain. |
| 49 | let (stop_tx, stop_rx) = watch::channel(false); | 110 | let (stop_tx, stop_rx) = watch::channel(false); |
| 50 | if state.oidc.is_some() { | 111 | if state.oidc.is_some() { |
| 51 | tokio::spawn(directory::run(state.clone(), stop_rx.clone())); | 112 | tokio::spawn(directory::run(state.clone(), stop_rx.clone())); |
| 113 | + tokio::spawn(family::run(state.clone(), stop_rx.clone())); | ||
| 114 | + } | ||
| 115 | + if state.config.backup.is_some() { | ||
| 116 | + tokio::spawn(backup::run(state.clone(), stop_rx.clone())); | ||
| 52 | } | 117 | } |
| 53 | tokio::spawn(sweeper::run(state.clone(), stop_rx.clone())); | 118 | tokio::spawn(sweeper::run(state.clone(), stop_rx.clone())); |
| 54 | tokio::spawn(thumbs_worker::run(state.clone(), stop_rx.clone())); | 119 | tokio::spawn(thumbs_worker::run(state.clone(), stop_rx.clone())); |
| @@ -116,6 +181,7 @@ async fn open_state(config: Config) -> Result<AppState> { | |||
| 116 | live: Arc::new(LiveHub::default()), | 181 | live: Arc::new(LiveHub::default()), |
| 117 | oidc, | 182 | oidc, |
| 118 | throttles: Arc::new(ShareThrottles::default()), | 183 | throttles: Arc::new(ShareThrottles::default()), |
| 184 | + family: Arc::new(FamilyCache::default()), | ||
| 119 | }) | 185 | }) |
| 120 | } | 186 | } |
| 121 | 187 | ||
| @@ -243,6 +309,7 @@ mod tests { | |||
| 243 | live: Arc::new(LiveHub::default()), | 309 | live: Arc::new(LiveHub::default()), |
| 244 | oidc: None, | 310 | oidc: None, |
| 245 | throttles: Arc::new(ShareThrottles::default()), | 311 | throttles: Arc::new(ShareThrottles::default()), |
| 312 | + family: Arc::new(FamilyCache::default()), | ||
| 246 | }; | 313 | }; |
| 247 | (dir, state) | 314 | (dir, state) |
| 248 | } | 315 | } |
crates/in-web/src/cli.rsadded+210 -0
| @@ -0,0 +1,210 @@ | |||
| 1 | +//! The command line of `in`. `in [--config <path>] [serve]` runs the server, and a bare `in` does the same. | ||
| 2 | +//! The other commands operate on a stopped instance: each takes the data-directory lock, so a server that is | ||
| 3 | +//! running makes them refuse with a message instead of racing it. | ||
| 4 | +//! | ||
| 5 | +//! Exit status: 0 for success, 1 for a failure or a check that found problems, 2 for a usage error (clap | ||
| 6 | +//! reports those itself). | ||
| 7 | + | ||
| 8 | +use std::path::{Path, PathBuf}; | ||
| 9 | +use std::process::ExitCode; | ||
| 10 | + | ||
| 11 | +use clap::{Parser, Subcommand}; | ||
| 12 | +use in_core::backup; | ||
| 13 | +use in_core::error::Error; | ||
| 14 | +use in_core::export::export_member; | ||
| 15 | +use in_core::fsck; | ||
| 16 | +use in_core::store::members::MemberFields; | ||
| 17 | +use in_core::time::now_stamp; | ||
| 18 | + | ||
| 19 | +use crate::boot; | ||
| 20 | + | ||
| 21 | +/// The parsed command line. | ||
| 22 | +#[derive(Debug, Parser)] | ||
| 23 | +#[command(name = "in", about = "The family's file drive", version)] | ||
| 24 | +pub struct Cli { | ||
| 25 | + /// Configuration file. Without it, `IN_CONFIG` is used, then `config/in.toml`. | ||
| 26 | + #[arg(long, global = true, value_name = "PATH")] | ||
| 27 | + pub config: Option<PathBuf>, | ||
| 28 | + /// The command. A bare `in` runs the server. | ||
| 29 | + #[command(subcommand)] | ||
| 30 | + pub command: Option<Command>, | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// The commands. | ||
| 34 | +#[derive(Debug, Subcommand)] | ||
| 35 | +pub enum Command { | ||
| 36 | + /// Run the server. This is the default. | ||
| 37 | + Serve, | ||
| 38 | + /// Copy one person's live files into a folder tree that uses their folder and file names. | ||
| 39 | + Export { | ||
| 40 | + /// The person: their subject id, or their email address. | ||
| 41 | + #[arg(long, value_name = "SUB|EMAIL")] | ||
| 42 | + member: String, | ||
| 43 | + /// The directory to write into. It is created when missing. | ||
| 44 | + #[arg(long, value_name = "DIR")] | ||
| 45 | + out: PathBuf, | ||
| 46 | + }, | ||
| 47 | + /// Check the database and the blob tree against each other. Changes nothing. | ||
| 48 | + Fsck { | ||
| 49 | + /// Also hash every blob and compare it with its row. Reads every byte, so it is slow. | ||
| 50 | + #[arg(long)] | ||
| 51 | + hash: bool, | ||
| 52 | + }, | ||
| 53 | + /// Replace the database with the one in a backup set. The server must be stopped. | ||
| 54 | + Restore { | ||
| 55 | + /// The backup set directory (the one holding `in.db` and `manifest.json`). | ||
| 56 | + #[arg(long, value_name = "SET")] | ||
| 57 | + from: PathBuf, | ||
| 58 | + }, | ||
| 59 | + /// Quota maintenance. | ||
| 60 | + Quota { | ||
| 61 | + /// What to do. | ||
| 62 | + #[command(subcommand)] | ||
| 63 | + action: QuotaCommand, | ||
| 64 | + }, | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// The quota subcommands. | ||
| 68 | +#[derive(Debug, Subcommand)] | ||
| 69 | +pub enum QuotaCommand { | ||
| 70 | + /// Recompute every person's used bytes from their files, and print the ones that were wrong. | ||
| 71 | + Recompute, | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// Runs the command and maps the outcome to an exit status. | ||
| 75 | +pub async fn run(config: &Path, command: Command) -> ExitCode { | ||
| 76 | + let outcome = match command { | ||
| 77 | + Command::Serve => return serve(config).await, | ||
| 78 | + Command::Export { member, out } => export(config, &member, &out).await, | ||
| 79 | + Command::Fsck { hash } => fsck_cmd(config, hash).await, | ||
| 80 | + Command::Restore { from } => restore(config, &from).await, | ||
| 81 | + Command::Quota { | ||
| 82 | + action: QuotaCommand::Recompute, | ||
| 83 | + } => recompute(config).await, | ||
| 84 | + }; | ||
| 85 | + match outcome { | ||
| 86 | + Ok(true) => ExitCode::SUCCESS, | ||
| 87 | + Ok(false) => ExitCode::FAILURE, | ||
| 88 | + // A conflict here is the lock: say so in plain words, without the "conflict:" prefix. | ||
| 89 | + Err(Error::Conflict(message)) => { | ||
| 90 | + eprintln!("in: {message}"); | ||
| 91 | + ExitCode::FAILURE | ||
| 92 | + } | ||
| 93 | + Err(error) => { | ||
| 94 | + eprintln!("in: {error}"); | ||
| 95 | + ExitCode::FAILURE | ||
| 96 | + } | ||
| 97 | + } | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// Runs the server and maps its outcome. | ||
| 101 | +async fn serve(config: &Path) -> ExitCode { | ||
| 102 | + match boot::serve(config).await { | ||
| 103 | + Ok(()) => ExitCode::SUCCESS, | ||
| 104 | + Err(error) => { | ||
| 105 | + tracing::error!(error = %error, "in stopped with an error"); | ||
| 106 | + ExitCode::FAILURE | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// Finds the person named by a subject id or an email address. | ||
| 112 | +async fn find_member(store: &in_core::store::Store, who: &str) -> Result<MemberFields, Error> { | ||
| 113 | + let member = if who.contains('@') { | ||
| 114 | + store.member_by_email(who).await? | ||
| 115 | + } else { | ||
| 116 | + store.member(who).await? | ||
| 117 | + }; | ||
| 118 | + let member = member.ok_or_else(|| Error::Invalid(format!("no person named {who}")))?; | ||
| 119 | + Ok(MemberFields { | ||
| 120 | + sub: member.sub, | ||
| 121 | + email: member.email, | ||
| 122 | + name: member.name, | ||
| 123 | + is_admin: member.is_admin, | ||
| 124 | + locale: member.locale, | ||
| 125 | + zoneinfo: member.zoneinfo, | ||
| 126 | + picture_version: member.picture_version, | ||
| 127 | + im_updated_at: member.im_updated_at, | ||
| 128 | + }) | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +/// `in export`. True when every file was written and verified. | ||
| 132 | +async fn export(config: &Path, who: &str, out: &Path) -> Result<bool, Error> { | ||
| 133 | + let offline = boot::open_offline(config).await?; | ||
| 134 | + let person = find_member(&offline.store, who).await?; | ||
| 135 | + let report = export_member(&offline.store, offline.blobs.as_ref(), &person.sub, out).await?; | ||
| 136 | + println!( | ||
| 137 | + "exported {} files ({} bytes) and {} folders to {}", | ||
| 138 | + report.files, | ||
| 139 | + report.bytes, | ||
| 140 | + report.folders, | ||
| 141 | + out.display() | ||
| 142 | + ); | ||
| 143 | + for id in &report.failed { | ||
| 144 | + println!("failed: file {id} did not verify and was not written"); | ||
| 145 | + } | ||
| 146 | + Ok(report.failed.is_empty()) | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// `in fsck`. True when the check found nothing wrong. Orphans are reported but do not fail the check. | ||
| 150 | +async fn fsck_cmd(config: &Path, hash: bool) -> Result<bool, Error> { | ||
| 151 | + let offline = boot::open_offline(config).await?; | ||
| 152 | + let report = fsck::check(&offline.store, offline.blobs.as_ref(), hash).await?; | ||
| 153 | + println!("database: {}", report.integrity.replace('\n', "; ")); | ||
| 154 | + println!("rows checked: {}", report.rows_checked); | ||
| 155 | + println!("missing blobs: {}", report.missing_count); | ||
| 156 | + for key in &report.missing { | ||
| 157 | + println!(" missing {key}"); | ||
| 158 | + } | ||
| 159 | + println!("size mismatches: {}", report.size_mismatch.len()); | ||
| 160 | + for key in &report.size_mismatch { | ||
| 161 | + println!(" size {key}"); | ||
| 162 | + } | ||
| 163 | + if hash { | ||
| 164 | + println!("hash mismatches: {}", report.hash_mismatch.len()); | ||
| 165 | + for key in &report.hash_mismatch { | ||
| 166 | + println!(" hash {key}"); | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + println!("orphan blobs (no row names them): {}", report.orphan_count); | ||
| 170 | + for key in &report.orphans { | ||
| 171 | + println!(" orphan {key}"); | ||
| 172 | + } | ||
| 173 | + Ok(report.is_clean()) | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +/// `in restore`. Opens nothing of the database itself: the snapshot is verified first, and only then is the | ||
| 177 | +/// file replaced. True when the restore completed. | ||
| 178 | +async fn restore(config_path: &Path, from: &Path) -> Result<bool, Error> { | ||
| 179 | + let config = in_core::config::Config::load(config_path)?; | ||
| 180 | + let _lock = boot::lock_data_dir(&config.data_dir)?; | ||
| 181 | + let data_dir = config.data_dir.canonicalize()?; | ||
| 182 | + let blobs = boot::open_blobs(&config, &data_dir)?; | ||
| 183 | + let stamp = now_stamp().replace([':', '.'], "-"); | ||
| 184 | + let outcome = | ||
| 185 | + backup::restore(&data_dir, &config.database, from, blobs.as_ref(), &stamp).await?; | ||
| 186 | + println!( | ||
| 187 | + "restored from {}: {} blobs listed, {} not in the blob tree", | ||
| 188 | + from.display(), | ||
| 189 | + outcome.blobs_listed, | ||
| 190 | + outcome.blobs_missing | ||
| 191 | + ); | ||
| 192 | + if let Some(previous) = &outcome.previous { | ||
| 193 | + println!("the replaced database is kept at {}", previous.display()); | ||
| 194 | + } | ||
| 195 | + Ok(true) | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +/// `in quota recompute`. True when it ran; drift that it corrected is printed, not failed. | ||
| 199 | +async fn recompute(config: &Path) -> Result<bool, Error> { | ||
| 200 | + let offline = boot::open_offline(config).await?; | ||
| 201 | + let drift = offline.store.reconcile_quota().await?; | ||
| 202 | + println!("corrected {} people", drift.len()); | ||
| 203 | + for item in &drift { | ||
| 204 | + println!( | ||
| 205 | + " {}: stored {} bytes, now {} bytes", | ||
| 206 | + item.sub, item.stored, item.actual | ||
| 207 | + ); | ||
| 208 | + } | ||
| 209 | + Ok(true) | ||
| 210 | +} | ||
crates/in-web/src/directory.rsmodified+8 -2
| @@ -15,7 +15,6 @@ use std::time::Duration; | |||
| 15 | 15 | ||
| 16 | use futures_util::StreamExt; | 16 | use futures_util::StreamExt; |
| 17 | use http::header::ACCEPT; | 17 | use http::header::ACCEPT; |
| 18 | -use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 19 | use in_core::store::members::MemberFields; | 18 | use in_core::store::members::MemberFields; |
| 20 | use in_core::time::now_stamp; | 19 | use in_core::time::now_stamp; |
| 21 | use serde::Deserialize; | 20 | use serde::Deserialize; |
| @@ -348,9 +347,16 @@ async fn apply_member(state: &AppState, member: WireMember) -> Result<(), SyncEr | |||
| 348 | member.updated_at | 347 | member.updated_at |
| 349 | }, | 348 | }, |
| 350 | }; | 349 | }; |
| 350 | + let default_quota = in_core::settings::resolve( | ||
| 351 | + &state.store, | ||
| 352 | + &state.config.limits, | ||
| 353 | + in_core::settings::DEFAULT_QUOTA_KEY, | ||
| 354 | + ) | ||
| 355 | + .await? | ||
| 356 | + .value; | ||
| 351 | let stored = state | 357 | let stored = state |
| 352 | .store | 358 | .store |
| 353 | - .apply_directory_member(&fields, member.disabled, DEFAULT_MEMBER_QUOTA) | 359 | + .apply_directory_member(&fields, member.disabled, default_quota) |
| 354 | .await?; | 360 | .await?; |
| 355 | if stored.disabled { | 361 | if stored.disabled { |
| 356 | state.store.delete_sessions_by_sub(&stored.sub).await?; | 362 | state.store.delete_sessions_by_sub(&stored.sub).await?; |
crates/in-web/src/family.rsadded+149 -0
| @@ -0,0 +1,149 @@ | |||
| 1 | +//! The family switcher: the list of services `im` publishes (contracts.md section 4), kept in memory for the | ||
| 2 | +//! shell. | ||
| 3 | +//! | ||
| 4 | +//! A worker fetches `GET {issuer}/api/v1/family` every five minutes with a client-credentials token for | ||
| 5 | +//! `im` (the token is cached by the OIDC client). A failed fetch keeps the last good list, because the list | ||
| 6 | +//! changes rarely and a stale switcher is harmless. Only links a browser may follow are kept: http or https | ||
| 7 | +//! URLs with no whitespace or control characters, and never this service's own key. The shell escapes every | ||
| 8 | +//! field when it renders, so a hostile name cannot break the page. | ||
| 9 | + | ||
| 10 | +use std::sync::{PoisonError, RwLock}; | ||
| 11 | +use std::time::Duration; | ||
| 12 | + | ||
| 13 | +use serde::Deserialize; | ||
| 14 | +use tokio::sync::watch; | ||
| 15 | + | ||
| 16 | +use crate::state::AppState; | ||
| 17 | + | ||
| 18 | +/// Time between two fetches of the list. | ||
| 19 | +pub const REFRESH: Duration = Duration::from_secs(5 * 60); | ||
| 20 | + | ||
| 21 | +/// The longest a fetch may take. A slow `im` must not hold the worker for long. | ||
| 22 | +pub const FETCH_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 23 | + | ||
| 24 | +/// The family key of this service. Its own entry is not shown in its own switcher. | ||
| 25 | +pub const SELF_KEY: &str = "in"; | ||
| 26 | + | ||
| 27 | +/// One service in the switcher. | ||
| 28 | +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] | ||
| 29 | +pub struct FamilyLink { | ||
| 30 | + /// The family key, such as `im` or `iz`. | ||
| 31 | + pub key: String, | ||
| 32 | + /// The name the admin gave it. | ||
| 33 | + pub name: String, | ||
| 34 | + /// The origin the switcher opens. | ||
| 35 | + pub url: String, | ||
| 36 | + /// Whether `im`'s last probe of the service passed. | ||
| 37 | + #[serde(default)] | ||
| 38 | + pub healthy: bool, | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// The body of `GET /api/v1/family`. Unknown fields are ignored. | ||
| 42 | +#[derive(Debug, Deserialize)] | ||
| 43 | +struct Listing { | ||
| 44 | + services: Vec<FamilyLink>, | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// The last good list. Read by every page render, written by the worker. | ||
| 48 | +#[derive(Default)] | ||
| 49 | +pub struct FamilyCache { | ||
| 50 | + links: RwLock<Vec<FamilyLink>>, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +impl FamilyCache { | ||
| 54 | + /// A copy of the current list. Empty until the first fetch succeeds. | ||
| 55 | + pub fn list(&self) -> Vec<FamilyLink> { | ||
| 56 | + self.links | ||
| 57 | + .read() | ||
| 58 | + .unwrap_or_else(PoisonError::into_inner) | ||
| 59 | + .clone() | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + /// Replaces the list. | ||
| 63 | + fn replace(&self, links: Vec<FamilyLink>) { | ||
| 64 | + *self.links.write().unwrap_or_else(PoisonError::into_inner) = links; | ||
| 65 | + } | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// Whether a switcher link may be shown: an absolute http or https URL with no whitespace or control | ||
| 69 | +/// characters, and not this service itself. | ||
| 70 | +pub fn usable(link: &FamilyLink) -> bool { | ||
| 71 | + let url = link.url.as_str(); | ||
| 72 | + let scheme_ok = url.starts_with("https://") || url.starts_with("http://"); | ||
| 73 | + scheme_ok | ||
| 74 | + && !url.chars().any(|c| c.is_whitespace() || c.is_control()) | ||
| 75 | + && link.key != SELF_KEY | ||
| 76 | + && !link.key.is_empty() | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// Parses the body of the family endpoint and keeps the usable entries, in the order `im` gave them. | ||
| 80 | +pub fn parse_listing(body: &[u8]) -> Result<Vec<FamilyLink>, String> { | ||
| 81 | + let listing: Listing = serde_json::from_slice(body).map_err(|e| e.to_string())?; | ||
| 82 | + Ok(listing.services.into_iter().filter(usable).collect()) | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// Fetches the list once and stores it. Returns the number of links kept. | ||
| 86 | +async fn refresh(state: &AppState, oidc: &crate::oidc::OidcClient) -> Result<usize, String> { | ||
| 87 | + let token = oidc.service_token().await.map_err(|e| e.to_string())?; | ||
| 88 | + let url = format!("{}/api/v1/family", oidc.issuer()); | ||
| 89 | + let response = oidc | ||
| 90 | + .http() | ||
| 91 | + .get(url) | ||
| 92 | + .bearer_auth(token) | ||
| 93 | + .timeout(FETCH_TIMEOUT) | ||
| 94 | + .send() | ||
| 95 | + .await | ||
| 96 | + .map_err(|e| e.to_string())?; | ||
| 97 | + if !response.status().is_success() { | ||
| 98 | + return Err(format!("im answered {}", response.status())); | ||
| 99 | + } | ||
| 100 | + let body = response.bytes().await.map_err(|e| e.to_string())?; | ||
| 101 | + let links = parse_listing(&body)?; | ||
| 102 | + let count = links.len(); | ||
| 103 | + state.family.replace(links); | ||
| 104 | + Ok(count) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// Fetches the list every [`REFRESH`] until the stop flag is set. Without an `[oidc]` table there is no `im`, | ||
| 108 | +/// and the worker is not started. | ||
| 109 | +pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) { | ||
| 110 | + let Some(oidc) = state.oidc.clone() else { | ||
| 111 | + return; | ||
| 112 | + }; | ||
| 113 | + loop { | ||
| 114 | + match refresh(&state, &oidc).await { | ||
| 115 | + Ok(count) => tracing::debug!(links = count, "family: switcher list refreshed"), | ||
| 116 | + Err(reason) => { | ||
| 117 | + tracing::warn!(reason = %reason, "family: could not refresh the switcher list") | ||
| 118 | + } | ||
| 119 | + } | ||
| 120 | + tokio::select! { | ||
| 121 | + _ = stop.wait_for(|stopped| *stopped) => return, | ||
| 122 | + () = tokio::time::sleep(REFRESH) => {} | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +#[cfg(test)] | ||
| 128 | +mod tests { | ||
| 129 | + use super::*; | ||
| 130 | + | ||
| 131 | + #[test] | ||
| 132 | + fn only_http_links_from_other_services_are_kept() { | ||
| 133 | + let body = br#"{"services":[ | ||
| 134 | + {"key":"im","name":"Account","url":"https://im.example.com","healthy":true,"checked_at":"x"}, | ||
| 135 | + {"key":"in","name":"Files","url":"https://in.example.com"}, | ||
| 136 | + {"key":"bad","name":"Bad","url":"javascript:alert(1)"}, | ||
| 137 | + {"key":"space","name":"S","url":"https://a.example/ x"}, | ||
| 138 | + {"key":"iz","name":"<b>Board</b>","url":"https://iz.example.com"} | ||
| 139 | + ]}"#; | ||
| 140 | + let links = parse_listing(body).unwrap(); | ||
| 141 | + let keys: Vec<&str> = links.iter().map(|l| l.key.as_str()).collect(); | ||
| 142 | + assert_eq!(keys, ["im", "iz"]); | ||
| 143 | + assert_eq!( | ||
| 144 | + links[1].name, "<b>Board</b>", | ||
| 145 | + "the name is kept and escaped when rendered" | ||
| 146 | + ); | ||
| 147 | + assert!(parse_listing(b"not json").is_err()); | ||
| 148 | + } | ||
| 149 | +} | ||
crates/in-web/src/health.rsmodified+3 -3
| @@ -56,8 +56,8 @@ async fn healthz(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> { | |||
| 56 | Ok((status, headers, body)) | 56 | Ok((status, headers, body)) |
| 57 | } | 57 | } |
| 58 | 58 | ||
| 59 | -/// Runs `SELECT 1` on a pooled reader. | 59 | +/// Runs `SELECT 1` on a pooled reader. Also used by the admin page. |
| 60 | -async fn probe_database(state: &AppState) -> CoreResult<()> { | 60 | +pub async fn probe_database(state: &AppState) -> CoreResult<()> { |
| 61 | let conn = state.store.read_conn().await; | 61 | let conn = state.store.read_conn().await; |
| 62 | fetch_opt(&conn, "SELECT 1", (), |row| col_int(row, 0)) | 62 | fetch_opt(&conn, "SELECT 1", (), |row| col_int(row, 0)) |
| 63 | .await? | 63 | .await? |
| @@ -67,7 +67,7 @@ async fn probe_database(state: &AppState) -> CoreResult<()> { | |||
| 67 | 67 | ||
| 68 | /// Asks the blob store for the size of a key that does not exist. Any answer other than an I/O error | 68 | /// Asks the blob store for the size of a key that does not exist. Any answer other than an I/O error |
| 69 | /// (`None` for absent) shows that the store is reachable. | 69 | /// (`None` for absent) shows that the store is reachable. |
| 70 | -async fn probe_blobs(blobs: &dyn BlobStore) -> CoreResult<()> { | 70 | +pub async fn probe_blobs(blobs: &dyn BlobStore) -> CoreResult<()> { |
| 71 | blobs.size(BLOB_PROBE_KEY).await.map(|_| ()) | 71 | blobs.size(BLOB_PROBE_KEY).await.map(|_| ()) |
| 72 | } | 72 | } |
| 73 | 73 | ||
crates/in-web/src/i18n/admin.rsadded+297 -0
| @@ -0,0 +1,297 @@ | |||
| 1 | +//! Strings of the administration page: health, storage, people, services, defaults and the audit log. | ||
| 2 | +//! | ||
| 3 | +//! Each key has an English and a Turkish text in [`a`], matched exhaustively. Sentences with values use the | ||
| 4 | +//! small helpers at the bottom. | ||
| 5 | + | ||
| 6 | +use super::Lang; | ||
| 7 | + | ||
| 8 | +/// One variant per phrase of the admin page. | ||
| 9 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 10 | +pub enum AK { | ||
| 11 | + /// Page title. | ||
| 12 | + Title, | ||
| 13 | + /// The sentence under the title. | ||
| 14 | + Hint, | ||
| 15 | + /// Section: health probes. | ||
| 16 | + Health, | ||
| 17 | + /// Probe result: passing. | ||
| 18 | + HealthOk, | ||
| 19 | + /// Probe result: failing. | ||
| 20 | + HealthFail, | ||
| 21 | + /// Probe: the database. | ||
| 22 | + Database, | ||
| 23 | + /// Probe: the blob store. | ||
| 24 | + Blobs, | ||
| 25 | + /// Label: the build. | ||
| 26 | + Build, | ||
| 27 | + /// Section: storage backend. | ||
| 28 | + Storage, | ||
| 29 | + /// Label: backend name. | ||
| 30 | + Backend, | ||
| 31 | + /// Label: local path. | ||
| 32 | + LocalPath, | ||
| 33 | + /// Label: free space on the local path. | ||
| 34 | + FreeSpace, | ||
| 35 | + /// Status: the S3 bucket answers. | ||
| 36 | + Reachable, | ||
| 37 | + /// Status: the S3 bucket does not answer. | ||
| 38 | + Unreachable, | ||
| 39 | + /// Value shown when the figure is not known. | ||
| 40 | + NotAvailable, | ||
| 41 | + /// Section: the base URL. | ||
| 42 | + BaseUrl, | ||
| 43 | + /// Note under the base URL. | ||
| 44 | + BaseUrlFile, | ||
| 45 | + /// Section: people. | ||
| 46 | + People, | ||
| 47 | + /// Column: name. | ||
| 48 | + ColName, | ||
| 49 | + /// Column: email address. | ||
| 50 | + ColEmail, | ||
| 51 | + /// Column: bytes used. | ||
| 52 | + ColUsed, | ||
| 53 | + /// Column: quota. | ||
| 54 | + ColQuota, | ||
| 55 | + /// Column: the form that sets the quota. | ||
| 56 | + ColSetQuota, | ||
| 57 | + /// Badge: administrator. | ||
| 58 | + AdminBadge, | ||
| 59 | + /// Badge: disabled account. | ||
| 60 | + DisabledBadge, | ||
| 61 | + /// Label of a quota field, in MiB. | ||
| 62 | + QuotaMib, | ||
| 63 | + /// Submit button of a quota form. | ||
| 64 | + SaveQuota, | ||
| 65 | + /// Section: services. | ||
| 66 | + Services, | ||
| 67 | + /// Shown when no service exists yet. | ||
| 68 | + ServicesEmpty, | ||
| 69 | + /// Column: objects stored. | ||
| 70 | + ColObjects, | ||
| 71 | + /// Section: defaults and their sources. | ||
| 72 | + Defaults, | ||
| 73 | + /// The note under the defaults section. | ||
| 74 | + DefaultsHint, | ||
| 75 | + /// Field: quota of a new person, in MiB. | ||
| 76 | + DefaultQuotaLabel, | ||
| 77 | + /// Field: quota of a new service, in MiB. | ||
| 78 | + DefaultServiceQuotaLabel, | ||
| 79 | + /// Field: days before trash is purged. | ||
| 80 | + PurgeLabel, | ||
| 81 | + /// Field: largest upload, in MiB. | ||
| 82 | + MaxUploadLabel, | ||
| 83 | + /// Field: longest share link, in days. | ||
| 84 | + LinkMaxLabel, | ||
| 85 | + /// Column: the value. | ||
| 86 | + ColValue, | ||
| 87 | + /// Column: where the value comes from. | ||
| 88 | + ColSource, | ||
| 89 | + /// Column: how the value may change. | ||
| 90 | + ColMode, | ||
| 91 | + /// Source: set on this page. | ||
| 92 | + SourceUi, | ||
| 93 | + /// Source: set in the file. | ||
| 94 | + SourceFile, | ||
| 95 | + /// Source: the built-in default. | ||
| 96 | + SourceDefault, | ||
| 97 | + /// Mode: takes effect at once. | ||
| 98 | + ModeLive, | ||
| 99 | + /// Mode: takes effect after a restart. | ||
| 100 | + ModeRestart, | ||
| 101 | + /// Mode: read-only. | ||
| 102 | + ModeReadOnly, | ||
| 103 | + /// Submit button of the defaults form. | ||
| 104 | + SaveDefaults, | ||
| 105 | + /// Section: audit log. | ||
| 106 | + Audit, | ||
| 107 | + /// Filter label: action. | ||
| 108 | + FilterAction, | ||
| 109 | + /// Filter label: actor. | ||
| 110 | + FilterActor, | ||
| 111 | + /// Filter label: target kind. | ||
| 112 | + FilterTarget, | ||
| 113 | + /// Submit button of the filters. | ||
| 114 | + Filter, | ||
| 115 | + /// Column: when. | ||
| 116 | + ColAt, | ||
| 117 | + /// Column: actor. | ||
| 118 | + ColActor, | ||
| 119 | + /// Column: action. | ||
| 120 | + ColAction, | ||
| 121 | + /// Column: target. | ||
| 122 | + ColTarget, | ||
| 123 | + /// Column: details. | ||
| 124 | + ColDetails, | ||
| 125 | + /// Link to the next page of the log. | ||
| 126 | + OlderEntries, | ||
| 127 | + /// Shown when no entry matches. | ||
| 128 | + AuditEmpty, | ||
| 129 | + /// Notice after a quota change. | ||
| 130 | + NoticeQuota, | ||
| 131 | + /// Notice after a service quota change. | ||
| 132 | + NoticeServiceQuota, | ||
| 133 | + /// Notice after a defaults change. | ||
| 134 | + NoticeDefaults, | ||
| 135 | + /// Refusal: a value is outside its range. | ||
| 136 | + RefusalRange, | ||
| 137 | + /// Refusal of anything else. | ||
| 138 | + RefusalGeneric, | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +/// The text of `key` in `lang`. | ||
| 142 | +pub fn a(lang: Lang, key: AK) -> &'static str { | ||
| 143 | + match (key, lang) { | ||
| 144 | + (AK::Title, Lang::En) => "Administration", | ||
| 145 | + (AK::Title, Lang::Tr) => "Yönetim", | ||
| 146 | + (AK::Hint, Lang::En) => "Every change made here is written to the audit log.", | ||
| 147 | + (AK::Hint, Lang::Tr) => "Burada yapılan her değişiklik denetim kaydına yazılır.", | ||
| 148 | + (AK::Health, Lang::En) => "Health", | ||
| 149 | + (AK::Health, Lang::Tr) => "Sağlık", | ||
| 150 | + (AK::HealthOk, Lang::En) => "Passing", | ||
| 151 | + (AK::HealthOk, Lang::Tr) => "Sağlıklı", | ||
| 152 | + (AK::HealthFail, Lang::En) => "Failing", | ||
| 153 | + (AK::HealthFail, Lang::Tr) => "Hatalı", | ||
| 154 | + (AK::Database, Lang::En) => "Database", | ||
| 155 | + (AK::Database, Lang::Tr) => "Veritabanı", | ||
| 156 | + (AK::Blobs, Lang::En) => "Blob store", | ||
| 157 | + (AK::Blobs, Lang::Tr) => "Blob deposu", | ||
| 158 | + (AK::Build, Lang::En) => "Build", | ||
| 159 | + (AK::Build, Lang::Tr) => "Derleme", | ||
| 160 | + (AK::Storage, Lang::En) => "Storage backend", | ||
| 161 | + (AK::Storage, Lang::Tr) => "Depolama arka ucu", | ||
| 162 | + (AK::Backend, Lang::En) => "Backend", | ||
| 163 | + (AK::Backend, Lang::Tr) => "Arka uç", | ||
| 164 | + (AK::LocalPath, Lang::En) => "Path", | ||
| 165 | + (AK::LocalPath, Lang::Tr) => "Yol", | ||
| 166 | + (AK::FreeSpace, Lang::En) => "Free space", | ||
| 167 | + (AK::FreeSpace, Lang::Tr) => "Boş alan", | ||
| 168 | + (AK::Reachable, Lang::En) => "Reachable", | ||
| 169 | + (AK::Reachable, Lang::Tr) => "Erişilebilir", | ||
| 170 | + (AK::Unreachable, Lang::En) => "Not reachable", | ||
| 171 | + (AK::Unreachable, Lang::Tr) => "Erişilemiyor", | ||
| 172 | + (AK::NotAvailable, Lang::En) => "not available", | ||
| 173 | + (AK::NotAvailable, Lang::Tr) => "yok", | ||
| 174 | + (AK::BaseUrl, Lang::En) => "Base URL", | ||
| 175 | + (AK::BaseUrl, Lang::Tr) => "Temel adres", | ||
| 176 | + (AK::BaseUrlFile, Lang::En) => "Set in the configuration file. Read-only here.", | ||
| 177 | + (AK::BaseUrlFile, Lang::Tr) => "Yapılandırma dosyasında ayarlanır. Burada salt okunur.", | ||
| 178 | + (AK::People, Lang::En) => "People", | ||
| 179 | + (AK::People, Lang::Tr) => "Kişiler", | ||
| 180 | + (AK::ColName, Lang::En) => "Name", | ||
| 181 | + (AK::ColName, Lang::Tr) => "Ad", | ||
| 182 | + (AK::ColEmail, Lang::En) => "Email", | ||
| 183 | + (AK::ColEmail, Lang::Tr) => "E-posta", | ||
| 184 | + (AK::ColUsed, Lang::En) => "Used", | ||
| 185 | + (AK::ColUsed, Lang::Tr) => "Kullanılan", | ||
| 186 | + (AK::ColQuota, Lang::En) => "Quota", | ||
| 187 | + (AK::ColQuota, Lang::Tr) => "Kota", | ||
| 188 | + (AK::ColSetQuota, Lang::En) => "Set quota", | ||
| 189 | + (AK::ColSetQuota, Lang::Tr) => "Kotayı ayarla", | ||
| 190 | + (AK::AdminBadge, Lang::En) => "Admin", | ||
| 191 | + (AK::AdminBadge, Lang::Tr) => "Yönetici", | ||
| 192 | + (AK::DisabledBadge, Lang::En) => "Disabled", | ||
| 193 | + (AK::DisabledBadge, Lang::Tr) => "Devre dışı", | ||
| 194 | + (AK::QuotaMib, Lang::En) => "Quota (MiB)", | ||
| 195 | + (AK::QuotaMib, Lang::Tr) => "Kota (MiB)", | ||
| 196 | + (AK::SaveQuota, Lang::En) => "Save quota", | ||
| 197 | + (AK::SaveQuota, Lang::Tr) => "Kotayı kaydet", | ||
| 198 | + (AK::Services, Lang::En) => "Services", | ||
| 199 | + (AK::Services, Lang::Tr) => "Hizmetler", | ||
| 200 | + (AK::ServicesEmpty, Lang::En) => "No service has made a call yet.", | ||
| 201 | + (AK::ServicesEmpty, Lang::Tr) => "Henüz çağrı yapan bir hizmet yok.", | ||
| 202 | + (AK::ColObjects, Lang::En) => "Objects", | ||
| 203 | + (AK::ColObjects, Lang::Tr) => "Nesne", | ||
| 204 | + (AK::Defaults, Lang::En) => "Defaults", | ||
| 205 | + (AK::Defaults, Lang::Tr) => "Varsayılanlar", | ||
| 206 | + (AK::DefaultsHint, Lang::En) => { | ||
| 207 | + "A blank field removes the value set here, so the file or the built-in default applies again." | ||
| 208 | + } | ||
| 209 | + (AK::DefaultsHint, Lang::Tr) => { | ||
| 210 | + "Boş alan, buradaki değeri kaldırır; dosyadaki ya da yerleşik varsayılan yeniden geçerli olur." | ||
| 211 | + } | ||
| 212 | + (AK::DefaultQuotaLabel, Lang::En) => "Quota of a new person (MiB)", | ||
| 213 | + (AK::DefaultQuotaLabel, Lang::Tr) => "Yeni kişinin kotası (MiB)", | ||
| 214 | + (AK::DefaultServiceQuotaLabel, Lang::En) => "Quota of a new service (MiB)", | ||
| 215 | + (AK::DefaultServiceQuotaLabel, Lang::Tr) => "Yeni hizmetin kotası (MiB)", | ||
| 216 | + (AK::PurgeLabel, Lang::En) => "Days before trash is purged", | ||
| 217 | + (AK::PurgeLabel, Lang::Tr) => "Çöpün silinmesinden önceki gün sayısı", | ||
| 218 | + (AK::MaxUploadLabel, Lang::En) => "Largest upload (MiB)", | ||
| 219 | + (AK::MaxUploadLabel, Lang::Tr) => "En büyük yükleme (MiB)", | ||
| 220 | + (AK::LinkMaxLabel, Lang::En) => "Longest share link (days)", | ||
| 221 | + (AK::LinkMaxLabel, Lang::Tr) => "En uzun paylaşım bağlantısı (gün)", | ||
| 222 | + (AK::ColValue, Lang::En) => "Value", | ||
| 223 | + (AK::ColValue, Lang::Tr) => "Değer", | ||
| 224 | + (AK::ColSource, Lang::En) => "Source", | ||
| 225 | + (AK::ColSource, Lang::Tr) => "Kaynak", | ||
| 226 | + (AK::ColMode, Lang::En) => "Changes", | ||
| 227 | + (AK::ColMode, Lang::Tr) => "Değişim", | ||
| 228 | + (AK::SourceUi, Lang::En) => "set here", | ||
| 229 | + (AK::SourceUi, Lang::Tr) => "burada ayarlandı", | ||
| 230 | + (AK::SourceFile, Lang::En) => "from the file", | ||
| 231 | + (AK::SourceFile, Lang::Tr) => "dosyadan", | ||
| 232 | + (AK::SourceDefault, Lang::En) => "built-in default", | ||
| 233 | + (AK::SourceDefault, Lang::Tr) => "yerleşik varsayılan", | ||
| 234 | + (AK::ModeLive, Lang::En) => "live", | ||
| 235 | + (AK::ModeLive, Lang::Tr) => "anında", | ||
| 236 | + (AK::ModeRestart, Lang::En) => "after a restart", | ||
| 237 | + (AK::ModeRestart, Lang::Tr) => "yeniden başlatmadan sonra", | ||
| 238 | + (AK::ModeReadOnly, Lang::En) => "read-only", | ||
| 239 | + (AK::ModeReadOnly, Lang::Tr) => "salt okunur", | ||
| 240 | + (AK::SaveDefaults, Lang::En) => "Save defaults", | ||
| 241 | + (AK::SaveDefaults, Lang::Tr) => "Varsayılanları kaydet", | ||
| 242 | + (AK::Audit, Lang::En) => "Audit log", | ||
| 243 | + (AK::Audit, Lang::Tr) => "Denetim kaydı", | ||
| 244 | + (AK::FilterAction, Lang::En) => "Action", | ||
| 245 | + (AK::FilterAction, Lang::Tr) => "İşlem", | ||
| 246 | + (AK::FilterActor, Lang::En) => "Actor id", | ||
| 247 | + (AK::FilterActor, Lang::Tr) => "Aktör kimliği", | ||
| 248 | + (AK::FilterTarget, Lang::En) => "Target kind", | ||
| 249 | + (AK::FilterTarget, Lang::Tr) => "Hedef türü", | ||
| 250 | + (AK::Filter, Lang::En) => "Filter", | ||
| 251 | + (AK::Filter, Lang::Tr) => "Filtrele", | ||
| 252 | + (AK::ColAt, Lang::En) => "When", | ||
| 253 | + (AK::ColAt, Lang::Tr) => "Zaman", | ||
| 254 | + (AK::ColActor, Lang::En) => "Actor", | ||
| 255 | + (AK::ColActor, Lang::Tr) => "Aktör", | ||
| 256 | + (AK::ColAction, Lang::En) => "Action", | ||
| 257 | + (AK::ColAction, Lang::Tr) => "İşlem", | ||
| 258 | + (AK::ColTarget, Lang::En) => "Target", | ||
| 259 | + (AK::ColTarget, Lang::Tr) => "Hedef", | ||
| 260 | + (AK::ColDetails, Lang::En) => "Details", | ||
| 261 | + (AK::ColDetails, Lang::Tr) => "Ayrıntılar", | ||
| 262 | + (AK::OlderEntries, Lang::En) => "Older entries", | ||
| 263 | + (AK::OlderEntries, Lang::Tr) => "Daha eski kayıtlar", | ||
| 264 | + (AK::AuditEmpty, Lang::En) => "No entries match.", | ||
| 265 | + (AK::AuditEmpty, Lang::Tr) => "Eşleşen kayıt yok.", | ||
| 266 | + (AK::NoticeQuota, Lang::En) => "Quota saved.", | ||
| 267 | + (AK::NoticeQuota, Lang::Tr) => "Kota kaydedildi.", | ||
| 268 | + (AK::NoticeServiceQuota, Lang::En) => "Service quota saved.", | ||
| 269 | + (AK::NoticeServiceQuota, Lang::Tr) => "Hizmet kotası kaydedildi.", | ||
| 270 | + (AK::NoticeDefaults, Lang::En) => "Defaults saved.", | ||
| 271 | + (AK::NoticeDefaults, Lang::Tr) => "Varsayılanlar kaydedildi.", | ||
| 272 | + (AK::RefusalRange, Lang::En) => "That value is outside the allowed range.", | ||
| 273 | + (AK::RefusalRange, Lang::Tr) => "Bu değer izin verilen aralığın dışında.", | ||
| 274 | + (AK::RefusalGeneric, Lang::En) => "Something went wrong. Try again.", | ||
| 275 | + (AK::RefusalGeneric, Lang::Tr) => "Bir sorun oluştu. Yeniden deneyin.", | ||
| 276 | + } | ||
| 277 | +} | ||
| 278 | + | ||
| 279 | +/// The sentence for a refusal word. Range refusals (any word ending `_range`) get their own text; anything | ||
| 280 | +/// else gets the generic one. | ||
| 281 | +pub fn refusal(lang: Lang, word: &str) -> &'static str { | ||
| 282 | + if word.ends_with("_range") || word == "quota_negative" { | ||
| 283 | + a(lang, AK::RefusalRange) | ||
| 284 | + } else { | ||
| 285 | + a(lang, AK::RefusalGeneric) | ||
| 286 | + } | ||
| 287 | +} | ||
| 288 | + | ||
| 289 | +/// The notice word of a successful change, as the page shows it. | ||
| 290 | +pub fn notice(lang: Lang, word: &str) -> Option<&'static str> { | ||
| 291 | + match word { | ||
| 292 | + "quota_saved" => Some(a(lang, AK::NoticeQuota)), | ||
| 293 | + "service_quota_saved" => Some(a(lang, AK::NoticeServiceQuota)), | ||
| 294 | + "defaults_saved" => Some(a(lang, AK::NoticeDefaults)), | ||
| 295 | + _ => None, | ||
| 296 | + } | ||
| 297 | +} | ||
crates/in-web/src/i18n/mod.rsmodified+2 -0
| @@ -7,7 +7,9 @@ | |||
| 7 | //! This module decides the language. It does not format sentences with values; those get small | 7 | //! This module decides the language. It does not format sentences with values; those get small |
| 8 | //! helper functions next to their keys. | 8 | //! helper functions next to their keys. |
| 9 | 9 | ||
| 10 | +pub mod admin; | ||
| 10 | pub mod drive; | 11 | pub mod drive; |
| 12 | +pub mod settings; | ||
| 11 | pub mod share; | 13 | pub mod share; |
| 12 | pub mod shell; | 14 | pub mod shell; |
| 13 | 15 | ||
crates/in-web/src/i18n/settings.rsadded+95 -0
| @@ -0,0 +1,95 @@ | |||
| 1 | +//! Strings of the settings page: a person's theme and language, and their storage. | ||
| 2 | +//! | ||
| 3 | +//! Each key has an English and a Turkish text in [`s`], matched exhaustively, so a key without a Turkish | ||
| 4 | +//! text does not compile. | ||
| 5 | + | ||
| 6 | +use super::Lang; | ||
| 7 | + | ||
| 8 | +/// One variant per phrase of the settings page. | ||
| 9 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 10 | +pub enum SK { | ||
| 11 | + /// Page title. | ||
| 12 | + Title, | ||
| 13 | + /// The sentence under the title. | ||
| 14 | + Hint, | ||
| 15 | + /// Label of the theme choice. | ||
| 16 | + ThemeLabel, | ||
| 17 | + /// Theme option: follow the device. | ||
| 18 | + ThemeSystem, | ||
| 19 | + /// Theme option: light. | ||
| 20 | + ThemeLight, | ||
| 21 | + /// Theme option: dark. | ||
| 22 | + ThemeDark, | ||
| 23 | + /// Label of the language choice. | ||
| 24 | + LanguageLabel, | ||
| 25 | + /// Language option: follow the account in `im`. | ||
| 26 | + LanguageFollow, | ||
| 27 | + /// Language option: English. | ||
| 28 | + LanguageEnglish, | ||
| 29 | + /// Language option: Turkish. | ||
| 30 | + LanguageTurkish, | ||
| 31 | + /// Submit button. | ||
| 32 | + Save, | ||
| 33 | + /// Notice after a successful save. | ||
| 34 | + Saved, | ||
| 35 | + /// Heading of the storage section. | ||
| 36 | + StorageTitle, | ||
| 37 | + /// Refusal: the value is not one of the choices. | ||
| 38 | + RefusalChoice, | ||
| 39 | + /// Refusal of anything else. | ||
| 40 | + RefusalGeneric, | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// The text of `key` in `lang`. | ||
| 44 | +pub fn s(lang: Lang, key: SK) -> &'static str { | ||
| 45 | + match (key, lang) { | ||
| 46 | + (SK::Title, Lang::En) => "Settings", | ||
| 47 | + (SK::Title, Lang::Tr) => "Ayarlar", | ||
| 48 | + (SK::Hint, Lang::En) => { | ||
| 49 | + "Your preferences. They apply to every page from the next one you open." | ||
| 50 | + } | ||
| 51 | + (SK::Hint, Lang::Tr) => { | ||
| 52 | + "Tercihleriniz. Açacağınız bir sonraki sayfadan itibaren her sayfada geçerli olur." | ||
| 53 | + } | ||
| 54 | + (SK::ThemeLabel, Lang::En) => "Theme", | ||
| 55 | + (SK::ThemeLabel, Lang::Tr) => "Tema", | ||
| 56 | + (SK::ThemeSystem, Lang::En) => "Match the device", | ||
| 57 | + (SK::ThemeSystem, Lang::Tr) => "Cihaza uy", | ||
| 58 | + (SK::ThemeLight, Lang::En) => "Light", | ||
| 59 | + (SK::ThemeLight, Lang::Tr) => "Açık", | ||
| 60 | + (SK::ThemeDark, Lang::En) => "Dark", | ||
| 61 | + (SK::ThemeDark, Lang::Tr) => "Koyu", | ||
| 62 | + (SK::LanguageLabel, Lang::En) => "Language", | ||
| 63 | + (SK::LanguageLabel, Lang::Tr) => "Dil", | ||
| 64 | + (SK::LanguageFollow, Lang::En) => "Follow my account", | ||
| 65 | + (SK::LanguageFollow, Lang::Tr) => "Hesabımı takip et", | ||
| 66 | + (SK::LanguageEnglish, _) => "English", | ||
| 67 | + (SK::LanguageTurkish, _) => "Türkçe", | ||
| 68 | + (SK::Save, Lang::En) => "Save", | ||
| 69 | + (SK::Save, Lang::Tr) => "Kaydet", | ||
| 70 | + (SK::Saved, Lang::En) => "Settings saved.", | ||
| 71 | + (SK::Saved, Lang::Tr) => "Ayarlar kaydedildi.", | ||
| 72 | + (SK::StorageTitle, Lang::En) => "Storage", | ||
| 73 | + (SK::StorageTitle, Lang::Tr) => "Depolama", | ||
| 74 | + (SK::RefusalChoice, Lang::En) => "That choice is not available.", | ||
| 75 | + (SK::RefusalChoice, Lang::Tr) => "Bu seçenek kullanılamıyor.", | ||
| 76 | + (SK::RefusalGeneric, Lang::En) => "Something went wrong. Try again.", | ||
| 77 | + (SK::RefusalGeneric, Lang::Tr) => "Bir sorun oluştu. Yeniden deneyin.", | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// "In effect: English" and its Turkish form, for the language choice. | ||
| 82 | +pub fn in_effect(lang: Lang, value: &str) -> String { | ||
| 83 | + match lang { | ||
| 84 | + Lang::En => format!("In effect: {value}"), | ||
| 85 | + Lang::Tr => format!("Şu an geçerli: {value}"), | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// "12 MiB of 10 GiB used" and its Turkish form. | ||
| 90 | +pub fn used_of(lang: Lang, used: &str, quota: &str) -> String { | ||
| 91 | + match lang { | ||
| 92 | + Lang::En => format!("{used} of {quota} used"), | ||
| 93 | + Lang::Tr => format!("{quota} içinden {used} kullanıldı"), | ||
| 94 | + } | ||
| 95 | +} | ||
crates/in-web/src/live.rsmodified+5 -4
| @@ -9,10 +9,8 @@ | |||
| 9 | //! The hub is not a queue and not an authorisation check. Each route that opens a stream | 9 | //! The hub is not a queue and not an authorisation check. Each route that opens a stream |
| 10 | //! authenticates and authorises first, then calls [`stream_changes`]. | 10 | //! authenticates and authorises first, then calls [`stream_changes`]. |
| 11 | //! | 11 | //! |
| 12 | -//! Nothing bumps a topic or opens [`stream_changes`] yet, so the items here are kept ahead of the | 12 | +//! The topics of the pages are listed on [`Topic`]. Every write that changes what a page shows bumps its |
| 13 | -//! pages that use them. | 13 | +//! topic after the commit. |
| 14 | - | ||
| 15 | -#![allow(dead_code)] // The hub and its topics wait for the pages that bump and follow them. | ||
| 16 | 14 | ||
| 17 | use std::collections::HashMap; | 15 | use std::collections::HashMap; |
| 18 | use std::future::Future; | 16 | use std::future::Future; |
| @@ -44,6 +42,9 @@ pub enum Topic { | |||
| 44 | Shared(String), | 42 | Shared(String), |
| 45 | /// The audit log: an entry was written. Global. Admin pages only. | 43 | /// The audit log: an entry was written. Global. Admin pages only. |
| 46 | AdminAudit, | 44 | AdminAudit, |
| 45 | + /// A person's share links: made, revoked, reminted, or their targets changed. Keyed by owner sub. | ||
| 46 | + /// Streamed only to that person. | ||
| 47 | + Links(String), | ||
| 47 | } | 48 | } |
| 48 | 49 | ||
| 49 | /// The change counters of all open topics. Cheap to share: every clone of the app state holds the | 50 | /// The change counters of all open topics. Cheap to share: every clone of the app state holds the |
crates/in-web/src/main.rsmodified+15 -59
| @@ -1,14 +1,19 @@ | |||
| 1 | -//! The `in` binary: the command line, logging and the process lifetime. | 1 | +//! The `in` binary: the process lifetime and the command line. The commands live in `cli`, the server in |
| 2 | +//! `boot`, and each feature in its own module. | ||
| 2 | //! | 3 | //! |
| 3 | -//! `in [--config <path>] [serve]` runs the server; a bare `in` does the same. `in admin ...` is the | 4 | +//! `in [--config <path>] [serve]` runs the server; a bare `in` does the same. `export`, `fsck`, `restore` and |
| 4 | -//! operator command line, which is not built yet. The configuration file is the `--config` path, | 5 | +//! `quota recompute` run on a stopped instance. The configuration file is the `--config` path, then |
| 5 | -//! then `IN_CONFIG`, then `config/in.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. | 6 | +//! `IN_CONFIG`, then `config/in.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. |
| 6 | 7 | ||
| 7 | mod api; | 8 | mod api; |
| 8 | mod assets; | 9 | mod assets; |
| 10 | +mod audit; | ||
| 9 | mod auth; | 11 | mod auth; |
| 12 | +mod backup; | ||
| 10 | mod boot; | 13 | mod boot; |
| 14 | +mod cli; | ||
| 11 | mod directory; | 15 | mod directory; |
| 16 | +mod family; | ||
| 12 | mod health; | 17 | mod health; |
| 13 | mod i18n; | 18 | mod i18n; |
| 14 | mod live; | 19 | mod live; |
| @@ -22,13 +27,13 @@ mod throttle; | |||
| 22 | mod thumbs_worker; | 27 | mod thumbs_worker; |
| 23 | mod views; | 28 | mod views; |
| 24 | 29 | ||
| 25 | -use std::path::{Path, PathBuf}; | 30 | +use std::path::PathBuf; |
| 26 | use std::process::ExitCode; | 31 | use std::process::ExitCode; |
| 27 | 32 | ||
| 33 | +use clap::Parser; | ||
| 28 | use tracing_subscriber::EnvFilter; | 34 | use tracing_subscriber::EnvFilter; |
| 29 | 35 | ||
| 30 | -/// Printed with a usage error. | 36 | +use crate::cli::{Cli, Command}; |
| 31 | -const USAGE: &str = "usage: in [--config <path>] [serve]"; | ||
| 32 | 37 | ||
| 33 | /// The configuration file when neither `--config` nor `IN_CONFIG` names one. | 38 | /// The configuration file when neither `--config` nor `IN_CONFIG` names one. |
| 34 | const DEFAULT_CONFIG: &str = "config/in.toml"; | 39 | const DEFAULT_CONFIG: &str = "config/in.toml"; |
| @@ -36,28 +41,6 @@ const DEFAULT_CONFIG: &str = "config/in.toml"; | |||
| 36 | /// The environment variable that names the configuration file. | 41 | /// The environment variable that names the configuration file. |
| 37 | const CONFIG_ENV: &str = "IN_CONFIG"; | 42 | const CONFIG_ENV: &str = "IN_CONFIG"; |
| 38 | 43 | ||
| 39 | -/// The parsed command line: the `--config` path and the positional words. | ||
| 40 | -struct Cli { | ||
| 41 | - config: Option<PathBuf>, | ||
| 42 | - words: Vec<String>, | ||
| 43 | -} | ||
| 44 | - | ||
| 45 | -/// Splits the arguments into the `--config <path>` pair and the positional words. | ||
| 46 | -fn parse_args(args: impl Iterator<Item = String>) -> Result<Cli, String> { | ||
| 47 | - let mut config = None; | ||
| 48 | - let mut words = Vec::new(); | ||
| 49 | - let mut args = args; | ||
| 50 | - while let Some(arg) = args.next() { | ||
| 51 | - if arg == "--config" { | ||
| 52 | - let path = args.next().ok_or("--config needs a path")?; | ||
| 53 | - config = Some(PathBuf::from(path)); | ||
| 54 | - } else { | ||
| 55 | - words.push(arg); | ||
| 56 | - } | ||
| 57 | - } | ||
| 58 | - Ok(Cli { config, words }) | ||
| 59 | -} | ||
| 60 | - | ||
| 61 | /// The configuration path: the flag, else `IN_CONFIG`, else the default. | 44 | /// The configuration path: the flag, else `IN_CONFIG`, else the default. |
| 62 | fn config_path(flag: Option<PathBuf>) -> PathBuf { | 45 | fn config_path(flag: Option<PathBuf>) -> PathBuf { |
| 63 | flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from)) | 46 | flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from)) |
| @@ -73,37 +56,10 @@ fn init_logging() { | |||
| 73 | .init(); | 56 | .init(); |
| 74 | } | 57 | } |
| 75 | 58 | ||
| 76 | -/// Runs the server and maps its outcome to an exit status. | ||
| 77 | -async fn serve(config: &Path) -> ExitCode { | ||
| 78 | - match boot::serve(config).await { | ||
| 79 | - Ok(()) => ExitCode::SUCCESS, | ||
| 80 | - Err(error) => { | ||
| 81 | - tracing::error!(error = %error, "in stopped with an error"); | ||
| 82 | - ExitCode::FAILURE | ||
| 83 | - } | ||
| 84 | - } | ||
| 85 | -} | ||
| 86 | - | ||
| 87 | #[tokio::main] | 59 | #[tokio::main] |
| 88 | async fn main() -> ExitCode { | 60 | async fn main() -> ExitCode { |
| 89 | init_logging(); | 61 | init_logging(); |
| 90 | - let cli = match parse_args(std::env::args().skip(1)) { | 62 | + let cli = Cli::parse(); |
| 91 | - Ok(cli) => cli, | 63 | + let path = config_path(cli.config.clone()); |
| 92 | - Err(message) => { | 64 | + cli::run(&path, cli.command.unwrap_or(Command::Serve)).await |
| 93 | - eprintln!("in: {message}\n{USAGE}"); | ||
| 94 | - return ExitCode::from(2); | ||
| 95 | - } | ||
| 96 | - }; | ||
| 97 | - let words: Vec<&str> = cli.words.iter().map(String::as_str).collect(); | ||
| 98 | - match words.as_slice() { | ||
| 99 | - [] | ["serve"] => serve(&config_path(cli.config)).await, | ||
| 100 | - ["admin", ..] => { | ||
| 101 | - eprintln!("in: admin commands are not implemented yet"); | ||
| 102 | - ExitCode::from(2) | ||
| 103 | - } | ||
| 104 | - _ => { | ||
| 105 | - eprintln!("in: unknown command\n{USAGE}"); | ||
| 106 | - ExitCode::from(2) | ||
| 107 | - } | ||
| 108 | - } | ||
| 109 | } | 65 | } |
crates/in-web/src/pages/admin.rsadded+947 -0
| @@ -0,0 +1,947 @@ | |||
| 1 | +//! The administration page (`GET /admin`) and its writes. Only an instance administrator (the `im_admin` | ||
| 2 | +//! claim, stored as `members.is_admin`) sees it. Anyone else gets `404`, and so does a write from them. | ||
| 3 | +//! | ||
| 4 | +//! The page shows: health (the database and the blob store answer), the storage backend and its free space | ||
| 5 | +//! or reachability, the base URL, every person with their quota, every service with its usage and quota, | ||
| 6 | +//! the defaults with the layer each value comes from (UI, file or built-in default), and the audit log with | ||
| 7 | +//! keyset paging and filters. | ||
| 8 | +//! | ||
| 9 | +//! Every write is checked (administrator, then CSRF, both before any side effect), validated, and then | ||
| 10 | +//! audited after it commits. The audit writer never fails a request. The defaults form is all-or-nothing: if | ||
| 11 | +//! one value is out of range, nothing is written. | ||
| 12 | + | ||
| 13 | +use std::time::Duration; | ||
| 14 | + | ||
| 15 | +use in_core::config::Backend; | ||
| 16 | +use in_core::error::Error as CoreError; | ||
| 17 | +use in_core::settings::{ | ||
| 18 | + self, DEFAULT_QUOTA_KEY, DEFAULT_SERVICE_QUOTA_KEY, FIELDS, LINK_MAX_DAYS_KEY, MAX_UPLOAD_KEY, | ||
| 19 | + Mode, PURGE_KEY, Source, | ||
| 20 | +}; | ||
| 21 | +use in_core::store::audit::{AuditQuery, AuditRow}; | ||
| 22 | +use in_core::store::members::Member; | ||
| 23 | +use in_core::store::objects::Service; | ||
| 24 | +use in_core::store::{Store, objects::Usage}; | ||
| 25 | +use serde::Deserialize; | ||
| 26 | +use serde_json::json; | ||
| 27 | +use topcoat::Result; | ||
| 28 | +use topcoat::context::{Cx, app_context}; | ||
| 29 | +use topcoat::router::content::Form; | ||
| 30 | +use topcoat::router::error::{SeeOther, not_found, see_other}; | ||
| 31 | +use topcoat::router::response::Response; | ||
| 32 | +use topcoat::router::{page, parse_query_params, path_param_segment, route}; | ||
| 33 | +use topcoat::view::{View, component, view}; | ||
| 34 | + | ||
| 35 | +use crate::audit::{self, Entry}; | ||
| 36 | +use crate::auth::{Viewer, require_admin, require_admin_csrf}; | ||
| 37 | +use crate::health::{probe_blobs, probe_database}; | ||
| 38 | +use crate::i18n::Lang; | ||
| 39 | +use crate::i18n::admin::{AK, a, notice, refusal}; | ||
| 40 | +use crate::live::{Topic, stream_changes}; | ||
| 41 | +use crate::oidc::percent_encode; | ||
| 42 | +use crate::pages::drive::{viewer_lang, with_param}; | ||
| 43 | +use crate::state::AppState; | ||
| 44 | +use crate::views::drive::{size_text, stamp_text}; | ||
| 45 | +use crate::views::{ViewerInfo, alert, notice as flash_notice, shell}; | ||
| 46 | + | ||
| 47 | +/// One mebibyte, the unit of the admin's byte fields. | ||
| 48 | +const MIB: i64 = 1024 * 1024; | ||
| 49 | + | ||
| 50 | +/// Audit rows per page. | ||
| 51 | +pub const AUDIT_PAGE: usize = 50; | ||
| 52 | + | ||
| 53 | +/// How long a probe of the blob store may take on this page. A slow bucket shows as not reachable. | ||
| 54 | +const PROBE_WAIT: Duration = Duration::from_secs(2); | ||
| 55 | + | ||
| 56 | +/// The query of the page: notice and refusal words, the audit filters and the keyset cursor. | ||
| 57 | +#[derive(Debug, Default, Deserialize)] | ||
| 58 | +#[serde(default)] | ||
| 59 | +pub struct AdminQuery { | ||
| 60 | + /// A word from a successful write. | ||
| 61 | + pub notice: String, | ||
| 62 | + /// A word from a refused write. | ||
| 63 | + pub refusal: String, | ||
| 64 | + /// Exact action filter. | ||
| 65 | + pub action: String, | ||
| 66 | + /// Exact actor id filter. | ||
| 67 | + pub actor: String, | ||
| 68 | + /// Exact target kind filter. | ||
| 69 | + pub target: String, | ||
| 70 | + /// Cursor `at|id` of the last row of the previous page. | ||
| 71 | + pub before: String, | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// The form of a quota write: the CSRF token and the quota in MiB. | ||
| 75 | +#[derive(Debug, Default, Deserialize)] | ||
| 76 | +#[serde(default)] | ||
| 77 | +pub struct QuotaForm { | ||
| 78 | + /// The CSRF token of the session. | ||
| 79 | + pub csrf: String, | ||
| 80 | + /// The new quota, in MiB. | ||
| 81 | + pub quota_mib: String, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// The form of the defaults. Every field is optional on the wire; blank clears the UI override. | ||
| 85 | +#[derive(Debug, Default, Deserialize)] | ||
| 86 | +#[serde(default)] | ||
| 87 | +pub struct DefaultsForm { | ||
| 88 | + /// The CSRF token of the session. | ||
| 89 | + pub csrf: String, | ||
| 90 | + /// New person's quota, MiB. | ||
| 91 | + pub default_quota_mib: String, | ||
| 92 | + /// New service's quota, MiB. | ||
| 93 | + pub default_service_quota_mib: String, | ||
| 94 | + /// Days before a purge. | ||
| 95 | + pub purge_after_days: String, | ||
| 96 | + /// Largest upload, MiB. | ||
| 97 | + pub max_upload_mib: String, | ||
| 98 | + /// Longest share link, days. | ||
| 99 | + pub link_max_days: String, | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +/// One row of the defaults table. | ||
| 103 | +#[derive(Debug, Clone)] | ||
| 104 | +pub struct DefaultRow { | ||
| 105 | + /// Form field name. | ||
| 106 | + pub field: &'static str, | ||
| 107 | + /// Heading of the row. | ||
| 108 | + pub label: AK, | ||
| 109 | + /// The UI override in the form's unit, blank when none is set. | ||
| 110 | + pub input: String, | ||
| 111 | + /// The effective value, formatted. | ||
| 112 | + pub shown: String, | ||
| 113 | + /// Where the effective value comes from. | ||
| 114 | + pub source: Source, | ||
| 115 | + /// How the value may change. | ||
| 116 | + pub mode: Mode, | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +/// What the page shows about the storage backend. | ||
| 120 | +#[derive(Debug, Clone)] | ||
| 121 | +pub struct StorageStatus { | ||
| 122 | + /// `local` or `s3`. | ||
| 123 | + pub backend: &'static str, | ||
| 124 | + /// The local blob path, or the bucket name. | ||
| 125 | + pub location: String, | ||
| 126 | + /// Free bytes on the local path, when it could be read. | ||
| 127 | + pub free: Option<i64>, | ||
| 128 | + /// Whether the S3 bucket answered a probe. | ||
| 129 | + pub reachable: Option<bool>, | ||
| 130 | + /// The base URL from the file. | ||
| 131 | + pub base_url: String, | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// The health probes: whether each part answered. | ||
| 135 | +#[derive(Debug, Clone, Copy)] | ||
| 136 | +pub struct Probes { | ||
| 137 | + /// The database answered a `SELECT 1`. | ||
| 138 | + pub database: bool, | ||
| 139 | + /// The blob store answered. | ||
| 140 | + pub blobs: bool, | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +/// Whether a field's form unit is MiB. | ||
| 144 | +fn is_mib(key: &str) -> bool { | ||
| 145 | + key == DEFAULT_QUOTA_KEY || key == DEFAULT_SERVICE_QUOTA_KEY || key == MAX_UPLOAD_KEY | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +/// The form field name of a runtime setting. | ||
| 149 | +fn field_name(key: &str) -> &'static str { | ||
| 150 | + match key { | ||
| 151 | + DEFAULT_QUOTA_KEY => "default_quota_mib", | ||
| 152 | + DEFAULT_SERVICE_QUOTA_KEY => "default_service_quota_mib", | ||
| 153 | + PURGE_KEY => "purge_after_days", | ||
| 154 | + MAX_UPLOAD_KEY => "max_upload_mib", | ||
| 155 | + _ => "link_max_days", | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +/// The label heading of a runtime setting. | ||
| 160 | +fn label_of(key: &str) -> AK { | ||
| 161 | + match key { | ||
| 162 | + DEFAULT_QUOTA_KEY => AK::DefaultQuotaLabel, | ||
| 163 | + DEFAULT_SERVICE_QUOTA_KEY => AK::DefaultServiceQuotaLabel, | ||
| 164 | + PURGE_KEY => AK::PurgeLabel, | ||
| 165 | + MAX_UPLOAD_KEY => AK::MaxUploadLabel, | ||
| 166 | + _ => AK::LinkMaxLabel, | ||
| 167 | + } | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +/// Converts a MiB figure from a form to bytes. Blank is "no value" and is passed through as blank. | ||
| 171 | +fn mib_to_text(text: &str) -> std::result::Result<String, CoreError> { | ||
| 172 | + let text = text.trim(); | ||
| 173 | + if text.is_empty() { | ||
| 174 | + return Ok(String::new()); | ||
| 175 | + } | ||
| 176 | + text.parse::<i64>() | ||
| 177 | + .ok() | ||
| 178 | + .and_then(|mib| mib.checked_mul(MIB)) | ||
| 179 | + .map(|bytes| bytes.to_string()) | ||
| 180 | + .ok_or_else(|| CoreError::Invalid("quota_range".into())) | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/// The bytes of a person's or a service's quota from its form: required, and within the field's bounds. | ||
| 184 | +fn quota_bytes(text: &str) -> std::result::Result<i64, CoreError> { | ||
| 185 | + let text = mib_to_text(text)?; | ||
| 186 | + let field = settings::field(DEFAULT_QUOTA_KEY) | ||
| 187 | + .ok_or_else(|| CoreError::Invalid("quota_range".into()))?; | ||
| 188 | + let bytes: i64 = text | ||
| 189 | + .parse() | ||
| 190 | + .map_err(|_| CoreError::Invalid("quota_range".into()))?; | ||
| 191 | + settings::check(field, bytes).map_err(|_| CoreError::Invalid("quota_range".into())) | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +/// Maps a refused write to the answer: a missing item is `404`, a refusal goes back to the page with its | ||
| 195 | +/// word, anything else is a server error. | ||
| 196 | +fn refuse(error: CoreError) -> Result<SeeOther> { | ||
| 197 | + match error { | ||
| 198 | + CoreError::NotFound => Err(not_found().into()), | ||
| 199 | + CoreError::Invalid(word) | CoreError::Conflict(word) | CoreError::Forbidden(word) => { | ||
| 200 | + let safe = if word.chars().all(|c| c.is_ascii_lowercase() || c == '_') { | ||
| 201 | + word | ||
| 202 | + } else { | ||
| 203 | + "generic".to_owned() | ||
| 204 | + }; | ||
| 205 | + Ok(see_other(with_param("/admin", "refusal", &safe))) | ||
| 206 | + } | ||
| 207 | + other => Err(other.into()), | ||
| 208 | + } | ||
| 209 | +} | ||
| 210 | + | ||
| 211 | +/// Appends one audit entry for a change made by `actor`. | ||
| 212 | +async fn audited( | ||
| 213 | + state: &AppState, | ||
| 214 | + actor: &Viewer, | ||
| 215 | + action: &str, | ||
| 216 | + target_kind: &str, | ||
| 217 | + target_id: &str, | ||
| 218 | + data: serde_json::Value, | ||
| 219 | +) { | ||
| 220 | + audit::record( | ||
| 221 | + state, | ||
| 222 | + Entry { | ||
| 223 | + actor: Some(&actor.member.sub), | ||
| 224 | + action, | ||
| 225 | + target_kind, | ||
| 226 | + target_id: Some(target_id), | ||
| 227 | + data, | ||
| 228 | + }, | ||
| 229 | + ) | ||
| 230 | + .await; | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +/// The rows of the defaults table: each field's effective value, its source and its mode. | ||
| 234 | +async fn default_rows(state: &AppState) -> Result<Vec<DefaultRow>> { | ||
| 235 | + let mut rows = Vec::with_capacity(FIELDS.len()); | ||
| 236 | + for field in &FIELDS { | ||
| 237 | + let resolved = settings::resolve(&state.store, &state.config.limits, field.key).await?; | ||
| 238 | + let ui = state | ||
| 239 | + .store | ||
| 240 | + .get_setting(field.key) | ||
| 241 | + .await? | ||
| 242 | + .and_then(|text| text.trim().parse::<i64>().ok()); | ||
| 243 | + let mib = is_mib(field.key); | ||
| 244 | + let input = match ui { | ||
| 245 | + Some(value) if mib => (value / MIB).to_string(), | ||
| 246 | + Some(value) => value.to_string(), | ||
| 247 | + None => String::new(), | ||
| 248 | + }; | ||
| 249 | + let shown = if mib { | ||
| 250 | + size_text(resolved.value) | ||
| 251 | + } else { | ||
| 252 | + resolved.value.to_string() | ||
| 253 | + }; | ||
| 254 | + rows.push(DefaultRow { | ||
| 255 | + field: field_name(field.key), | ||
| 256 | + label: label_of(field.key), | ||
| 257 | + input, | ||
| 258 | + shown, | ||
| 259 | + source: resolved.source, | ||
| 260 | + mode: field.mode, | ||
| 261 | + }); | ||
| 262 | + } | ||
| 263 | + Ok(rows) | ||
| 264 | +} | ||
| 265 | + | ||
| 266 | +/// What the storage section needs: the backend, its location and its free space or reachability. | ||
| 267 | +async fn storage_status(state: &AppState) -> StorageStatus { | ||
| 268 | + let base_url = state.config.base_url.clone(); | ||
| 269 | + match state.config.storage.backend { | ||
| 270 | + Backend::Local => { | ||
| 271 | + let path = state.config.data_dir.join(crate::boot::BLOB_DIR); | ||
| 272 | + StorageStatus { | ||
| 273 | + backend: "local", | ||
| 274 | + location: path.display().to_string(), | ||
| 275 | + free: free_space(&path), | ||
| 276 | + reachable: None, | ||
| 277 | + base_url, | ||
| 278 | + } | ||
| 279 | + } | ||
| 280 | + Backend::S3 => { | ||
| 281 | + let reachable = tokio::time::timeout(PROBE_WAIT, probe_blobs(state.blobs.as_ref())) | ||
| 282 | + .await | ||
| 283 | + .is_ok_and(|outcome| outcome.is_ok()); | ||
| 284 | + StorageStatus { | ||
| 285 | + backend: "s3", | ||
| 286 | + location: state | ||
| 287 | + .config | ||
| 288 | + .storage | ||
| 289 | + .s3 | ||
| 290 | + .as_ref() | ||
| 291 | + .map(|s3| s3.bucket.clone()) | ||
| 292 | + .unwrap_or_default(), | ||
| 293 | + free: None, | ||
| 294 | + reachable: Some(reachable), | ||
| 295 | + base_url, | ||
| 296 | + } | ||
| 297 | + } | ||
| 298 | + } | ||
| 299 | +} | ||
| 300 | + | ||
| 301 | +/// Free bytes available to this user on the filesystem of `path`, when it can be read. | ||
| 302 | +fn free_space(path: &std::path::Path) -> Option<i64> { | ||
| 303 | + let stat = rustix::fs::statvfs(path).ok()?; | ||
| 304 | + let bytes = u128::from(stat.f_bavail) * u128::from(stat.f_frsize); | ||
| 305 | + Some(i64::try_from(bytes).unwrap_or(i64::MAX)) | ||
| 306 | +} | ||
| 307 | + | ||
| 308 | +/// Both health probes, each within the probe deadline. | ||
| 309 | +async fn probe_all(state: &AppState) -> Probes { | ||
| 310 | + let (database, blobs) = tokio::join!( | ||
| 311 | + tokio::time::timeout(PROBE_WAIT, probe_database(state)), | ||
| 312 | + tokio::time::timeout(PROBE_WAIT, probe_blobs(state.blobs.as_ref())), | ||
| 313 | + ); | ||
| 314 | + Probes { | ||
| 315 | + database: database.is_ok_and(|r| r.is_ok()), | ||
| 316 | + blobs: blobs.is_ok_and(|r| r.is_ok()), | ||
| 317 | + } | ||
| 318 | +} | ||
| 319 | + | ||
| 320 | +/// Parses the `at|id` cursor. Anything malformed starts the log from the top. | ||
| 321 | +fn parse_cursor(raw: &str) -> Option<(String, String)> { | ||
| 322 | + let (at, id) = raw.split_once('|')?; | ||
| 323 | + (!at.is_empty() && !id.is_empty()).then(|| (at.to_owned(), id.to_owned())) | ||
| 324 | +} | ||
| 325 | + | ||
| 326 | +/// The link to the next page of the log, keeping the filters. | ||
| 327 | +fn older_link(query: &AdminQuery, last: &AuditRow) -> String { | ||
| 328 | + format!( | ||
| 329 | + "/admin?action={}&actor={}&target={}&before={}", | ||
| 330 | + percent_encode(&query.action), | ||
| 331 | + percent_encode(&query.actor), | ||
| 332 | + percent_encode(&query.target), | ||
| 333 | + percent_encode(&format!("{}|{}", last.at, last.id)), | ||
| 334 | + ) | ||
| 335 | +} | ||
| 336 | + | ||
| 337 | +/// The health line of one probe. | ||
| 338 | +#[component] | ||
| 339 | +async fn probe_line(lang: Lang, label: &str, ok: bool) -> Result<impl View> { | ||
| 340 | + let word = if ok { | ||
| 341 | + a(lang, AK::HealthOk) | ||
| 342 | + } else { | ||
| 343 | + a(lang, AK::HealthFail) | ||
| 344 | + }; | ||
| 345 | + Ok(view! { <li>(label) ": " <strong>(word)</strong></li> }) | ||
| 346 | +} | ||
| 347 | + | ||
| 348 | +/// The health section. | ||
| 349 | +#[component] | ||
| 350 | +async fn health_section(lang: Lang, probes: Probes, build_sha: &str) -> Result<impl View> { | ||
| 351 | + Ok(view! { | ||
| 352 | + <section class="admin-section"> | ||
| 353 | + <h2>(a(lang, AK::Health))</h2> | ||
| 354 | + <ul> | ||
| 355 | + probe_line(lang: lang, label: a(lang, AK::Database), ok: probes.database) | ||
| 356 | + probe_line(lang: lang, label: a(lang, AK::Blobs), ok: probes.blobs) | ||
| 357 | + <li>(a(lang, AK::Build)) ": " <code>(build_sha)</code></li> | ||
| 358 | + </ul> | ||
| 359 | + </section> | ||
| 360 | + }) | ||
| 361 | +} | ||
| 362 | + | ||
| 363 | +/// The storage and base URL section. | ||
| 364 | +#[component] | ||
| 365 | +async fn storage_section(lang: Lang, status: &StorageStatus) -> Result<impl View> { | ||
| 366 | + let free = status | ||
| 367 | + .free | ||
| 368 | + .map_or_else(|| a(lang, AK::NotAvailable).to_owned(), size_text); | ||
| 369 | + let reach = match status.reachable { | ||
| 370 | + Some(true) => a(lang, AK::Reachable), | ||
| 371 | + Some(false) => a(lang, AK::Unreachable), | ||
| 372 | + None => a(lang, AK::NotAvailable), | ||
| 373 | + }; | ||
| 374 | + Ok(view! { | ||
| 375 | + <section class="admin-section"> | ||
| 376 | + <h2>(a(lang, AK::Storage))</h2> | ||
| 377 | + <ul> | ||
| 378 | + <li>(a(lang, AK::Backend)) ": " (status.backend)</li> | ||
| 379 | + <li>(a(lang, AK::LocalPath)) ": " <code>(status.location.as_str())</code></li> | ||
| 380 | + if status.backend == "local" { | ||
| 381 | + <li>(a(lang, AK::FreeSpace)) ": " (free.as_str())</li> | ||
| 382 | + } else { | ||
| 383 | + <li>(reach)</li> | ||
| 384 | + } | ||
| 385 | + </ul> | ||
| 386 | + <h3>(a(lang, AK::BaseUrl))</h3> | ||
| 387 | + <p><code>(status.base_url.as_str())</code> " " <span class="muted">(a(lang, AK::BaseUrlFile))</span></p> | ||
| 388 | + </section> | ||
| 389 | + }) | ||
| 390 | +} | ||
| 391 | + | ||
| 392 | +/// One person in the people table, with the form that sets their quota. | ||
| 393 | +#[component] | ||
| 394 | +async fn person_row(lang: Lang, member: &Member, csrf: &str) -> Result<impl View> { | ||
| 395 | + let action = format!("/admin/people/{}/quota", member.sub); | ||
| 396 | + let quota_mib = (member.quota_bytes / MIB).to_string(); | ||
| 397 | + let used = size_text(member.used_bytes); | ||
| 398 | + let quota = size_text(member.quota_bytes); | ||
| 399 | + let input_id = format!("q-{}", member.sub); | ||
| 400 | + Ok(view! { | ||
| 401 | + <tr> | ||
| 402 | + <td>(member.name.as_str()) | ||
| 403 | + if member.is_admin { | ||
| 404 | + " " <span class="badge accent">(a(lang, AK::AdminBadge))</span> | ||
| 405 | + } | ||
| 406 | + if member.disabled { | ||
| 407 | + " " <span class="badge">(a(lang, AK::DisabledBadge))</span> | ||
| 408 | + } | ||
| 409 | + </td> | ||
| 410 | + <td>(member.email.as_str())</td> | ||
| 411 | + <td>(used.as_str()) " / " (quota.as_str())</td> | ||
| 412 | + <td> | ||
| 413 | + <form method="post" action=(action.as_str()) class="inline-form"> | ||
| 414 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 415 | + <label class="sr-only" for=(input_id.as_str())>(a(lang, AK::QuotaMib))</label> | ||
| 416 | + <input id=(input_id.as_str()) name="quota_mib" inputmode="numeric" value=(quota_mib.as_str()) size="8"> | ||
| 417 | + <button class="button" type="submit">(a(lang, AK::SaveQuota))</button> | ||
| 418 | + </form> | ||
| 419 | + </td> | ||
| 420 | + </tr> | ||
| 421 | + }) | ||
| 422 | +} | ||
| 423 | + | ||
| 424 | +/// The people section. | ||
| 425 | +#[component] | ||
| 426 | +async fn people_section(lang: Lang, members: &[Member], csrf: &str) -> Result<impl View> { | ||
| 427 | + Ok(view! { | ||
| 428 | + <section class="admin-section"> | ||
| 429 | + <h2>(a(lang, AK::People))</h2> | ||
| 430 | + <table class="table"> | ||
| 431 | + <thead><tr> | ||
| 432 | + <th>(a(lang, AK::ColName))</th> | ||
| 433 | + <th>(a(lang, AK::ColEmail))</th> | ||
| 434 | + <th>(a(lang, AK::ColUsed)) " / " (a(lang, AK::ColQuota))</th> | ||
| 435 | + <th>(a(lang, AK::ColSetQuota))</th> | ||
| 436 | + </tr></thead> | ||
| 437 | + <tbody> | ||
| 438 | + for member in members { | ||
| 439 | + person_row(lang: lang, member: member, csrf: csrf) | ||
| 440 | + } | ||
| 441 | + </tbody> | ||
| 442 | + </table> | ||
| 443 | + </section> | ||
| 444 | + }) | ||
| 445 | +} | ||
| 446 | + | ||
| 447 | +/// One service in the services table, with the form that sets its quota. | ||
| 448 | +#[component] | ||
| 449 | +async fn service_row( | ||
| 450 | + lang: Lang, | ||
| 451 | + service: &Service, | ||
| 452 | + usage: &Usage, | ||
| 453 | + csrf: &str, | ||
| 454 | +) -> Result<impl View> { | ||
| 455 | + let action = format!("/admin/services/{}/quota", service.key); | ||
| 456 | + let quota_mib = (usage.quota_bytes / MIB).to_string(); | ||
| 457 | + let used = size_text(usage.used_bytes); | ||
| 458 | + let quota = size_text(usage.quota_bytes); | ||
| 459 | + let objects = usage.objects.to_string(); | ||
| 460 | + let input_id = format!("s-{}", service.key); | ||
| 461 | + Ok(view! { | ||
| 462 | + <tr> | ||
| 463 | + <td>(service.key.as_str())</td> | ||
| 464 | + <td>(objects.as_str())</td> | ||
| 465 | + <td>(used.as_str()) " / " (quota.as_str())</td> | ||
| 466 | + <td> | ||
| 467 | + <form method="post" action=(action.as_str()) class="inline-form"> | ||
| 468 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 469 | + <label class="sr-only" for=(input_id.as_str())>(a(lang, AK::QuotaMib))</label> | ||
| 470 | + <input id=(input_id.as_str()) name="quota_mib" inputmode="numeric" value=(quota_mib.as_str()) size="8"> | ||
| 471 | + <button class="button" type="submit">(a(lang, AK::SaveQuota))</button> | ||
| 472 | + </form> | ||
| 473 | + </td> | ||
| 474 | + </tr> | ||
| 475 | + }) | ||
| 476 | +} | ||
| 477 | + | ||
| 478 | +/// The services section. Each row carries its usage, read by the caller. | ||
| 479 | +#[component] | ||
| 480 | +async fn services_section(lang: Lang, rows: &[(Service, Usage)], csrf: &str) -> Result<impl View> { | ||
| 481 | + Ok(view! { | ||
| 482 | + <section class="admin-section"> | ||
| 483 | + <h2>(a(lang, AK::Services))</h2> | ||
| 484 | + if rows.is_empty() { | ||
| 485 | + <p class="muted">(a(lang, AK::ServicesEmpty))</p> | ||
| 486 | + } else { | ||
| 487 | + <table class="table"> | ||
| 488 | + <thead><tr> | ||
| 489 | + <th>"key"</th> | ||
| 490 | + <th>(a(lang, AK::ColObjects))</th> | ||
| 491 | + <th>(a(lang, AK::ColUsed)) " / " (a(lang, AK::ColQuota))</th> | ||
| 492 | + <th>(a(lang, AK::ColSetQuota))</th> | ||
| 493 | + </tr></thead> | ||
| 494 | + <tbody> | ||
| 495 | + for (service, usage) in rows { | ||
| 496 | + service_row(lang: lang, service: service, usage: usage, csrf: csrf) | ||
| 497 | + } | ||
| 498 | + </tbody> | ||
| 499 | + </table> | ||
| 500 | + } | ||
| 501 | + </section> | ||
| 502 | + }) | ||
| 503 | +} | ||
| 504 | + | ||
| 505 | +/// One row of the defaults table: the field, the value in effect, its source, its mode and the input. | ||
| 506 | +#[component] | ||
| 507 | +async fn default_field(lang: Lang, row: &DefaultRow) -> Result<impl View> { | ||
| 508 | + let source = match row.source { | ||
| 509 | + Source::Ui => a(lang, AK::SourceUi), | ||
| 510 | + Source::File => a(lang, AK::SourceFile), | ||
| 511 | + Source::Default => a(lang, AK::SourceDefault), | ||
| 512 | + }; | ||
| 513 | + let mode = match row.mode { | ||
| 514 | + Mode::Live => a(lang, AK::ModeLive), | ||
| 515 | + Mode::Restart => a(lang, AK::ModeRestart), | ||
| 516 | + Mode::ReadOnly => a(lang, AK::ModeReadOnly), | ||
| 517 | + }; | ||
| 518 | + let input_id = format!("d-{}", row.field); | ||
| 519 | + Ok(view! { | ||
| 520 | + <tr> | ||
| 521 | + <td><label for=(input_id.as_str())>(a(lang, row.label))</label></td> | ||
| 522 | + <td><input id=(input_id.as_str()) name=(row.field) inputmode="numeric" value=(row.input.as_str()) size="10"></td> | ||
| 523 | + <td>(row.shown.as_str())</td> | ||
| 524 | + <td>(source)</td> | ||
| 525 | + <td>(mode)</td> | ||
| 526 | + </tr> | ||
| 527 | + }) | ||
| 528 | +} | ||
| 529 | + | ||
| 530 | +/// The defaults section: the form of the five defaults. | ||
| 531 | +#[component] | ||
| 532 | +async fn defaults_section(lang: Lang, rows: &[DefaultRow], csrf: &str) -> Result<impl View> { | ||
| 533 | + Ok(view! { | ||
| 534 | + <section class="admin-section"> | ||
| 535 | + <h2>(a(lang, AK::Defaults))</h2> | ||
| 536 | + <p class="muted">(a(lang, AK::DefaultsHint))</p> | ||
| 537 | + <form method="post" action="/admin/defaults"> | ||
| 538 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 539 | + <table class="table"> | ||
| 540 | + <thead><tr> | ||
| 541 | + <th>(a(lang, AK::ColName))</th> | ||
| 542 | + <th>(a(lang, AK::ColValue))</th> | ||
| 543 | + <th>"="</th> | ||
| 544 | + <th>(a(lang, AK::ColSource))</th> | ||
| 545 | + <th>(a(lang, AK::ColMode))</th> | ||
| 546 | + </tr></thead> | ||
| 547 | + <tbody> | ||
| 548 | + for row in rows { | ||
| 549 | + default_field(lang: lang, row: row) | ||
| 550 | + } | ||
| 551 | + </tbody> | ||
| 552 | + </table> | ||
| 553 | + <button class="button" type="submit">(a(lang, AK::SaveDefaults))</button> | ||
| 554 | + </form> | ||
| 555 | + </section> | ||
| 556 | + }) | ||
| 557 | +} | ||
| 558 | + | ||
| 559 | +/// One audit row: when, who, what, to what, and the details. | ||
| 560 | +#[component] | ||
| 561 | +async fn audit_row(row: &AuditRow) -> Result<impl View> { | ||
| 562 | + let when = stamp_text(&row.at); | ||
| 563 | + let actor = match &row.actor_id { | ||
| 564 | + Some(id) => format!("{} {id}", row.actor_kind), | ||
| 565 | + None => row.actor_kind.clone(), | ||
| 566 | + }; | ||
| 567 | + let target = match &row.target_id { | ||
| 568 | + Some(id) => format!("{} {id}", row.target_kind), | ||
| 569 | + None => row.target_kind.clone(), | ||
| 570 | + }; | ||
| 571 | + Ok(view! { | ||
| 572 | + <tr> | ||
| 573 | + <td>(when.as_str())</td> | ||
| 574 | + <td>(actor.as_str())</td> | ||
| 575 | + <td><code>(row.action.as_str())</code></td> | ||
| 576 | + <td>(target.as_str())</td> | ||
| 577 | + <td><code>(row.data.as_str())</code></td> | ||
| 578 | + </tr> | ||
| 579 | + }) | ||
| 580 | +} | ||
| 581 | + | ||
| 582 | +/// The audit section: the filters, the page of rows and the link to the next page. | ||
| 583 | +#[component] | ||
| 584 | +async fn audit_section( | ||
| 585 | + lang: Lang, | ||
| 586 | + rows: &[AuditRow], | ||
| 587 | + action: &str, | ||
| 588 | + actor: &str, | ||
| 589 | + target: &str, | ||
| 590 | + older: Option<&str>, | ||
| 591 | +) -> Result<impl View> { | ||
| 592 | + Ok(view! { | ||
| 593 | + <section class="admin-section" data-live="/live/admin"> | ||
| 594 | + <h2>(a(lang, AK::Audit))</h2> | ||
| 595 | + <form method="get" action="/admin" class="inline-form"> | ||
| 596 | + <label for="f-action">(a(lang, AK::FilterAction))</label> | ||
| 597 | + <input id="f-action" name="action" value=(action) size="18"> | ||
| 598 | + <label for="f-actor">(a(lang, AK::FilterActor))</label> | ||
| 599 | + <input id="f-actor" name="actor" value=(actor) size="18"> | ||
| 600 | + <label for="f-target">(a(lang, AK::FilterTarget))</label> | ||
| 601 | + <input id="f-target" name="target" value=(target) size="12"> | ||
| 602 | + <button class="button" type="submit">(a(lang, AK::Filter))</button> | ||
| 603 | + </form> | ||
| 604 | + if rows.is_empty() { | ||
| 605 | + <p class="muted">(a(lang, AK::AuditEmpty))</p> | ||
| 606 | + } else { | ||
| 607 | + <table class="table"> | ||
| 608 | + <thead><tr> | ||
| 609 | + <th>(a(lang, AK::ColAt))</th> | ||
| 610 | + <th>(a(lang, AK::ColActor))</th> | ||
| 611 | + <th>(a(lang, AK::ColAction))</th> | ||
| 612 | + <th>(a(lang, AK::ColTarget))</th> | ||
| 613 | + <th>(a(lang, AK::ColDetails))</th> | ||
| 614 | + </tr></thead> | ||
| 615 | + <tbody> | ||
| 616 | + for row in rows { | ||
| 617 | + audit_row(row: row) | ||
| 618 | + } | ||
| 619 | + </tbody> | ||
| 620 | + </table> | ||
| 621 | + } | ||
| 622 | + if let Some(link) = older { | ||
| 623 | + <p><a href=(link)>(a(lang, AK::OlderEntries))</a></p> | ||
| 624 | + } | ||
| 625 | + </section> | ||
| 626 | + }) | ||
| 627 | +} | ||
| 628 | + | ||
| 629 | +/// The whole page body: the notice or refusal, then the sections. | ||
| 630 | +#[allow(clippy::too_many_arguments)] // The page has this many separate parts; a struct would only hide them. | ||
| 631 | +#[component] | ||
| 632 | +async fn admin_body( | ||
| 633 | + lang: Lang, | ||
| 634 | + csrf: &str, | ||
| 635 | + flash: Option<&str>, | ||
| 636 | + refusal_text: Option<&str>, | ||
| 637 | + probes: Probes, | ||
| 638 | + build_sha: &str, | ||
| 639 | + storage: &StorageStatus, | ||
| 640 | + members: &[Member], | ||
| 641 | + services: &[(Service, Usage)], | ||
| 642 | + defaults: &[DefaultRow], | ||
| 643 | + audit_rows: &[AuditRow], | ||
| 644 | + filters: (&str, &str, &str), | ||
| 645 | + older: Option<&str>, | ||
| 646 | +) -> Result<impl View> { | ||
| 647 | + Ok(view! { | ||
| 648 | + <section class="admin"> | ||
| 649 | + <h1>(a(lang, AK::Title))</h1> | ||
| 650 | + <p class="muted">(a(lang, AK::Hint))</p> | ||
| 651 | + if let Some(text) = flash { | ||
| 652 | + flash_notice(message: text) | ||
| 653 | + } | ||
| 654 | + if let Some(text) = refusal_text { | ||
| 655 | + alert(message: text) | ||
| 656 | + } | ||
| 657 | + health_section(lang: lang, probes: probes, build_sha: build_sha) | ||
| 658 | + storage_section(lang: lang, status: storage) | ||
| 659 | + people_section(lang: lang, members: members, csrf: csrf) | ||
| 660 | + services_section(lang: lang, rows: services, csrf: csrf) | ||
| 661 | + defaults_section(lang: lang, rows: defaults, csrf: csrf) | ||
| 662 | + audit_section(lang: lang, rows: audit_rows, action: filters.0, actor: filters.1, target: filters.2, older: older) | ||
| 663 | + </section> | ||
| 664 | + }) | ||
| 665 | +} | ||
| 666 | + | ||
| 667 | +/// `GET /admin`. | ||
| 668 | +#[page("/admin")] | ||
| 669 | +async fn admin_page(cx: &Cx) -> Result<impl View> { | ||
| 670 | + let state = app_context::<AppState>(cx); | ||
| 671 | + let viewer = require_admin(cx).await?; | ||
| 672 | + let lang = viewer_lang(cx, &viewer); | ||
| 673 | + let query: AdminQuery = parse_query_params(cx).unwrap_or_default(); | ||
| 674 | + | ||
| 675 | + let members = state.store.list_members().await?; | ||
| 676 | + let mut services = Vec::new(); | ||
| 677 | + for service in state.store.services().await? { | ||
| 678 | + let usage = state.store.service_usage(&service.key).await?; | ||
| 679 | + services.push((service, usage)); | ||
| 680 | + } | ||
| 681 | + let defaults = default_rows(state).await?; | ||
| 682 | + let storage = storage_status(state).await; | ||
| 683 | + let probes = probe_all(state).await; | ||
| 684 | + let page = state | ||
| 685 | + .store | ||
| 686 | + .audit_page(&AuditQuery { | ||
| 687 | + action: query.action.trim().to_owned(), | ||
| 688 | + actor_id: query.actor.trim().to_owned(), | ||
| 689 | + target_kind: query.target.trim().to_owned(), | ||
| 690 | + before: parse_cursor(&query.before), | ||
| 691 | + limit: AUDIT_PAGE + 1, | ||
| 692 | + }) | ||
| 693 | + .await?; | ||
| 694 | + let has_more = page.len() > AUDIT_PAGE; | ||
| 695 | + let shown: Vec<AuditRow> = page.into_iter().take(AUDIT_PAGE).collect(); | ||
| 696 | + let older = if has_more { | ||
| 697 | + shown.last().map(|last| older_link(&query, last)) | ||
| 698 | + } else { | ||
| 699 | + None | ||
| 700 | + }; | ||
| 701 | + | ||
| 702 | + let flash = (!query.notice.is_empty()) | ||
| 703 | + .then(|| notice(lang, &query.notice)) | ||
| 704 | + .flatten(); | ||
| 705 | + let refusal_text = (!query.refusal.is_empty()).then(|| refusal(lang, &query.refusal)); | ||
| 706 | + let info = ViewerInfo::of(&viewer, state.family.list()); | ||
| 707 | + let build = env!("IN_BUILD_SHA"); | ||
| 708 | + Ok(view! { | ||
| 709 | + shell(title: a(lang, AK::Title), lang: lang, viewer: Some(&info), | ||
| 710 | + admin_body( | ||
| 711 | + lang: lang, | ||
| 712 | + csrf: viewer.session.csrf_token.as_str(), | ||
| 713 | + flash: flash, | ||
| 714 | + refusal_text: refusal_text, | ||
| 715 | + probes: probes, | ||
| 716 | + build_sha: build, | ||
| 717 | + storage: &storage, | ||
| 718 | + members: &members, | ||
| 719 | + services: &services, | ||
| 720 | + defaults: &defaults, | ||
| 721 | + audit_rows: &shown, | ||
| 722 | + filters: (query.action.trim(), query.actor.trim(), query.target.trim()), | ||
| 723 | + older: older.as_deref(), | ||
| 724 | + ) | ||
| 725 | + ) | ||
| 726 | + }) | ||
| 727 | +} | ||
| 728 | + | ||
| 729 | +/// `POST /admin/people/{sub}/quota`: sets a person's quota. The administrator and the CSRF token are checked | ||
| 730 | +/// first; the change is audited after it commits. | ||
| 731 | +#[route(POST "/admin/people/{sub}/quota")] | ||
| 732 | +async fn set_person_quota(cx: &Cx, Form(form): Form<QuotaForm>) -> Result<SeeOther> { | ||
| 733 | + let state = app_context::<AppState>(cx); | ||
| 734 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | ||
| 735 | + let sub = path_param_segment(cx, "sub").to_owned(); | ||
| 736 | + let bytes = match quota_bytes(&form.quota_mib) { | ||
| 737 | + Ok(bytes) => bytes, | ||
| 738 | + Err(error) => return refuse(error), | ||
| 739 | + }; | ||
| 740 | + let Some(before) = state.store.member(&sub).await? else { | ||
| 741 | + return Err(not_found().into()); | ||
| 742 | + }; | ||
| 743 | + if let Err(error) = state.store.set_quota(&sub, bytes).await { | ||
| 744 | + return refuse(error); | ||
| 745 | + } | ||
| 746 | + audited( | ||
| 747 | + state, | ||
| 748 | + &viewer, | ||
| 749 | + "quota.set", | ||
| 750 | + "member", | ||
| 751 | + &sub, | ||
| 752 | + json!({ "from": before.quota_bytes, "to": bytes }), | ||
| 753 | + ) | ||
| 754 | + .await; | ||
| 755 | + Ok(see_other("/admin?notice=quota_saved")) | ||
| 756 | +} | ||
| 757 | + | ||
| 758 | +/// `POST /admin/services/{key}/quota`: sets a service's quota. | ||
| 759 | +#[route(POST "/admin/services/{key}/quota")] | ||
| 760 | +async fn set_service_quota(cx: &Cx, Form(form): Form<QuotaForm>) -> Result<SeeOther> { | ||
| 761 | + let state = app_context::<AppState>(cx); | ||
| 762 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | ||
| 763 | + let key = path_param_segment(cx, "key").to_owned(); | ||
| 764 | + let bytes = match quota_bytes(&form.quota_mib) { | ||
| 765 | + Ok(bytes) => bytes, | ||
| 766 | + Err(error) => return refuse(error), | ||
| 767 | + }; | ||
| 768 | + let Some(before) = state.store.service(&key).await? else { | ||
| 769 | + return Err(not_found().into()); | ||
| 770 | + }; | ||
| 771 | + if let Err(error) = state.store.set_service_quota(&key, bytes).await { | ||
| 772 | + return refuse(error); | ||
| 773 | + } | ||
| 774 | + audited( | ||
| 775 | + state, | ||
| 776 | + &viewer, | ||
| 777 | + "service.quota.set", | ||
| 778 | + "service", | ||
| 779 | + &key, | ||
| 780 | + json!({ "from": before.quota_bytes, "to": bytes }), | ||
| 781 | + ) | ||
| 782 | + .await; | ||
| 783 | + Ok(see_other("/admin?notice=service_quota_saved")) | ||
| 784 | +} | ||
| 785 | + | ||
| 786 | +/// Validates every default before writing any of them, then writes the changed ones, each audited. | ||
| 787 | +async fn apply_defaults( | ||
| 788 | + state: &AppState, | ||
| 789 | + viewer: &Viewer, | ||
| 790 | + form: &DefaultsForm, | ||
| 791 | +) -> std::result::Result<(), CoreError> { | ||
| 792 | + let inputs = [ | ||
| 793 | + (DEFAULT_QUOTA_KEY, form.default_quota_mib.as_str()), | ||
| 794 | + ( | ||
| 795 | + DEFAULT_SERVICE_QUOTA_KEY, | ||
| 796 | + form.default_service_quota_mib.as_str(), | ||
| 797 | + ), | ||
| 798 | + (PURGE_KEY, form.purge_after_days.as_str()), | ||
| 799 | + (MAX_UPLOAD_KEY, form.max_upload_mib.as_str()), | ||
| 800 | + (LINK_MAX_DAYS_KEY, form.link_max_days.as_str()), | ||
| 801 | + ]; | ||
| 802 | + let mut parsed = Vec::with_capacity(inputs.len()); | ||
| 803 | + for (key, text) in inputs { | ||
| 804 | + let text = if is_mib(key) { | ||
| 805 | + mib_to_text(text)? | ||
| 806 | + } else { | ||
| 807 | + text.trim().to_owned() | ||
| 808 | + }; | ||
| 809 | + parsed.push((key, settings::parse_ui(key, &text)?)); | ||
| 810 | + } | ||
| 811 | + for (key, new) in parsed { | ||
| 812 | + let current = state | ||
| 813 | + .store | ||
| 814 | + .get_setting(key) | ||
| 815 | + .await? | ||
| 816 | + .and_then(|text| text.trim().parse::<i64>().ok()); | ||
| 817 | + if current == new { | ||
| 818 | + continue; | ||
| 819 | + } | ||
| 820 | + match new { | ||
| 821 | + Some(value) => { | ||
| 822 | + state.store.set_setting(key, &value.to_string()).await?; | ||
| 823 | + audited( | ||
| 824 | + state, | ||
| 825 | + viewer, | ||
| 826 | + "setting.set", | ||
| 827 | + "setting", | ||
| 828 | + key, | ||
| 829 | + json!({ "value": value }), | ||
| 830 | + ) | ||
| 831 | + .await; | ||
| 832 | + } | ||
| 833 | + None => { | ||
| 834 | + state.store.clear_setting(key).await?; | ||
| 835 | + audited(state, viewer, "setting.clear", "setting", key, json!({})).await; | ||
| 836 | + } | ||
| 837 | + } | ||
| 838 | + } | ||
| 839 | + Ok(()) | ||
| 840 | +} | ||
| 841 | + | ||
| 842 | +/// `POST /admin/defaults`: sets or clears the UI overrides of the five defaults. | ||
| 843 | +#[route(POST "/admin/defaults")] | ||
| 844 | +async fn save_defaults(cx: &Cx, Form(form): Form<DefaultsForm>) -> Result<SeeOther> { | ||
| 845 | + let state = app_context::<AppState>(cx); | ||
| 846 | + let viewer = require_admin_csrf(cx, &form.csrf).await?; | ||
| 847 | + match apply_defaults(state, &viewer, &form).await { | ||
| 848 | + Ok(()) => Ok(see_other("/admin?notice=defaults_saved")), | ||
| 849 | + Err(error) => refuse(error), | ||
| 850 | + } | ||
| 851 | +} | ||
| 852 | + | ||
| 853 | +/// `GET /live/admin`: a data-less `changed` event whenever an audit entry is written. It ends when the viewer | ||
| 854 | +/// is no longer an administrator. | ||
| 855 | +#[route(GET "/live/admin")] | ||
| 856 | +async fn admin_live(cx: &Cx) -> Result<Response> { | ||
| 857 | + let state = app_context::<AppState>(cx); | ||
| 858 | + let viewer = require_admin(cx).await?; | ||
| 859 | + let sub = viewer.member.sub.clone(); | ||
| 860 | + let store: Store = state.store.clone(); | ||
| 861 | + stream_changes(cx, &state.live, &[Topic::AdminAudit], move || { | ||
| 862 | + let store = store.clone(); | ||
| 863 | + let sub = sub.clone(); | ||
| 864 | + async move { | ||
| 865 | + match store.member(&sub).await? { | ||
| 866 | + Some(member) if member.is_admin && !member.disabled => {} | ||
| 867 | + _ => return Err(not_found().into()), | ||
| 868 | + } | ||
| 869 | + Ok(store.latest_audit_id().await?.unwrap_or_default()) | ||
| 870 | + } | ||
| 871 | + }) | ||
| 872 | + .await | ||
| 873 | +} | ||
| 874 | + | ||
| 875 | +#[cfg(test)] | ||
| 876 | +mod tests { | ||
| 877 | + use http::header::{CONTENT_TYPE, COOKIE}; | ||
| 878 | + use in_core::store::members::MemberFields; | ||
| 879 | + use topcoat::router::Body; | ||
| 880 | + | ||
| 881 | + use super::*; | ||
| 882 | + use crate::auth::SESSION_COOKIE; | ||
| 883 | + use crate::auth::test_support::signed_in; | ||
| 884 | + use crate::boot::{router, test_state}; | ||
| 885 | + | ||
| 886 | + /// Makes `sub` an administrator as well, through the same write the sign-in uses. | ||
| 887 | + async fn make_admin(state: &AppState, sub: &str) { | ||
| 888 | + state | ||
| 889 | + .store | ||
| 890 | + .upsert_member_from_claims( | ||
| 891 | + &MemberFields { | ||
| 892 | + sub: sub.into(), | ||
| 893 | + email: format!("{sub}@example.test"), | ||
| 894 | + name: sub.into(), | ||
| 895 | + is_admin: true, | ||
| 896 | + locale: "en".into(), | ||
| 897 | + zoneinfo: "UTC".into(), | ||
| 898 | + picture_version: 0, | ||
| 899 | + im_updated_at: String::new(), | ||
| 900 | + }, | ||
| 901 | + in_core::quota::DEFAULT_MEMBER_QUOTA, | ||
| 902 | + ) | ||
| 903 | + .await | ||
| 904 | + .expect("admin"); | ||
| 905 | + } | ||
| 906 | + | ||
| 907 | + #[tokio::test] | ||
| 908 | + async fn a_member_who_is_not_an_administrator_gets_404_on_the_admin_page() { | ||
| 909 | + let (_dir, state) = test_state().await; | ||
| 910 | + let token = signed_in(&state, "ann", in_core::quota::DEFAULT_MEMBER_QUOTA).await; | ||
| 911 | + let request = http::Request::get("/admin") | ||
| 912 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) | ||
| 913 | + .body(Body::empty()) | ||
| 914 | + .expect("request"); | ||
| 915 | + let response = router(state).handle(request).await; | ||
| 916 | + assert_eq!(response.status(), 404); | ||
| 917 | + } | ||
| 918 | + | ||
| 919 | + #[tokio::test] | ||
| 920 | + async fn an_admin_quota_write_without_the_csrf_token_is_refused_and_changes_nothing() { | ||
| 921 | + let (_dir, state) = test_state().await; | ||
| 922 | + let token = signed_in(&state, "ann", in_core::quota::DEFAULT_MEMBER_QUOTA).await; | ||
| 923 | + make_admin(&state, "ann").await; | ||
| 924 | + let before = state | ||
| 925 | + .store | ||
| 926 | + .member("ann") | ||
| 927 | + .await | ||
| 928 | + .unwrap() | ||
| 929 | + .unwrap() | ||
| 930 | + .quota_bytes; | ||
| 931 | + let request = http::Request::post("/admin/people/ann/quota") | ||
| 932 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) | ||
| 933 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| 934 | + .body(Body::from("quota_mib=1")) | ||
| 935 | + .expect("request"); | ||
| 936 | + let response = router(state.clone()).handle(request).await; | ||
| 937 | + assert_eq!(response.status(), 403); | ||
| 938 | + let after = state | ||
| 939 | + .store | ||
| 940 | + .member("ann") | ||
| 941 | + .await | ||
| 942 | + .unwrap() | ||
| 943 | + .unwrap() | ||
| 944 | + .quota_bytes; | ||
| 945 | + assert_eq!(before, after); | ||
| 946 | + } | ||
| 947 | +} | ||
crates/in-web/src/pages/drive.rsmodified+5 -3
| @@ -257,6 +257,8 @@ pub fn refused(back: &str, error: CoreError) -> Result<SeeOther> { | |||
| 257 | /// Tells the owner's open pages that their drive changed. | 257 | /// Tells the owner's open pages that their drive changed. |
| 258 | pub fn changed(state: &AppState, owner: &str) { | 258 | pub fn changed(state: &AppState, owner: &str) { |
| 259 | state.live.bump(&Topic::Drive(owner.to_owned())); | 259 | state.live.bump(&Topic::Drive(owner.to_owned())); |
| 260 | + // The owner's links show the names of their targets, so a rename or trash reaches the links page too. | ||
| 261 | + state.live.bump(&Topic::Links(owner.to_owned())); | ||
| 260 | } | 262 | } |
| 261 | 263 | ||
| 262 | /// Sorts a listing: folders first, then files; each group by the key, ties by id. Descending reverses | 264 | /// Sorts a listing: folders first, then files; each group by the key, ties by id. Descending reverses |
| @@ -542,7 +544,7 @@ async fn drive_root_page(cx: &Cx) -> Result<impl View> { | |||
| 542 | } else { | 544 | } else { |
| 543 | search_board(state, &viewer, &query, lang).await? | 545 | search_board(state, &viewer, &query, lang).await? |
| 544 | }; | 546 | }; |
| 545 | - let info = ViewerInfo::of(&viewer); | 547 | + let info = ViewerInfo::of(&viewer, state.family.list()); |
| 546 | Ok(view! { | 548 | Ok(view! { |
| 547 | shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), drive_js: true, | 549 | shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), drive_js: true, |
| 548 | drive_board(lang: lang, board: &board) | 550 | drive_board(lang: lang, board: &board) |
| @@ -559,7 +561,7 @@ async fn folder_page(cx: &Cx) -> Result<impl View> { | |||
| 559 | let folder_id = path_param_segment(cx, "folder_id").to_owned(); | 561 | let folder_id = path_param_segment(cx, "folder_id").to_owned(); |
| 560 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); | 562 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); |
| 561 | let board = folder_board(state, &viewer, Some(folder_id), &query, lang).await?; | 563 | let board = folder_board(state, &viewer, Some(folder_id), &query, lang).await?; |
| 562 | - let info = ViewerInfo::of(&viewer); | 564 | + let info = ViewerInfo::of(&viewer, state.family.list()); |
| 563 | Ok(view! { | 565 | Ok(view! { |
| 564 | shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), drive_js: true, | 566 | shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), drive_js: true, |
| 565 | drive_board(lang: lang, board: &board) | 567 | drive_board(lang: lang, board: &board) |
| @@ -742,7 +744,7 @@ async fn pick_folder(cx: &Cx) -> Result<impl View> { | |||
| 742 | let action = format!("/folders/{id}/move"); | 744 | let action = format!("/folders/{id}/move"); |
| 743 | let back = format!("/drive/{id}"); | 745 | let back = format!("/drive/{id}"); |
| 744 | let csrf = viewer.session.csrf_token.clone(); | 746 | let csrf = viewer.session.csrf_token.clone(); |
| 745 | - let info = ViewerInfo::of(&viewer); | 747 | + let info = ViewerInfo::of(&viewer, state.family.list()); |
| 746 | let title = d(lang, DK::MoveTo); | 748 | let title = d(lang, DK::MoveTo); |
| 747 | Ok(view! { | 749 | Ok(view! { |
| 748 | shell(title: title, lang: lang, viewer: Some(&info), | 750 | shell(title: title, lang: lang, viewer: Some(&info), |
crates/in-web/src/pages/files.rsmodified+1 -1
| @@ -349,7 +349,7 @@ async fn pick_file(cx: &Cx) -> Result<impl View> { | |||
| 349 | let action = format!("/files/{id}/move"); | 349 | let action = format!("/files/{id}/move"); |
| 350 | let back = format!("/view/{id}"); | 350 | let back = format!("/view/{id}"); |
| 351 | let csrf = viewer.session.csrf_token.clone(); | 351 | let csrf = viewer.session.csrf_token.clone(); |
| 352 | - let info = ViewerInfo::of(&viewer); | 352 | + let info = ViewerInfo::of(&viewer, state.family.list()); |
| 353 | let title = d(lang, DK::MoveTo); | 353 | let title = d(lang, DK::MoveTo); |
| 354 | Ok(view! { | 354 | Ok(view! { |
| 355 | shell(title: title, lang: lang, viewer: Some(&info), | 355 | shell(title: title, lang: lang, viewer: Some(&info), |
crates/in-web/src/pages/links.rsmodified+65 -16
| @@ -28,18 +28,13 @@ use topcoat::view::{View, component, view}; | |||
| 28 | use crate::auth::{Viewer, require_csrf, require_member}; | 28 | use crate::auth::{Viewer, require_csrf, require_member}; |
| 29 | use crate::i18n::Lang; | 29 | use crate::i18n::Lang; |
| 30 | use crate::i18n::share::{SK, s as share_s}; | 30 | use crate::i18n::share::{SK, s as share_s}; |
| 31 | +use crate::live::{Topic, stream_changes}; | ||
| 31 | use crate::pages::drive::{back_or, done, refused, viewer_lang}; | 32 | use crate::pages::drive::{back_or, done, refused, viewer_lang}; |
| 32 | use crate::pages::share_dialog::shareable; | 33 | use crate::pages::share_dialog::shareable; |
| 33 | use crate::state::AppState; | 34 | use crate::state::AppState; |
| 34 | use crate::views::drive::stamp_text; | 35 | use crate::views::drive::stamp_text; |
| 35 | use crate::views::{ViewerInfo, empty_state, shell}; | 36 | use crate::views::{ViewerInfo, empty_state, shell}; |
| 36 | 37 | ||
| 37 | -/// The settings key of the longest a link may last, in days. | ||
| 38 | -pub const LINK_MAX_DAYS_SETTING: &str = "link_max_days"; | ||
| 39 | - | ||
| 40 | -/// The longest a link may last when the settings say nothing: a year. | ||
| 41 | -pub const DEFAULT_LINK_MAX_DAYS: u32 = 365; | ||
| 42 | - | ||
| 43 | /// Longest password accepted, in bytes. Longer ones are refused rather than cut. | 38 | /// Longest password accepted, in bytes. Longer ones are refused rather than cut. |
| 44 | pub const MAX_PASSWORD_BYTES: usize = 256; | 39 | pub const MAX_PASSWORD_BYTES: usize = 256; |
| 45 | 40 | ||
| @@ -48,11 +43,13 @@ const DAY_SECONDS: u64 = 24 * 60 * 60; | |||
| 48 | 43 | ||
| 49 | /// The longest a link may last, from the settings, else the default. Never zero. | 44 | /// The longest a link may last, from the settings, else the default. Never zero. |
| 50 | pub async fn link_max_days(state: &AppState) -> Result<u32> { | 45 | pub async fn link_max_days(state: &AppState) -> Result<u32> { |
| 51 | - let setting = state.store.get_setting(LINK_MAX_DAYS_SETTING).await?; | 46 | + let resolved = in_core::settings::resolve( |
| 52 | - Ok(setting | 47 | + &state.store, |
| 53 | - .and_then(|value| value.trim().parse::<u32>().ok()) | 48 | + &state.config.limits, |
| 54 | - .filter(|days| *days >= 1) | 49 | + in_core::settings::LINK_MAX_DAYS_KEY, |
| 55 | - .unwrap_or(DEFAULT_LINK_MAX_DAYS)) | 50 | + ) |
| 51 | + .await?; | ||
| 52 | + Ok(u32::try_from(resolved.value).unwrap_or(1).max(1)) | ||
| 56 | } | 53 | } |
| 57 | 54 | ||
| 58 | /// A link as the owner sees it: the link, the name of its target, and the full URL. | 55 | /// A link as the owner sees it: the link, the name of its target, and the full URL. |
| @@ -150,7 +147,7 @@ pub async fn link_row(lang: Lang, view: &LinkView, csrf: &str, back: &str) -> Re | |||
| 150 | #[component] | 147 | #[component] |
| 151 | pub async fn links_body(lang: Lang, rows: &[LinkView], csrf: &str) -> Result<impl View> { | 148 | pub async fn links_body(lang: Lang, rows: &[LinkView], csrf: &str) -> Result<impl View> { |
| 152 | Ok(view! { | 149 | Ok(view! { |
| 153 | - <section class="drive"> | 150 | + <section class="drive" data-live="/live/links"> |
| 154 | <h1>(share_s(lang, SK::LinksTitle))</h1> | 151 | <h1>(share_s(lang, SK::LinksTitle))</h1> |
| 155 | <p class="muted">(share_s(lang, SK::LinksHint))</p> | 152 | <p class="muted">(share_s(lang, SK::LinksHint))</p> |
| 156 | if rows.is_empty() { | 153 | if rows.is_empty() { |
| @@ -175,7 +172,7 @@ async fn links_page(cx: &Cx) -> Result<impl View> { | |||
| 175 | let links = state.store.links_of(&viewer.member.sub).await?; | 172 | let links = state.store.links_of(&viewer.member.sub).await?; |
| 176 | let rows = link_views(state, links).await?; | 173 | let rows = link_views(state, links).await?; |
| 177 | let csrf = viewer.session.csrf_token.clone(); | 174 | let csrf = viewer.session.csrf_token.clone(); |
| 178 | - let info = ViewerInfo::of(&viewer); | 175 | + let info = ViewerInfo::of(&viewer, state.family.list()); |
| 179 | let title = share_s(lang, SK::LinksTitle); | 176 | let title = share_s(lang, SK::LinksTitle); |
| 180 | Ok(view! { | 177 | Ok(view! { |
| 181 | shell(title: title, lang: lang, viewer: Some(&info), | 178 | shell(title: title, lang: lang, viewer: Some(&info), |
| @@ -255,7 +252,10 @@ async fn create_link(cx: &Cx, Form(form): Form<LinkForm>) -> Result<SeeOther> { | |||
| 255 | ))), | 252 | ))), |
| 256 | }; | 253 | }; |
| 257 | match state.store.create_link(new).await { | 254 | match state.store.create_link(new).await { |
| 258 | - Ok(_) => Ok(done(&back, "link_created")), | 255 | + Ok(_) => { |
| 256 | + state.live.bump(&Topic::Links(viewer.member.sub.clone())); | ||
| 257 | + Ok(done(&back, "link_created")) | ||
| 258 | + } | ||
| 259 | Err(error) => refused(&back, error), | 259 | Err(error) => refused(&back, error), |
| 260 | } | 260 | } |
| 261 | } | 261 | } |
| @@ -268,7 +268,10 @@ async fn revoke_link(cx: &Cx, Form(form): Form<LinkForm>) -> Result<SeeOther> { | |||
| 268 | let id = path_param_segment(cx, "id").to_owned(); | 268 | let id = path_param_segment(cx, "id").to_owned(); |
| 269 | let back = back_or(&form.back, "/links"); | 269 | let back = back_or(&form.back, "/links"); |
| 270 | match state.store.revoke_link(&viewer.member.sub, &id).await { | 270 | match state.store.revoke_link(&viewer.member.sub, &id).await { |
| 271 | - Ok(()) => Ok(done(&back, "link_revoked")), | 271 | + Ok(()) => { |
| 272 | + state.live.bump(&Topic::Links(viewer.member.sub.clone())); | ||
| 273 | + Ok(done(&back, "link_revoked")) | ||
| 274 | + } | ||
| 272 | Err(error) => refused(&back, error), | 275 | Err(error) => refused(&back, error), |
| 273 | } | 276 | } |
| 274 | } | 277 | } |
| @@ -286,7 +289,53 @@ async fn remint_link(cx: &Cx, Form(form): Form<LinkForm>) -> Result<SeeOther> { | |||
| 286 | .remint_link(&viewer.member.sub, &id, &token_hash, &token_sealed) | 289 | .remint_link(&viewer.member.sub, &id, &token_hash, &token_sealed) |
| 287 | .await | 290 | .await |
| 288 | { | 291 | { |
| 289 | - Ok(_) => Ok(done(&back, "link_reminted")), | 292 | + Ok(_) => { |
| 293 | + state.live.bump(&Topic::Links(viewer.member.sub.clone())); | ||
| 294 | + Ok(done(&back, "link_reminted")) | ||
| 295 | + } | ||
| 290 | Err(error) => refused(&back, error), | 296 | Err(error) => refused(&back, error), |
| 291 | } | 297 | } |
| 292 | } | 298 | } |
| 299 | + | ||
| 300 | +/// `GET /live/links`: a data-less `changed` event whenever one of the viewer's links changes, or the name of | ||
| 301 | +/// a link's target does. It ends when the session is gone. | ||
| 302 | +#[route(GET "/live/links")] | ||
| 303 | +async fn links_live(cx: &Cx) -> Result<topcoat::router::response::Response> { | ||
| 304 | + let state = app_context::<AppState>(cx); | ||
| 305 | + let viewer = require_member(cx).await?; | ||
| 306 | + let sub = viewer.member.sub.clone(); | ||
| 307 | + let token_hash = viewer.session.token_hash.clone(); | ||
| 308 | + let topics = vec![Topic::Links(sub.clone())]; | ||
| 309 | + let state_for_reads = state.clone(); | ||
| 310 | + stream_changes(cx, &state.live, &topics, move || { | ||
| 311 | + let state = state_for_reads.clone(); | ||
| 312 | + let sub = sub.clone(); | ||
| 313 | + let token_hash = token_hash.clone(); | ||
| 314 | + async move { | ||
| 315 | + if state | ||
| 316 | + .store | ||
| 317 | + .session_by_token_hash(&token_hash) | ||
| 318 | + .await? | ||
| 319 | + .is_none() | ||
| 320 | + { | ||
| 321 | + return Err(not_found().into()); | ||
| 322 | + } | ||
| 323 | + let links = state.store.links_of(&sub).await?; | ||
| 324 | + let rows = link_views(&state, links).await?; | ||
| 325 | + Ok(rows | ||
| 326 | + .iter() | ||
| 327 | + .map(|row| { | ||
| 328 | + format!( | ||
| 329 | + "{}|{}|{}|{}|{}\n", | ||
| 330 | + row.link.id, | ||
| 331 | + row.name, | ||
| 332 | + row.link.use_count, | ||
| 333 | + row.link.revoked_at.as_deref().unwrap_or(""), | ||
| 334 | + row.url | ||
| 335 | + ) | ||
| 336 | + }) | ||
| 337 | + .collect()) | ||
| 338 | + } | ||
| 339 | + }) | ||
| 340 | + .await | ||
| 341 | +} | ||
crates/in-web/src/pages/mod.rsmodified+2 -0
| @@ -1,5 +1,6 @@ | |||
| 1 | //! The pages and the page-level layers. One file per page or per closely related group of pages. | 1 | //! The pages and the page-level layers. One file per page or per closely related group of pages. |
| 2 | 2 | ||
| 3 | +pub mod admin; | ||
| 3 | pub mod backchannel; | 4 | pub mod backchannel; |
| 4 | pub mod drive; | 5 | pub mod drive; |
| 5 | pub mod files; | 6 | pub mod files; |
| @@ -8,6 +9,7 @@ pub mod links; | |||
| 8 | pub mod not_found; | 9 | pub mod not_found; |
| 9 | pub mod photo; | 10 | pub mod photo; |
| 10 | pub mod public_share; | 11 | pub mod public_share; |
| 12 | +pub mod settings; | ||
| 11 | pub mod share_dialog; | 13 | pub mod share_dialog; |
| 12 | pub mod shared; | 14 | pub mod shared; |
| 13 | pub mod sign_in; | 15 | pub mod sign_in; |
crates/in-web/src/pages/settings.rsadded+176 -0
| @@ -0,0 +1,176 @@ | |||
| 1 | +//! The settings page (`GET /settings`) and its form (`POST /settings`): the viewer's theme and language, and | ||
| 2 | +//! a read of their storage. | ||
| 3 | +//! | ||
| 4 | +//! The theme is applied to `<html data-theme>` on every page. The language follows `im` unless the person | ||
| 5 | +//! picks one here; a blank choice clears the override. A save bumps the viewer's `Account` topic, so their | ||
| 6 | +//! other open tabs pick up the new theme on their next fetch. Storage shows the bytes in use against the | ||
| 7 | +//! quota; it never lists anyone else's files. | ||
| 8 | + | ||
| 9 | +use in_core::error::Error as CoreError; | ||
| 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::error::SeeOther; | ||
| 15 | +use topcoat::router::error::see_other; | ||
| 16 | +use topcoat::router::{page, parse_query_params, route}; | ||
| 17 | +use topcoat::view::{View, component, view}; | ||
| 18 | + | ||
| 19 | +use crate::auth::{Viewer, require_csrf, require_member}; | ||
| 20 | +use crate::i18n::Lang; | ||
| 21 | +use crate::i18n::settings::{SK, in_effect, s, used_of}; | ||
| 22 | +use crate::live::Topic; | ||
| 23 | +use crate::pages::drive::viewer_lang; | ||
| 24 | +use crate::state::AppState; | ||
| 25 | +use crate::views::drive::{quota_bar, size_text}; | ||
| 26 | +use crate::views::{ViewerInfo, alert, notice, shell}; | ||
| 27 | + | ||
| 28 | +/// The query of the page: a notice word or a refusal word after a save. Unknown words show nothing. | ||
| 29 | +#[derive(Debug, Default, Deserialize)] | ||
| 30 | +#[serde(default)] | ||
| 31 | +pub struct SettingsQuery { | ||
| 32 | + /// `saved` after a successful save. | ||
| 33 | + pub notice: String, | ||
| 34 | + /// `choice` when the theme or language was not one of the choices. | ||
| 35 | + pub refusal: String, | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// The form of the page. Every field is optional on the wire. | ||
| 39 | +#[derive(Debug, Default, Deserialize)] | ||
| 40 | +#[serde(default)] | ||
| 41 | +pub struct SettingsForm { | ||
| 42 | + /// The CSRF token of the session. | ||
| 43 | + pub csrf: String, | ||
| 44 | + /// `system`, `light` or `dark`. | ||
| 45 | + pub theme: String, | ||
| 46 | + /// `en`, `tr`, or blank to follow `im`. | ||
| 47 | + pub language: String, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// One option of a select (named `choice_option` so it does not shadow `Option`). `selected` is written as a static attribute, so no script is needed. | ||
| 51 | +#[component] | ||
| 52 | +async fn choice_option(value: &str, label: &str, selected: bool) -> Result<impl View> { | ||
| 53 | + Ok(view! { | ||
| 54 | + if selected { | ||
| 55 | + <option value=(value) selected="">(label)</option> | ||
| 56 | + } else { | ||
| 57 | + <option value=(value)>(label)</option> | ||
| 58 | + } | ||
| 59 | + }) | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// The body of the page: the choices, the storage figures and the flash line. | ||
| 63 | +#[component] | ||
| 64 | +pub async fn settings_body( | ||
| 65 | + lang: Lang, | ||
| 66 | + csrf: &str, | ||
| 67 | + theme: &str, | ||
| 68 | + language: &str, | ||
| 69 | + effective: &str, | ||
| 70 | + used: i64, | ||
| 71 | + quota: i64, | ||
| 72 | + flash: Option<&str>, | ||
| 73 | + refusal: Option<&str>, | ||
| 74 | +) -> Result<impl View> { | ||
| 75 | + let used_line = used_of(lang, &size_text(used), &size_text(quota)); | ||
| 76 | + let effective_line = in_effect(lang, effective); | ||
| 77 | + Ok(view! { | ||
| 78 | + <section class="settings"> | ||
| 79 | + <h1>(s(lang, SK::Title))</h1> | ||
| 80 | + <p class="muted">(s(lang, SK::Hint))</p> | ||
| 81 | + if let Some(text) = flash { | ||
| 82 | + notice(message: text) | ||
| 83 | + } | ||
| 84 | + if let Some(text) = refusal { | ||
| 85 | + alert(message: text) | ||
| 86 | + } | ||
| 87 | + <form method="post" action="/settings" class="settings-form"> | ||
| 88 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 89 | + <label for="theme">(s(lang, SK::ThemeLabel))</label> | ||
| 90 | + <select id="theme" name="theme"> | ||
| 91 | + choice_option(value: "system", label: s(lang, SK::ThemeSystem), selected: theme == "system") | ||
| 92 | + choice_option(value: "light", label: s(lang, SK::ThemeLight), selected: theme == "light") | ||
| 93 | + choice_option(value: "dark", label: s(lang, SK::ThemeDark), selected: theme == "dark") | ||
| 94 | + </select> | ||
| 95 | + <label for="language">(s(lang, SK::LanguageLabel))</label> | ||
| 96 | + <select id="language" name="language"> | ||
| 97 | + choice_option(value: "", label: s(lang, SK::LanguageFollow), selected: language.is_empty()) | ||
| 98 | + choice_option(value: "en", label: s(lang, SK::LanguageEnglish), selected: language == "en") | ||
| 99 | + choice_option(value: "tr", label: s(lang, SK::LanguageTurkish), selected: language == "tr") | ||
| 100 | + </select> | ||
| 101 | + <p class="muted">(effective_line.as_str())</p> | ||
| 102 | + <button class="button" type="submit">(s(lang, SK::Save))</button> | ||
| 103 | + </form> | ||
| 104 | + <h2>(s(lang, SK::StorageTitle))</h2> | ||
| 105 | + quota_bar(lang: lang, used: used, quota: quota) | ||
| 106 | + <p class="muted">(used_line.as_str())</p> | ||
| 107 | + </section> | ||
| 108 | + }) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// `GET /settings`. | ||
| 112 | +#[page("/settings")] | ||
| 113 | +async fn settings_page(cx: &Cx) -> Result<impl View> { | ||
| 114 | + let state = app_context::<AppState>(cx); | ||
| 115 | + let viewer = require_member(cx).await?; | ||
| 116 | + let lang = viewer_lang(cx, &viewer); | ||
| 117 | + let query: SettingsQuery = parse_query_params(cx).unwrap_or_default(); | ||
| 118 | + let info = ViewerInfo::of(&viewer, state.family.list()); | ||
| 119 | + let flash = (query.notice == "saved").then(|| s(lang, SK::Saved)); | ||
| 120 | + let refusal: Option<&'static str> = | ||
| 121 | + (!query.refusal.is_empty()).then(|| match query.refusal.as_str() { | ||
| 122 | + "choice" => s(lang, SK::RefusalChoice), | ||
| 123 | + _ => s(lang, SK::RefusalGeneric), | ||
| 124 | + }); | ||
| 125 | + let effective = match viewer | ||
| 126 | + .member | ||
| 127 | + .locale_override | ||
| 128 | + .as_deref() | ||
| 129 | + .unwrap_or(viewer.member.locale.as_str()) | ||
| 130 | + { | ||
| 131 | + "tr" => "Türkçe", | ||
| 132 | + _ => "English", | ||
| 133 | + }; | ||
| 134 | + let language = viewer.member.locale_override.clone().unwrap_or_default(); | ||
| 135 | + Ok(view! { | ||
| 136 | + shell(title: s(lang, SK::Title), lang: lang, viewer: Some(&info), | ||
| 137 | + settings_body( | ||
| 138 | + lang: lang, | ||
| 139 | + csrf: viewer.session.csrf_token.as_str(), | ||
| 140 | + theme: viewer.member.theme.as_str(), | ||
| 141 | + language: language.as_str(), | ||
| 142 | + effective: effective, | ||
| 143 | + used: viewer.member.used_bytes, | ||
| 144 | + quota: viewer.member.quota_bytes, | ||
| 145 | + flash: flash, | ||
| 146 | + refusal: refusal, | ||
| 147 | + ) | ||
| 148 | + ) | ||
| 149 | + }) | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +/// `POST /settings`: saves the theme and the language. Anything else than the choices is refused with the | ||
| 153 | +/// `choice` word, and nothing is written. | ||
| 154 | +#[route(POST "/settings")] | ||
| 155 | +async fn save_settings(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<SeeOther> { | ||
| 156 | + let state = app_context::<AppState>(cx); | ||
| 157 | + let viewer: Viewer = require_csrf(cx, &form.csrf).await?; | ||
| 158 | + let theme = form.theme.trim(); | ||
| 159 | + let locale = match form.language.trim() { | ||
| 160 | + "" => None, | ||
| 161 | + code @ ("en" | "tr") => Some(code), | ||
| 162 | + _ => return Ok(see_other("/settings?refusal=choice")), | ||
| 163 | + }; | ||
| 164 | + if !matches!(theme, "system" | "light" | "dark") { | ||
| 165 | + return Ok(see_other("/settings?refusal=choice")); | ||
| 166 | + } | ||
| 167 | + let sub = viewer.member.sub.clone(); | ||
| 168 | + match state.store.set_theme(&sub, theme).await { | ||
| 169 | + Ok(()) => {} | ||
| 170 | + Err(CoreError::Invalid(_)) => return Ok(see_other("/settings?refusal=choice")), | ||
| 171 | + Err(error) => return Err(error.into()), | ||
| 172 | + } | ||
| 173 | + state.store.set_locale_override(&sub, locale).await?; | ||
| 174 | + state.live.bump(&Topic::Account(sub)); | ||
| 175 | + Ok(see_other("/settings?notice=saved")) | ||
| 176 | +} | ||
crates/in-web/src/pages/share_dialog.rsmodified+1 -1
| @@ -245,7 +245,7 @@ async fn share_page(cx: &Cx) -> Result<impl View> { | |||
| 245 | ItemKind::Folder => format!("/drive/{id}"), | 245 | ItemKind::Folder => format!("/drive/{id}"), |
| 246 | }; | 246 | }; |
| 247 | let csrf = viewer.session.csrf_token.clone(); | 247 | let csrf = viewer.session.csrf_token.clone(); |
| 248 | - let info = ViewerInfo::of(&viewer); | 248 | + let info = ViewerInfo::of(&viewer, state.family.list()); |
| 249 | Ok(view! { | 249 | Ok(view! { |
| 250 | shell(title: name.as_str(), lang: lang, viewer: Some(&info), | 250 | shell(title: name.as_str(), lang: lang, viewer: Some(&info), |
| 251 | share_body(lang: lang, name: name.as_str(), kind: kind_word(kind), id: id.as_str(), | 251 | share_body(lang: lang, name: name.as_str(), kind: kind_word(kind), id: id.as_str(), |
crates/in-web/src/pages/shared.rsmodified+1 -1
| @@ -117,7 +117,7 @@ async fn shared_page(cx: &Cx) -> Result<impl View> { | |||
| 117 | let viewer = require_member(cx).await?; | 117 | let viewer = require_member(cx).await?; |
| 118 | let lang = viewer_lang(cx, &viewer); | 118 | let lang = viewer_lang(cx, &viewer); |
| 119 | let items = state.store.shared_with(&viewer.member.sub).await?; | 119 | let items = state.store.shared_with(&viewer.member.sub).await?; |
| 120 | - let info = ViewerInfo::of(&viewer); | 120 | + let info = ViewerInfo::of(&viewer, state.family.list()); |
| 121 | let title = share_s(lang, SK::SharedTitle); | 121 | let title = share_s(lang, SK::SharedTitle); |
| 122 | Ok(view! { | 122 | Ok(view! { |
| 123 | shell(title: title, lang: lang, viewer: Some(&info), | 123 | shell(title: title, lang: lang, viewer: Some(&info), |
crates/in-web/src/pages/sign_in.rsmodified+9 -3
| @@ -11,7 +11,6 @@ use std::time::Duration; | |||
| 11 | 11 | ||
| 12 | use http::header::USER_AGENT; | 12 | use http::header::USER_AGENT; |
| 13 | use in_core::error::{Error as CoreError, Result as CoreResult}; | 13 | use in_core::error::{Error as CoreError, Result as CoreResult}; |
| 14 | -use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 15 | use in_core::secret; | 14 | use in_core::secret; |
| 16 | use in_core::store::members::MemberFields; | 15 | use in_core::store::members::MemberFields; |
| 17 | use in_core::store::sessions::NewSession; | 16 | use in_core::store::sessions::NewSession; |
| @@ -184,6 +183,13 @@ async fn callback(cx: &Cx, query: Option<Form<CallbackQuery>>) -> Result<SeeOthe | |||
| 184 | Err(error) => return Ok(problem_for(&error)), | 183 | Err(error) => return Ok(problem_for(&error)), |
| 185 | }; | 184 | }; |
| 186 | 185 | ||
| 186 | + let default_quota = in_core::settings::resolve( | ||
| 187 | + &state.store, | ||
| 188 | + &state.config.limits, | ||
| 189 | + in_core::settings::DEFAULT_QUOTA_KEY, | ||
| 190 | + ) | ||
| 191 | + .await? | ||
| 192 | + .value; | ||
| 187 | let member = state | 193 | let member = state |
| 188 | .store | 194 | .store |
| 189 | .upsert_member_from_claims( | 195 | .upsert_member_from_claims( |
| @@ -198,7 +204,7 @@ async fn callback(cx: &Cx, query: Option<Form<CallbackQuery>>) -> Result<SeeOthe | |||
| 198 | // Sign-in claims carry no directory timestamp, so the store uses the sign-in time. | 204 | // Sign-in claims carry no directory timestamp, so the store uses the sign-in time. |
| 199 | im_updated_at: String::new(), | 205 | im_updated_at: String::new(), |
| 200 | }, | 206 | }, |
| 201 | - DEFAULT_MEMBER_QUOTA, | 207 | + default_quota, |
| 202 | ) | 208 | ) |
| 203 | .await?; | 209 | .await?; |
| 204 | if member.disabled { | 210 | if member.disabled { |
| @@ -344,7 +350,7 @@ mod tests { | |||
| 344 | picture_version: 0, | 350 | picture_version: 0, |
| 345 | im_updated_at: String::new(), | 351 | im_updated_at: String::new(), |
| 346 | }, | 352 | }, |
| 347 | - DEFAULT_MEMBER_QUOTA, | 353 | + in_core::quota::DEFAULT_MEMBER_QUOTA, |
| 348 | ) | 354 | ) |
| 349 | .await | 355 | .await |
| 350 | .expect("member"); | 356 | .expect("member"); |
crates/in-web/src/pages/trash.rsmodified+1 -1
| @@ -156,7 +156,7 @@ async fn trash_page(cx: &Cx) -> Result<impl View> { | |||
| 156 | let lang = viewer_lang(cx, &viewer); | 156 | let lang = viewer_lang(cx, &viewer); |
| 157 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); | 157 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); |
| 158 | let listing = state.store.list_trash(&viewer.member.sub).await?; | 158 | let listing = state.store.list_trash(&viewer.member.sub).await?; |
| 159 | - let info = ViewerInfo::of(&viewer); | 159 | + let info = ViewerInfo::of(&viewer, state.family.list()); |
| 160 | let csrf = viewer.session.csrf_token.clone(); | 160 | let csrf = viewer.session.csrf_token.clone(); |
| 161 | let title = d(lang, DK::Trash); | 161 | let title = d(lang, DK::Trash); |
| 162 | Ok(view! { | 162 | Ok(view! { |
crates/in-web/src/pages/view.rsmodified+1 -1
| @@ -268,7 +268,7 @@ async fn view_page(cx: &Cx) -> Result<impl View> { | |||
| 268 | } | 268 | } |
| 269 | }; | 269 | }; |
| 270 | let csrf = viewer.session.csrf_token.clone(); | 270 | let csrf = viewer.session.csrf_token.clone(); |
| 271 | - let info = ViewerInfo::of(&viewer); | 271 | + let info = ViewerInfo::of(&viewer, state.family.list()); |
| 272 | let title = file.name.clone(); | 272 | let title = file.name.clone(); |
| 273 | Ok(view! { | 273 | Ok(view! { |
| 274 | shell(title: title.as_str(), lang: lang, viewer: Some(&info), | 274 | shell(title: title.as_str(), lang: lang, viewer: Some(&info), |
crates/in-web/src/state.rsmodified+3 -0
| @@ -6,6 +6,7 @@ use in_core::blob::BlobStore; | |||
| 6 | use in_core::config::Config; | 6 | use in_core::config::Config; |
| 7 | use in_core::store::Store; | 7 | use in_core::store::Store; |
| 8 | 8 | ||
| 9 | +use crate::family::FamilyCache; | ||
| 9 | use crate::live::LiveHub; | 10 | use crate::live::LiveHub; |
| 10 | use crate::oidc::OidcClient; | 11 | use crate::oidc::OidcClient; |
| 11 | use crate::throttle::ShareThrottles; | 12 | use crate::throttle::ShareThrottles; |
| @@ -29,4 +30,6 @@ pub struct AppState { | |||
| 29 | pub oidc: Option<Arc<OidcClient>>, | 30 | pub oidc: Option<Arc<OidcClient>>, |
| 30 | /// The failure windows of share-link passwords. | 31 | /// The failure windows of share-link passwords. |
| 31 | pub throttles: Arc<ShareThrottles>, | 32 | pub throttles: Arc<ShareThrottles>, |
| 33 | + /// The switcher list of the family, refreshed by the family worker. | ||
| 34 | + pub family: Arc<FamilyCache>, | ||
| 32 | } | 35 | } |
crates/in-web/src/sweeper.rsmodified+7 -11
| @@ -30,12 +30,6 @@ pub const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60); | |||
| 30 | /// Age a blob or a staged file must reach before the sweeper may remove it for lacking a row: 24 hours. | 30 | /// Age a blob or a staged file must reach before the sweeper may remove it for lacking a row: 24 hours. |
| 31 | pub const ORPHAN_GRACE: Duration = Duration::from_secs(24 * 60 * 60); | 31 | pub const ORPHAN_GRACE: Duration = Duration::from_secs(24 * 60 * 60); |
| 32 | 32 | ||
| 33 | -/// Trash older than this many days is purged when the `purge_after_days` setting is absent: 30. | ||
| 34 | -pub const DEFAULT_PURGE_AFTER_DAYS: u64 = 30; | ||
| 35 | - | ||
| 36 | -/// The settings key that overrides [`DEFAULT_PURGE_AFTER_DAYS`]. | ||
| 37 | -pub const PURGE_SETTING: &str = "purge_after_days"; | ||
| 38 | - | ||
| 39 | /// The settings key that records when the quota check last ran. | 33 | /// The settings key that records when the quota check last ran. |
| 40 | const DRIFT_SETTING: &str = "quota_drift_checked_at"; | 34 | const DRIFT_SETTING: &str = "quota_drift_checked_at"; |
| 41 | 35 | ||
| @@ -96,11 +90,13 @@ fn log_step<T>(step: &str, outcome: Result<T>) { | |||
| 96 | /// The number of days trash is kept: the setting when it holds a number, else the default. Clamped to 1 to | 90 | /// The number of days trash is kept: the setting when it holds a number, else the default. Clamped to 1 to |
| 97 | /// 3650 days. | 91 | /// 3650 days. |
| 98 | pub async fn purge_after_days(state: &AppState) -> Result<u64> { | 92 | pub async fn purge_after_days(state: &AppState) -> Result<u64> { |
| 99 | - let value = state.store.get_setting(PURGE_SETTING).await?; | 93 | + let resolved = in_core::settings::resolve( |
| 100 | - Ok(value | 94 | + &state.store, |
| 101 | - .and_then(|text| text.trim().parse::<u64>().ok()) | 95 | + &state.config.limits, |
| 102 | - .unwrap_or(DEFAULT_PURGE_AFTER_DAYS) | 96 | + in_core::settings::PURGE_KEY, |
| 103 | - .clamp(1, 3650)) | 97 | + ) |
| 98 | + .await?; | ||
| 99 | + Ok(u64::try_from(resolved.value).unwrap_or(1).clamp(1, 3650)) | ||
| 104 | } | 100 | } |
| 105 | 101 | ||
| 106 | /// Purges trash older than the retention period, and deletes the bytes the store released. The rows go first; | 102 | /// Purges trash older than the retention period, and deletes the bytes the store released. The rows go first; |
crates/in-web/src/views/mod.rsmodified+43 -6
| @@ -8,8 +8,11 @@ use topcoat::view::{Child, View, component, view}; | |||
| 8 | 8 | ||
| 9 | use crate::assets::{DRIVE_JS_HREF, MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF, VIEWER_JS_HREF}; | 9 | use crate::assets::{DRIVE_JS_HREF, MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF, VIEWER_JS_HREF}; |
| 10 | use crate::auth::Viewer; | 10 | use crate::auth::Viewer; |
| 11 | +use crate::family::FamilyLink; | ||
| 11 | use crate::i18n::Lang; | 12 | use crate::i18n::Lang; |
| 13 | +use crate::i18n::admin::{AK, a}; | ||
| 12 | use crate::i18n::drive::{DK, d}; | 14 | use crate::i18n::drive::{DK, d}; |
| 15 | +use crate::i18n::settings::{SK as SettingsK, s as settings_s}; | ||
| 13 | use crate::i18n::share::{SK, s as share_s}; | 16 | use crate::i18n::share::{SK, s as share_s}; |
| 14 | use crate::i18n::shell::{K, t}; | 17 | use crate::i18n::shell::{K, t}; |
| 15 | use crate::views::drive::quota_bar; | 18 | use crate::views::drive::quota_bar; |
| @@ -29,17 +32,23 @@ pub struct ViewerInfo { | |||
| 29 | pub used: i64, | 32 | pub used: i64, |
| 30 | /// The viewer's quota in bytes. | 33 | /// The viewer's quota in bytes. |
| 31 | pub quota: i64, | 34 | pub quota: i64, |
| 35 | + /// The viewer's theme: `system`, `light` or `dark`. It goes on `<html data-theme>`. | ||
| 36 | + pub theme: String, | ||
| 37 | + /// The family switcher list, as the family worker last fetched it. | ||
| 38 | + pub family: Vec<FamilyLink>, | ||
| 32 | } | 39 | } |
| 33 | 40 | ||
| 34 | impl ViewerInfo { | 41 | impl ViewerInfo { |
| 35 | - /// What the shell needs to know about a signed-in viewer. | 42 | + /// What the shell needs to know about a signed-in viewer. `family` is the switcher list. |
| 36 | - pub fn of(viewer: &Viewer) -> Self { | 43 | + pub fn of(viewer: &Viewer, family: Vec<FamilyLink>) -> Self { |
| 37 | Self { | 44 | Self { |
| 38 | name: viewer.member.name.clone(), | 45 | name: viewer.member.name.clone(), |
| 39 | is_admin: viewer.member.is_admin, | 46 | is_admin: viewer.member.is_admin, |
| 40 | csrf: viewer.session.csrf_token.clone(), | 47 | csrf: viewer.session.csrf_token.clone(), |
| 41 | used: viewer.member.used_bytes, | 48 | used: viewer.member.used_bytes, |
| 42 | quota: viewer.member.quota_bytes, | 49 | quota: viewer.member.quota_bytes, |
| 50 | + theme: viewer.member.theme.clone(), | ||
| 51 | + family, | ||
| 43 | } | 52 | } |
| 44 | } | 53 | } |
| 45 | } | 54 | } |
| @@ -48,9 +57,10 @@ impl ViewerInfo { | |||
| 48 | /// app name. `child` is the page, placed in `<main>`. `drive_js` adds the upload script, which only the | 57 | /// app name. `child` is the page, placed in `<main>`. `drive_js` adds the upload script, which only the |
| 49 | /// drive pages need. | 58 | /// drive pages need. |
| 50 | /// | 59 | /// |
| 51 | -/// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and | 60 | +/// The topbar has the wordmark on the left, the service switcher in the middle (this service's pages, then |
| 52 | -/// the viewer's user menu on the right. The menu's sign-out form opts out of soft navigation, because | 61 | +/// the other family services from the family worker) and the viewer's user menu on the right. The menu's |
| 53 | -/// it ends in a redirect to `im`. `nav.js` reads the restart text from `<body data-restart-text>`. | 62 | +/// sign-out form opts out of soft navigation, because it ends in a redirect to `im`. `nav.js` reads the |
| 63 | +/// restart text from `<body data-restart-text>`. | ||
| 54 | #[component] | 64 | #[component] |
| 55 | pub async fn shell( | 65 | pub async fn shell( |
| 56 | title: &str, | 66 | title: &str, |
| @@ -60,9 +70,10 @@ pub async fn shell( | |||
| 60 | #[default] child: Child<'_>, | 70 | #[default] child: Child<'_>, |
| 61 | ) -> Result<impl View> { | 71 | ) -> Result<impl View> { |
| 62 | let document_title = format!("{title} \u{b7} in"); | 72 | let document_title = format!("{title} \u{b7} in"); |
| 73 | + let theme = viewer.map_or("system", |v| v.theme.as_str()); | ||
| 63 | Ok(view! { | 74 | Ok(view! { |
| 64 | <!DOCTYPE html> | 75 | <!DOCTYPE html> |
| 65 | - <html lang=(lang.code()) data-theme="system"> | 76 | + <html lang=(lang.code()) data-theme=(theme)> |
| 66 | <head> | 77 | <head> |
| 67 | <meta charset="utf-8"> | 78 | <meta charset="utf-8"> |
| 68 | <meta name="viewport" content="width=device-width, initial-scale=1"> | 79 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| @@ -85,6 +96,11 @@ pub async fn shell( | |||
| 85 | <a href="/shared">(share_s(lang, SK::NavShared))</a> | 96 | <a href="/shared">(share_s(lang, SK::NavShared))</a> |
| 86 | <a href="/links">(share_s(lang, SK::NavLinks))</a> | 97 | <a href="/links">(share_s(lang, SK::NavLinks))</a> |
| 87 | <a href="/trash">(d(lang, DK::Trash))</a> | 98 | <a href="/trash">(d(lang, DK::Trash))</a> |
| 99 | + if let Some(viewer) = viewer { | ||
| 100 | + for link in &viewer.family { | ||
| 101 | + switch_link(name: link.name.as_str(), url: link.url.as_str()) | ||
| 102 | + } | ||
| 103 | + } | ||
| 88 | } | 104 | } |
| 89 | </nav> | 105 | </nav> |
| 90 | <div class="topbar-end"> | 106 | <div class="topbar-end"> |
| @@ -92,6 +108,10 @@ pub async fn shell( | |||
| 92 | quota_bar(lang: lang, used: viewer.used, quota: viewer.quota) | 108 | quota_bar(lang: lang, used: viewer.used, quota: viewer.quota) |
| 93 | <details class="user-menu"> | 109 | <details class="user-menu"> |
| 94 | <summary>(viewer.name.as_str())</summary> | 110 | <summary>(viewer.name.as_str())</summary> |
| 111 | + <a href="/settings">(s_title(lang))</a> | ||
| 112 | + if viewer.is_admin { | ||
| 113 | + <a href="/admin">(a_title(lang))</a> | ||
| 114 | + } | ||
| 95 | <form method="post" action="/auth/logout" data-hard=""> | 115 | <form method="post" action="/auth/logout" data-hard=""> |
| 96 | <input type="hidden" name="csrf" value=(viewer.csrf.as_str())> | 116 | <input type="hidden" name="csrf" value=(viewer.csrf.as_str())> |
| 97 | <button class="button" type="submit">(t(lang, K::SignOut))</button> | 117 | <button class="button" type="submit">(t(lang, K::SignOut))</button> |
| @@ -109,6 +129,23 @@ pub async fn shell( | |||
| 109 | }) | 129 | }) |
| 110 | } | 130 | } |
| 111 | 131 | ||
| 132 | +/// The menu link to the settings page, in the viewer's language. | ||
| 133 | +fn s_title(lang: Lang) -> &'static str { | ||
| 134 | + settings_s(lang, SettingsK::Title) | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// The menu link to the administration page, in the viewer's language. | ||
| 138 | +fn a_title(lang: Lang) -> &'static str { | ||
| 139 | + a(lang, AK::Title) | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// One other family service in the switcher. The name and the URL are escaped by `view!`, and the URL was | ||
| 143 | +/// checked by `family::usable` before it was stored. | ||
| 144 | +#[component] | ||
| 145 | +pub async fn switch_link(name: &str, url: &str) -> Result<impl View> { | ||
| 146 | + Ok(view! { <a class="switch-link" href=(url) rel="noopener">(name)</a> }) | ||
| 147 | +} | ||
| 148 | + | ||
| 112 | /// An error message for a failed action. Forms show it above their fields. | 149 | /// An error message for a failed action. Forms show it above their fields. |
| 113 | #[allow(dead_code)] // The first form that can fail a check uses it. | 150 | #[allow(dead_code)] // The first form that can fail a check uses it. |
| 114 | #[component] | 151 | #[component] |
deploy/ferron.kdladded+6 -0
| @@ -0,0 +1,6 @@ | |||
| 1 | +// Example Ferron site for `in`. Ferron terminates TLS and forwards to the loopback listener of `in`. | ||
| 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. | ||
| 4 | +in.example.com { | ||
| 5 | + proxy http://127.0.0.1:7655 | ||
| 6 | +} | ||
deploy/in.serviceadded+47 -0
| @@ -0,0 +1,47 @@ | |||
| 1 | +[Unit] | ||
| 2 | +Description=in: the family's file drive | ||
| 3 | +After=network-online.target | ||
| 4 | +Wants=network-online.target | ||
| 5 | +StartLimitIntervalSec=60 | ||
| 6 | +StartLimitBurst=5 | ||
| 7 | + | ||
| 8 | +[Service] | ||
| 9 | +Type=simple | ||
| 10 | +User=in | ||
| 11 | +Group=in | ||
| 12 | +Environment=IN_CONFIG=/etc/in/in.toml | ||
| 13 | +ExecStart=/usr/local/bin/in serve | ||
| 14 | +WorkingDirectory=/var/lib/in | ||
| 15 | +Restart=on-failure | ||
| 16 | +RestartSec=2 | ||
| 17 | +LimitNOFILE=65536 | ||
| 18 | + | ||
| 19 | +# Hardening. The service writes only to its state directory; see `[backup] dir` in in.toml and add that path | ||
| 20 | +# to ReadWritePaths if backups are on. | ||
| 21 | +NoNewPrivileges=yes | ||
| 22 | +ProtectSystem=strict | ||
| 23 | +ProtectHome=yes | ||
| 24 | +ReadWritePaths=/var/lib/in | ||
| 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 | ||