From 23b6bde2b425d62d9bc7a1caa99e8e101c28311f Mon Sep 17 00:00:00 2001 From: daylioti Date: Tue, 1 Dec 2026 14:16:52 +0200 Subject: [PATCH 1/2] Add export and import to the qdb dashboard The dashboard gains an Export / Import view. Parts of the data root are picked from a two-level tree with a select-all: the root's directories and their subdirectories. Export streams a plain .tar.gz built from the files on disk, led by a manifest naming the parts it was taken at. Links inside the root are written relative and rebased under the importing root. Import is off unless the dashboard is started with QUANTA_DB_DASHBOARD_IMPORT=on and a token. The upload is spooled and checked end to end before anything is written. Merge adds and overwrites; replace also removes what the archive lacks within each selected part, and is refused for a part wider than the archive was exported at. Whatever an import displaces goes to the trash bin. The page's static files are now served without the token, and the page asks for the token when the API answers 401, then sends it as an Authorization header. This also fixes a token-protected dashboard opened with ?token= loading without its stylesheet and script. The Docker wrapper hands the extension's trashbin_dir to qdbstat, so an import displaces files into the site's own trash bin. --- Dockerfile | 10 +- docker/qdbstat-dashboard.sh | 41 +- docker/supervisord.conf | 3 +- docker/tests/02_qdbstat_dashboard.sh | 34 +- qdb/Cargo.lock | 22 + qdb/Cargo.toml | 5 + qdb/README.md | 65 +- qdb/docs/usage.md | 5 +- qdb/src/bin/qdbstat.rs | 82 +- qdb/src/dashboard.rs | 566 ++++++- qdb/src/dashboard/app.css | 360 +++++ qdb/src/dashboard/app.js | 1116 +++++++++++++- qdb/src/dashboard/index.html | 11 + qdb/src/transfer.rs | 2061 ++++++++++++++++++++++++++ 14 files changed, 4277 insertions(+), 104 deletions(-) create mode 100644 qdb/src/transfer.rs diff --git a/Dockerfile b/Dockerfile index 02fb8fb39..a92a44d6f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -367,12 +367,14 @@ COPY --link --from=qdb-builder /out/quanta_db.so /usr/local/lib/php/extensions/q # binary serves those counters as Prometheus /metrics with --listen; supervisord # runs it that way when QUANTA_DB_METRICS_LISTEN is set (docker/qdbstat-exporter.sh). # -# It also serves a read-only web browser for the indexed files with --dashboard, -# started by supervisord when QUANTA_DB_DASHBOARD_LISTEN is set +# It also serves a web browser for the indexed files with --dashboard, started +# by supervisord when QUANTA_DB_DASHBOARD_LISTEN is set # (docker/qdbstat-dashboard.sh). That one carries node paths and document # content rather than counters, so it binds loopback unless told otherwise and -# takes an optional QUANTA_DB_DASHBOARD_TOKEN. Neither port is EXPOSEd: this -# image is a base for deployments that never asked to open one. +# takes an optional QUANTA_DB_DASHBOARD_TOKEN. It exports parts of the site, and +# imports them only with QUANTA_DB_DASHBOARD_IMPORT=on plus the token. Neither +# port is EXPOSEd: this image is a base for deployments that never asked to +# open one. # # qdbd: the qdb daemon. Loads the whole node tree into a shared-memory # segment at boot, keeps it authoritative via inotify + periodic reconcile, and diff --git a/docker/qdbstat-dashboard.sh b/docker/qdbstat-dashboard.sh index 51217e6cf..c70aa655b 100755 --- a/docker/qdbstat-dashboard.sh +++ b/docker/qdbstat-dashboard.sh @@ -1,10 +1,11 @@ #!/bin/sh # supervisord wrapper for the qdb web dashboard. # -# `qdbstat --dashboard` serves a read-only browser for the index: every node, -# its place in the tree, its links, and the document files themselves, rendered -# out of the shared-memory segment. It answers "what is in the DB" where -# /metrics answers "is the DB healthy". +# `qdbstat --dashboard` serves a browser for the index: every node, its place in +# the tree, its links, and the document files themselves, rendered out of the +# shared-memory segment. It answers "what is in the DB" where /metrics answers +# "is the DB healthy". It also exports parts of the site as a .tar.gz and, only +# when switched on, imports one back (see below). # # It runs INSIDE this container for the same reason the exporter does: the # metrics arena is under /tmp/quanta_db, on the container's own filesystem, so @@ -21,12 +22,18 @@ # * the default address is loopback (127.0.0.1:9110), reachable with # `kubectl port-forward` but not from the cluster. Binding 0.0.0.0 is # possible and has to be typed; -# * QUANTA_DB_DASHBOARD_TOKEN, if set, is required on every request. Set it -# for anything wider than loopback -- an address is not access control. +# * QUANTA_DB_DASHBOARD_TOKEN, if set, is required for everything the page +# loads from the site (the page itself loads without it and asks for it). +# Set it for anything wider than loopback -- an address is not access +# control. # # QUANTA_DB_DASHBOARD_BASE_PATH is read by qdbstat itself (not here) and names # the URL prefix the dashboard is reached at, for an ingress that routes a # sub-path to this port without stripping it. +# +# Import is the one route that writes, and it is off unless +# QUANTA_DB_DASHBOARD_IMPORT=on AND QUANTA_DB_DASHBOARD_TOKEN is set (qdbstat +# checks both). What an import overwrites or removes goes to the trash bin. set -e LISTEN="${QUANTA_DB_DASHBOARD_LISTEN:-}" @@ -49,8 +56,22 @@ case "$LISTEN" in ;; esac -# Read-only throughout: a read-only mapping of the segment, no route that -# mutates, and no lock held. Like the exporter, a crash loop here would be a -# bug rather than a capacity problem, so supervisord's own restart is the right -# response and there is no throttle of the kind qdbd-run.sh needs. +# The trash bin an import moves displaced files into: the site's own, where +# Quanta's deletes and the extension's land, so recovery is done in one place. +# The image keeps its path in the extension's ini (re-pointed per site by +# docker-entrypoint.sh), which qdbstat does not read; without this it would +# fall back to pod-local derived storage, which a restart loses. A value set in +# the environment wins. +INI="${PHP_INI_DIR:-/usr/local/etc/php}/conf.d/quanta-db.ini" +if [ -z "${QUANTA_DB_TRASHBIN_DIR:-}" ] && [ -f "$INI" ]; then + TRASH=$(sed -n 's/^quanta_db\.trashbin_dir=//p' "$INI" | tail -n 1) + if [ -n "$TRASH" ]; then + export QUANTA_DB_TRASHBIN_DIR="$TRASH" + fi +fi + +# Read-only unless import is on: a read-only mapping of the segment and no +# lock held. Like the exporter, a crash loop here would be a bug rather than a +# capacity problem, so supervisord's own restart is the right response and +# there is no throttle of the kind qdbd-run.sh needs. exec qdbstat --dashboard "$LISTEN" "$@" diff --git a/docker/supervisord.conf b/docker/supervisord.conf index c59e73b1f..75fdff8e2 100644 --- a/docker/supervisord.conf +++ b/docker/supervisord.conf @@ -86,7 +86,8 @@ stderr_logfile = /dev/stderr stdout_logfile_maxbytes = 0 stderr_logfile_maxbytes = 0 -; The web dashboard: a read-only browser for what the index actually holds. +; The web dashboard: a browser for what the index actually holds, plus export +; and (only with QUANTA_DB_DASHBOARD_IMPORT=on and a token) import of the site. ; Opt-in on QUANTA_DB_DASHBOARD_LISTEN, same EXITED-when-unset shape as the ; exporter above, and last for the same reason -- it inspects the other ; programs and must never be what keeps them from starting. diff --git a/docker/tests/02_qdbstat_dashboard.sh b/docker/tests/02_qdbstat_dashboard.sh index 93e2f2e66..ba2fed04c 100755 --- a/docker/tests/02_qdbstat_dashboard.sh +++ b/docker/tests/02_qdbstat_dashboard.sh @@ -20,11 +20,13 @@ TMP="${TMPDIR:-/tmp}/qdbstat-dashboard-test.$$" mkdir -p "$TMP/bin" trap 'rm -rf "$TMP"' EXIT -# The stub prints its argv and exits 0, so a test can assert on what the -# wrapper would have run without needing a segment or a port. +# The stub prints its argv, and the trash bin it was handed, and exits 0, so a +# test can assert on what the wrapper would have run without needing a segment +# or a port. cat > "$TMP/bin/qdbstat" <<'STUB' #!/bin/sh echo "qdbstat $*" +echo "trash=${QUANTA_DB_TRASHBIN_DIR:-}" STUB chmod +x "$TMP/bin/qdbstat" PATH="$TMP/bin:$PATH" @@ -107,5 +109,33 @@ case "$out" in *) ok ;; esac +# --- the trash bin an import uses ------------------------------------------ + +# The image keeps the site's trash bin in the extension's ini, which qdbstat +# does not read: the wrapper hands it over, so an import displaces files to +# where Quanta's own deletes go and not to pod-local storage. +mkdir -p "$TMP/ini/conf.d" +printf 'quanta_db.root=/srv/site\nquanta_db.trashbin_dir=/srv/static/tmp/site/trashbin\n' \ + > "$TMP/ini/conf.d/quanta-db.ini" +run QUANTA_DB_DASHBOARD_LISTEN=127.0.0.1:9110 "PHP_INI_DIR=$TMP/ini" +case "$out" in + *"trash=/srv/static/tmp/site/trashbin"*) ok ;; + *) bad "the ini's trashbin_dir must reach qdbstat" "$out" ;; +esac + +# One set in the environment is a deliberate choice and wins. +run QUANTA_DB_DASHBOARD_LISTEN=127.0.0.1:9110 "PHP_INI_DIR=$TMP/ini" QUANTA_DB_TRASHBIN_DIR=/elsewhere +case "$out" in + *"trash=/elsewhere"*) ok ;; + *) bad "QUANTA_DB_TRASHBIN_DIR from the environment must win over the ini" "$out" ;; +esac + +# No ini at all (a bare qdbstat install) leaves qdbstat to its own default. +run QUANTA_DB_DASHBOARD_LISTEN=127.0.0.1:9110 "PHP_INI_DIR=$TMP/none" QUANTA_DB_TRASHBIN_DIR= +case "$out" in + *"trash=") ok ;; + *) bad "with no ini the wrapper must not invent a trash bin" "$out" ;; +esac + echo " $pass passed, $fail failed" [ "$fail" -eq 0 ] || exit 1 diff --git a/qdb/Cargo.lock b/qdb/Cargo.lock index e4e316eaf..53d92f497 100644 --- a/qdb/Cargo.lock +++ b/qdb/Cargo.lock @@ -424,6 +424,16 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -904,9 +914,11 @@ name = "quanta_db" version = "0.1.0" dependencies = [ "ext-php-rs", + "flate2", "inotify", "libc", "serde_json", + "tar", ] [[package]] @@ -1187,6 +1199,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" diff --git a/qdb/Cargo.toml b/qdb/Cargo.toml index f51665669..225ce4f9a 100644 --- a/qdb/Cargo.toml +++ b/qdb/Cargo.toml @@ -27,6 +27,11 @@ ext-php-rs = "0.15" serde_json = { version = "1", features = ["preserve_order"] } libc = "0.2" inotify = { version = "0.11", default-features = false } +# The dashboard's export/import archive: a plain .tar.gz, so a backup taken +# there is also readable with nothing but `tar`. No xattr support -- node +# trees carry none, and it would pull in a platform layer for nothing. +tar = { version = "0.4", default-features = false } +flate2 = "1" [profile.release] lto = true diff --git a/qdb/README.md b/qdb/README.md index 4f7901e82..1835d33df 100644 --- a/qdb/README.md +++ b/qdb/README.md @@ -129,7 +129,7 @@ one — `rate(quanta_db_served_total{source="fallback"}[5m])` can. ### Web dashboard -`--dashboard` serves a read-only browser for **what the index actually holds**: +`--dashboard` serves a browser for **what the index actually holds**: the node tree, each node's father, children and inlinks, and the document files themselves. Where `qdbstat` and `/metrics` answer "is the index healthy", this answers "what is in it" — which node is missing, which document failed to @@ -150,8 +150,11 @@ serving changes when it is on. | | | |---|---| | `QUANTA_DB_DASHBOARD_LISTEN` | `host:port` to serve on. Unset (or `off`/`0`/`false`) means the dashboard does not start | -| `QUANTA_DB_DASHBOARD_TOKEN` | Optional shared secret. When set, every route but `/healthz` requires `Authorization: Bearer ` or `?token=` | +| `QUANTA_DB_DASHBOARD_TOKEN` | Optional shared secret. When set, every `/api/*` route requires `Authorization: Bearer ` or `?token=`. The page itself loads without it and asks for the token when the URL does not carry one | | `QUANTA_DB_DASHBOARD_BASE_PATH` | URL prefix it is served under, e.g. `/qdb`. Empty (default) means the root | +| `QUANTA_DB_DASHBOARD_IMPORT` | `on` (or `--allow-import`) turns on import, the one route that writes. Needs the token too | +| `QUANTA_DB_DASHBOARD_IMPORT_MAX_MB` | Largest archive an import accepts, counted as what it expands to. Default `2048` | +| `QUANTA_DB_TRASHBIN_DIR` | Where an import moves what it overwrites or removes. The Docker wrapper takes it from `quanta_db.trashbin_dir` | **Serving it under a sub-path.** An ingress that routes `/qdb` to a backend does *not* strip that path — the request arrives spelled `/qdb/api/node` — so tell the @@ -168,9 +171,9 @@ against the directory of the current URL — without the trailing slash they wou resolve outside the prefix), and nothing outside it is served. That keeps the ingress plain: one path, one backend, no per-controller annotations. -Three views: **Files** (the node tree and every document), **Size** (what each -subtree weighs, as a treemap you can drill into) and **Stats** (the counters -`qdbstat` prints, in HTML). +Four views: **Files** (the node tree and every document), **Size** (what each +subtree weighs, as a treemap you can drill into), **Stats** (the counters +`qdbstat` prints, in HTML) and **Export / Import** (below). The Size view answers "what is heavy, and where" with two metrics that routinely disagree. *Documents on disk* sums each node's `data*.json`; *segment footprint* @@ -181,7 +184,8 @@ node pays a record; one un-imaged 2 MB document is the reverse. The second metric is the one to open when sizing `/dev/shm`: nothing else in the tooling attributes segment bytes to a *subtree*. -**Everything it shows comes from the shared-memory segment, never from disk.** +**Everything it shows comes from the shared-memory segment, never from disk** +(export and import, which work on the files, are the exception). That is what makes it worth opening during an incident: it shows what a PHP worker would be served, so a node that is on disk but not in the answer is the finding, not a rendering bug. A document the daemon imaged is walked back into @@ -192,6 +196,39 @@ It reads the segment even with `quanta_db.metrics=off` — with no arena to name the active epoch it takes the highest one in the segment directory — so it still works on a box where no PHP worker has run. +#### Export and import + +The Export / Import view moves parts of the data root between sites as a plain +`.tar.gz` that `tar` itself can read. Parts are picked from a two-level tree, +with a select-all: the root's directories (`db`, `_tpl`, …) and, under each, +its subdirectories (`db/_users`, `db/_translations`, …). A whole group also +carries the files directly inside it. + +- **Export** reads the files on disk, not the segment: an archive is a backup, + so payload files and links travel too. Dot-prefixed names and `_modules` + never do. A container link that points inside the root is written relative + and made absolute again under the importing site's root, so an archive holds + no deployment path. The archive leads with a manifest (`.qdb-export.json`) + naming the parts it was taken at. +- **Import** is off unless `QUANTA_DB_DASHBOARD_IMPORT=on` *and* a token are + set. The page reads the archive's manifest in the browser and offers its + parts before anything is uploaded. The server spools the upload and reads it + twice. The first pass writes nothing: a path that climbs out of the root, a + damaged or truncated archive, or a selected part the archive lacks refuses + the whole import. The second applies it, each file by temp file and rename. + - *Merge* adds and overwrites; nothing else changes. + - *Replace* makes each selected part exactly the archive's copy, removing + what it lacks. It is refused for a part wider than the archive was + exported at, so an export of `db/_users` can never replace all of `db`. + - Whatever an import overwrites or removes goes to the trash bin under + `-import/`, never deleted. The daemon picks the changes up through + inotify like any other write. + +An upload is the raw archive as the request body, so a reverse proxy in front +of the dashboard has to allow a body that size (nginx: `client_max_body_size`). +Progress comes back as JSON lines while the import runs, so a long one does +not sit behind a silent connection. + Exposure is the one thing to decide deliberately. `/metrics` carries counters, sizes and epochs; this carries **node paths and document bodies**, i.e. the site's content. Hence the loopback default, which `kubectl port-forward` reaches @@ -202,9 +239,19 @@ kubectl port-forward 9110:9110 # with QUANTA_DB_DASHBOARD_LISTEN=127.0.0 ``` Set `QUANTA_DB_DASHBOARD_TOKEN` for anything wider — a bind address is not -access control. The dashboard is read-only by construction (a `PROT_READ` -mapping, no mutating route, and a node name from the URL is only ever a hash -key, never a path), so the risk it carries is disclosure, not damage. +access control. Only the page's own HTML, stylesheet and script (the same bytes +in every deployment, naming no setting) and `/healthz` are served without it; +the page asks for the token, checks it against the server, and keeps it for the +tab, or for the browser if asked. It then sends it as an `Authorization` +header, so it stays out of URLs and access logs, except on an export download, +which is a plain link. Without import the dashboard is read-only by construction (a +`PROT_READ` mapping, no mutating route, and a node name from the URL is only +ever a hash key, never a path), so the risk it carries is disclosure, not +damage. Import changes that, hence its two switches: the opt-in, and the token, +which the write route checks again itself. A part name from the URL does reach +the filesystem there, so it is checked component by component (no `..`, no +dot-names, no `_modules`), and the upload has to declare a gzip or tar content +type, which no cross-site form can send. ## Build & test (Docker) diff --git a/qdb/docs/usage.md b/qdb/docs/usage.md index e7775ae35..b213e9ea8 100644 --- a/qdb/docs/usage.md +++ b/qdb/docs/usage.md @@ -123,8 +123,11 @@ are not. The extension has no `enabled` key and never reads any of these: | `QUANTA_DB_DAEMON=off` | `docker/qdbd-run.sh` | The supervisord wrapper exits immediately, so no daemon runs. The extension still loads and serves in fallback mode. | | `QUANTA_DB_METRICS_LISTEN` | `docker/qdbstat-exporter.sh` | `host:port` for the Prometheus `/metrics` exporter. Unset, the wrapper exits 0 and no port is opened. | | `QUANTA_DB_DASHBOARD_LISTEN` | `docker/qdbstat-dashboard.sh` | `host:port` for the web file browser. Unset, the wrapper exits 0 and no port is opened. | -| `QUANTA_DB_DASHBOARD_TOKEN` | `qdbstat --dashboard` | Optional shared secret for that dashboard; when set, every route but `/healthz` requires it. | +| `QUANTA_DB_DASHBOARD_TOKEN` | `qdbstat --dashboard` | Optional shared secret for that dashboard; when set, every `/api/*` route requires it, and the page asks for it if the URL has no `?token=`. Required for import. | | `QUANTA_DB_DASHBOARD_BASE_PATH` | `qdbstat --dashboard` | URL prefix it is served under (e.g. `/qdb`), for an ingress that routes a sub-path to it. Empty = the root. | +| `QUANTA_DB_DASHBOARD_IMPORT=on` | `qdbstat --dashboard` | Turns on the dashboard's import, the one route that writes to the data root. Also needs `QUANTA_DB_DASHBOARD_TOKEN`. Same as `--allow-import`. | +| `QUANTA_DB_DASHBOARD_IMPORT_MAX_MB` | `qdbstat --dashboard` | Largest archive an import accepts, counted as the size it expands to. Default `2048`. | +| `QUANTA_DB_TRASHBIN_DIR` | `qdbstat --dashboard` (via `docker/qdbstat-dashboard.sh`) | Where an import moves what it overwrites or removes. The wrapper copies it from the extension's `quanta_db.trashbin_dir`, so it is the site's own trash bin. | Each runs as its own supervisord program on its own port, separate from nginx and php-fpm, so turning either on changes nothing about how the site is served. diff --git a/qdb/src/bin/qdbstat.rs b/qdb/src/bin/qdbstat.rs index 0c0eaf4d0..8b0870e24 100644 --- a/qdb/src/bin/qdbstat.rs +++ b/qdb/src/bin/qdbstat.rs @@ -41,6 +41,10 @@ mod shm; mod image; #[path = "../dashboard.rs"] mod dashboard; +// Export/import for the dashboard: the one part of it that reads the data +// root's files rather than the segment, and the one part that can write. +#[path = "../transfer.rs"] +mod transfer; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -74,6 +78,14 @@ OPTIONS: (default: none, or $QUANTA_DB_DASHBOARD_BASE_PATH). Set it when an ingress routes a sub-path here: the request arrives with the prefix still on it. + --allow-import Let the dashboard apply uploaded archives to the + data root (default: off, or + $QUANTA_DB_DASHBOARD_IMPORT=on). Takes effect only + with $QUANTA_DB_DASHBOARD_TOKEN set. Uploads are + capped by $QUANTA_DB_DASHBOARD_IMPORT_MAX_MB + (default 2048, uncompressed); what an import + overwrites or removes goes to $QUANTA_DB_TRASHBIN_DIR + (default: the per-root derived dir). --exit-code Exit by verdict instead of always 0: 0 healthy, 1 degraded, 2 fallback, 3 no metrics. --no-color Disable ANSI color (also auto-off when piped or @@ -97,6 +109,7 @@ struct Args { listen: Option, dashboard: Option, base_path: String, + allow_import: bool, exit_code: bool, no_color: bool, } @@ -113,6 +126,9 @@ fn parse_args() -> Result { listen: None, dashboard: None, base_path: std::env::var("QUANTA_DB_DASHBOARD_BASE_PATH").unwrap_or_default(), + allow_import: std::env::var("QUANTA_DB_DASHBOARD_IMPORT") + .map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "on" | "true" | "yes")) + .unwrap_or(false), exit_code: false, no_color: false, }; @@ -175,6 +191,7 @@ fn parse_args() -> Result { a.dashboard = Some(addr); } "--base-path" => a.base_path = next("--base-path", &mut i)?, + "--allow-import" => a.allow_import = true, "--exit-code" => a.exit_code = true, "--no-color" => a.no_color = true, "-h" | "--help" => { @@ -1653,6 +1670,60 @@ fn exit_code(health: Health) -> i32 { } } +/// What the dashboard may export from and import into. +/// +/// Import needs three things, and each missing one is named back to the +/// operator rather than silently leaving the button grey: the opt-in, the +/// shared secret, and a root to write to. The secret is not optional here +/// the way it is for reading: a route that can rewrite `_users` is an account +/// takeover for anything that reaches it — which, without a secret, includes +/// any web page open in the operator's browser, through DNS rebinding against +/// a loopback port-forward. +fn transfer_policy(a: &Args, has_token: bool) -> transfer::Policy { + let root = a.root.as_ref().and_then(|r| r.canonicalize().ok()); + // The configured spelling, kept for link targets (see `Policy::link_root`). + // Only an absolute one: a relative root would make relative "absolute" links. + let link_root = a.root.clone().filter(|r| r.is_absolute() && root.is_some()); + let trash = std::env::var_os("QUANTA_DB_TRASHBIN_DIR") + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + .or_else(|| { + root.as_ref() + .and_then(|r| paths::derive_base(r).ok()) + .map(|b| b.join("trashbin")) + }); + let max_mb = std::env::var("QUANTA_DB_DASHBOARD_IMPORT_MAX_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|v| *v > 0) + .unwrap_or(transfer::DEFAULT_IMPORT_MAX_MB); + // Each reason is a sentence of its own: the startup log, the page and the + // refusal of an upload all show it after saying that import is off. + let off = if !a.allow_import { + Some("Start the dashboard with QUANTA_DB_DASHBOARD_IMPORT=on (or --allow-import) to enable it.") + } else if !has_token { + Some( + "It also needs QUANTA_DB_DASHBOARD_TOKEN: a route that can rewrite the database is never \ + served without the shared secret.", + ) + } else if root.is_none() { + Some("It needs the data root (--root or QUANTA_DB_ROOT).") + } else if trash.is_none() { + Some("It needs a trash bin for what an import displaces (QUANTA_DB_TRASHBIN_DIR).") + } else { + None + }; + transfer::Policy { + root, + link_root, + import: off.is_none(), + import_off: off.map(str::to_string), + max_bytes: max_mb.saturating_mul(1 << 20), + trash, + spool_dir: std::env::temp_dir(), + } +} + /// `/api/stats` for the dashboard: the same object `--json` prints. /// /// The dashboard does not build this itself because the snapshot is assembled @@ -1693,15 +1764,18 @@ fn main() { return; } - if let Some(addr) = args.dashboard { + if let Some(addr) = args.dashboard.clone() { + let token = std::env::var("QUANTA_DB_DASHBOARD_TOKEN") + .ok() + .filter(|v| !v.is_empty()); + let transfer = transfer_policy(&args, token.is_some()); let cfg = dashboard::Config { addr, shm_path, data_dir, - token: std::env::var("QUANTA_DB_DASHBOARD_TOKEN") - .ok() - .filter(|v| !v.is_empty()), + token, base_path: dashboard::normalize_base(&args.base_path), + transfer, }; if let Err(e) = dashboard::serve(cfg, dashboard_stats) { eprintln!("qdbstat: {e}"); diff --git a/qdb/src/dashboard.rs b/qdb/src/dashboard.rs index 713005aa4..dde5770c4 100644 --- a/qdb/src/dashboard.rs +++ b/qdb/src/dashboard.rs @@ -1,5 +1,5 @@ -//! `qdbstat --dashboard` — a read-only web browser for what the qdb -//! actually holds. +//! `qdbstat --dashboard` — a web browser for what the qdb actually holds, +//! and the export/import of parts of the data root. //! //! The terminal dashboard and `/metrics` answer "is the index healthy"; this //! answers "what is *in* it" — every node, its position in the tree, its links, @@ -12,15 +12,22 @@ //! while silently answering a different question — "what is on disk" rather //! than "what is served". When there is no segment it says so and shows //! nothing else. That is the useful answer, not a degraded one. -//! * **Read-only by construction.** The mapping is `PROT_READ`, no route -//! mutates, and node names arriving from a query string are only ever hash -//! keys for `SegmentReader::lookup` — they never become a path, so there is -//! no traversal surface to get wrong. +//! * **Read-only unless import is switched on.** The mapping is `PROT_READ`, +//! and node names arriving from a query string are only ever hash keys for +//! `SegmentReader::lookup` — they never become a path, so there is no +//! traversal surface to get wrong. The one route that writes, +//! `/api/import`, is off unless the operator opts in AND sets the shared +//! secret, and the part names it and `/api/export` take are checked in +//! `transfer`, the only module here that turns a request into a path. //! * **It serves content, not counters.** `/metrics` deliberately exposes no //! paths and no document bodies; this exposes both. Hence a loopback //! default and the optional shared-secret check below, where the exporter //! needs neither. //! +//! Export and import (`transfer`) are the exception to the first rule: an +//! archive is a backup, so it is made from the files, which are the source of +//! truth, and applied back to them. +//! //! Every request opens the segment afresh (see `View::open`). That costs an //! open + mmap + munmap and buys the two things a cached mapping cannot give: //! no epoch flip can happen *inside* a request, and a compaction can never @@ -28,7 +35,7 @@ #![allow(dead_code)] use std::io::{BufRead, BufReader, Read, Write}; -use std::net::{TcpListener, TcpStream}; +use std::net::TcpListener; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; @@ -39,6 +46,7 @@ use serde_json::{json, Map, Value}; use crate::image; use crate::metrics; use crate::shm::{self, Lookup, RecordView, SegmentReader}; +use crate::transfer; /// Loopback, unlike the exporter's `0.0.0.0`, and for the reason in the module /// docs: the payload here is site content. `kubectl port-forward` reaches it @@ -70,7 +78,11 @@ const LIST_DEFAULT_LIMIT: usize = 200; /// Request-line and header limits. Neither is a security boundary on its own — /// the timeouts are — but they keep one connection from reading forever. -const MAX_LINE: usize = 8 * 1024; +/// +/// Sized for the export and import routes, whose part list rides in the query +/// string: a few hundred `part=` pairs is a legitimate request, and a GET is +/// what lets a browser stream the download straight to disk. +const MAX_LINE: usize = 64 * 1024; const MAX_HEADERS: usize = 64; const INDEX_HTML: &str = include_str!("dashboard/index.html"); @@ -82,8 +94,9 @@ pub struct Config { pub addr: String, pub shm_path: PathBuf, pub data_dir: PathBuf, - /// Shared secret required on every route but `/healthz`, or `None` for an - /// unauthenticated dashboard (announced at startup). + /// Shared secret required on every `/api/*` route, or `None` for an + /// unauthenticated dashboard (announced at startup). `/healthz` and the + /// page's own static files are served without it. pub token: Option, /// URL prefix this dashboard is reached at, normalised by /// [`normalize_base`]: `""` at the root, or `"/qdb"` — leading slash, no @@ -98,6 +111,8 @@ pub struct Config { /// `/app.js`, outside the prefix. Knowing the prefix here fixes both, and /// keeps the deployment's ingress plain. pub base_path: String, + /// What `/api/export` and `/api/import` may do, and with which root. + pub transfer: transfer::Policy, } /// Normalise a base path: `""`, `"/"`, `"qdb"`, `"/qdb/"` all mean the same two @@ -916,39 +931,44 @@ fn route_summary(view: &View) -> Response { // HTTP plumbing // --------------------------------------------------------------------------- +/// A body produced while it is sent: an export, or an import's progress. +/// Run on the connection's own thread, after the head is on the wire. +pub type BodyStream = Box std::io::Result<()>>; + pub struct Response { status: u16, content_type: &'static str, body: Vec, /// Extra headers, already formatted as `Name: value` lines. extra: Vec, + /// When set, `body` is unused and the response has no Content-Length: + /// it ends when the connection closes, which `Connection: close` already + /// promises. Its size is not known until it has been produced. + stream: Option, +} + +fn response(status: u16, content_type: &'static str, body: Vec) -> Response { + Response { status, content_type, body, extra: Vec::new(), stream: None } } fn json_response(status: u16, v: &Value) -> Response { - Response { + response( status, - content_type: "application/json; charset=utf-8", - body: serde_json::to_vec(v).unwrap_or_else(|_| b"{\"error\":\"encode failed\"}".to_vec()), - extra: Vec::new(), - } + "application/json; charset=utf-8", + serde_json::to_vec(v).unwrap_or_else(|_| b"{\"error\":\"encode failed\"}".to_vec()), + ) } fn text_response(status: u16, body: &str) -> Response { - Response { - status, - content_type: "text/plain; charset=utf-8", - body: body.as_bytes().to_vec(), - extra: Vec::new(), - } + response(status, "text/plain; charset=utf-8", body.as_bytes().to_vec()) } fn asset(content_type: &'static str, body: &str) -> Response { - Response { - status: 200, - content_type, - body: body.as_bytes().to_vec(), - extra: Vec::new(), - } + response(200, content_type, body.as_bytes().to_vec()) +} + +fn streamed(content_type: &'static str, stream: BodyStream) -> Response { + Response { status: 200, content_type, body: Vec::new(), extra: Vec::new(), stream: Some(stream) } } fn bad_request(detail: &str) -> Response { @@ -964,7 +984,12 @@ fn reason(status: u16) -> &'static str { 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", + 409 => "Conflict", + 411 => "Length Required", + 413 => "Payload Too Large", + 415 => "Unsupported Media Type", 429 => "Too Many Requests", + 500 => "Internal Server Error", 503 => "Service Unavailable", _ => "Error", } @@ -980,8 +1005,13 @@ impl Response { /// it: one request per connection, and a keep-alive we do not honour makes /// every client wait out its own timeout. fn encode(&self, head_only: bool) -> Vec { + // A streamed body has no length to announce; the close ends it. + let length = match self.stream { + Some(_) => String::new(), + None => format!("Content-Length: {}\r\n", self.body.len()), + }; let mut head = format!( - "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\ + "HTTP/1.1 {} {}\r\nContent-Type: {}\r\n{}Connection: close\r\n\ Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\ Referrer-Policy: no-referrer\r\n\ Content-Security-Policy: default-src 'none'; style-src 'self'; script-src 'self'; \ @@ -989,7 +1019,7 @@ impl Response { self.status, reason(self.status), self.content_type, - self.body.len() + length ); for h in &self.extra { head.push_str(h); @@ -1002,6 +1032,15 @@ impl Response { } out } + + /// Send the whole response: the head, then the body or its stream. + pub fn write_to(self, w: &mut dyn Write, head_only: bool) -> std::io::Result<()> { + w.write_all(&self.encode(head_only))?; + if let (Some(stream), false) = (self.stream, head_only) { + stream(w)?; + } + w.flush() + } } /// Parsed query string. Values are percent-decoded; repeated keys keep the @@ -1025,6 +1064,13 @@ impl Query { self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) } + /// Every value of a repeated key, in order. The part lists use repeated + /// `part=` rather than one separated value because a part name may hold + /// any character a directory name can — a separator included. + pub fn get_all(&self, key: &str) -> Vec { + self.0.iter().filter(|(k, _)| k == key).map(|(_, v)| v.clone()).collect() + } + fn get_usize(&self, key: &str) -> Option { self.get(key)?.parse().ok() } @@ -1136,8 +1182,36 @@ fn strip_base<'a>(base: &str, path: &'a str) -> Base<'a> { } } -/// Route one parsed request. Split out from the connection loop so the whole -/// surface is testable without a socket. +/// What the server keeps of a request's head. +pub struct Head { + pub method: String, + pub target: String, + pub auth: Option, + pub content_type: Option, + pub content_length: Option, + /// A `Transfer-Encoding` was sent. Nothing here reads a chunked body, and + /// guessing at one would read the next request as data. + pub chunked: bool, +} + +impl Head { + pub fn new(method: &str, target: &str, auth: Option<&str>) -> Head { + Head { + method: method.to_string(), + target: target.to_string(), + auth: auth.map(str::to_string), + content_type: None, + content_length: None, + chunked: false, + } + } +} + +/// The only route that takes a body. +const IMPORT_ROUTE: &str = "/api/import"; + +/// Route one bodiless request. Kept for the read routes, which are most of +/// the surface and most of the tests. pub fn dispatch( cfg: &Config, stats: StatsFn, @@ -1145,13 +1219,25 @@ pub fn dispatch( target: &str, auth: Option<&str>, ) -> Response { + dispatch_request(cfg, stats, &Head::new(method, target, auth), &mut std::io::empty()) +} + +/// Route one parsed request. Split out from the connection loop so the whole +/// surface is testable without a socket. +pub fn dispatch_request(cfg: &Config, stats: StatsFn, head: &Head, body: &mut dyn Read) -> Response { + let method = head.method.as_str(); + let target = head.target.as_str(); + let auth = head.auth.as_deref(); let (raw_path, raw_query) = match target.split_once('?') { Some((p, q)) => (p, q), None => (target, ""), }; let query = Query::parse(raw_query); - if !matches!(method, "GET" | "HEAD") { + // POST exists for one route; everything else stays GET and HEAD, so a + // verb aimed at a read route is still refused before anything runs. + let posting = method == "POST"; + if !matches!(method, "GET" | "HEAD" | "POST") { return text_response(405, "method not allowed\n").with_header("Allow: GET, HEAD".into()); } @@ -1169,6 +1255,9 @@ pub fn dispatch( // safe here despite being config-derived: every response carries // `Cache-Control: no-store`, so a base-path change is not stuck in // somebody's browser. + Base::Bare if posting => { + return text_response(405, "method not allowed\n").with_header("Allow: GET, HEAD".into()); + } Base::Bare => { let loc = if raw_query.is_empty() { format!("{}/", cfg.base_path) @@ -1182,12 +1271,30 @@ pub fn dispatch( } }; + if posting != (path == IMPORT_ROUTE) { + let allow = if path == IMPORT_ROUTE { "Allow: POST" } else { "Allow: GET, HEAD" }; + return text_response(405, "method not allowed\n").with_header(allow.into()); + } + // Liveness is exempt: a probe must not need the secret, and it reveals only // that the process is up. if path == "/healthz" { return text_response(200, "ok\n"); } + // So is the page itself: its HTML, stylesheet and script are the same + // bytes in every deployment and hold no site data. Serving them without the + // secret is what lets the page ask for it when the URL does not carry it, + // and what lets a page opened with `?token=` load its assets at all (a + // browser resolves `app.css` against the page's path, not its query). + // Everything the page shows comes from `/api/*`, which stays behind it. + match path { + "/" | "/index.html" => return asset("text/html; charset=utf-8", INDEX_HTML), + "/app.css" => return asset("text/css; charset=utf-8", APP_CSS), + "/app.js" => return asset("text/javascript; charset=utf-8", APP_JS), + _ => {} + } + if let Some(want) = &cfg.token { let ok = presented_token(auth, &query).is_some_and(|got| secret_eq(&got, want)); if !ok { @@ -1197,25 +1304,142 @@ pub fn dispatch( } match path { - "/" | "/index.html" => asset("text/html; charset=utf-8", INDEX_HTML), - "/app.css" => asset("text/css; charset=utf-8", APP_CSS), - "/app.js" => asset("text/javascript; charset=utf-8", APP_JS), - "/api/stats" => Response { - status: 200, - content_type: "application/json; charset=utf-8", - body: stats(&cfg.shm_path, &cfg.data_dir).into_bytes(), - extra: Vec::new(), - }, + "/api/stats" => response( + 200, + "application/json; charset=utf-8", + stats(&cfg.shm_path, &cfg.data_dir).into_bytes(), + ), "/api/summary" => route_summary(&View::open(cfg)), "/api/roots" => unwrap_route(route_roots(&View::open(cfg))), "/api/node" => unwrap_route(route_node(&View::open(cfg), &query)), "/api/doc" => unwrap_route(route_doc(&View::open(cfg), &query)), "/api/list" => unwrap_route(route_list(&View::open(cfg), &query)), "/api/sizes" => unwrap_route(route_sizes(&View::open(cfg), &query)), + "/api/parts" => { + let view = View::open(cfg); + json_response(200, &transfer::parts_json(&cfg.transfer, view.seg.as_ref())) + } + "/api/export" => route_export(cfg, &query), + IMPORT_ROUTE => route_import(cfg, &query, head, body), _ => json_response(404, &json!({ "error": "not found", "path": path })), } } +/// The selected parts as a `.tar.gz`, streamed as it is made. +/// +/// A GET with the parts in the query, so a browser can be pointed at it and +/// write the download straight to disk: an export can be far larger than a +/// page should hold in memory. Everything that can be wrong with the request +/// is found before the head goes out, so a HEAD (which the page sends first) +/// answers for the GET. +fn route_export(cfg: &Config, q: &Query) -> Response { + let plan = match transfer::plan_export(&cfg.transfer, &q.get_all("part")) { + Ok(p) => p, + Err((status, detail)) => { + return json_response(status, &json!({ "error": "cannot export", "detail": detail })) + } + }; + let name = transfer::export_filename(transfer::unix_now()); + streamed("application/gzip", Box::new(move |w| transfer::write_export(&plan, w))) + .with_header(format!("Content-Disposition: attachment; filename=\"{name}\"")) +} + +/// Media types an archive upload may be labelled with. +/// +/// Also what stops a cross-site form: a form can only send urlencoded, +/// multipart or text/plain, and a script on another origin that sets one of +/// these types is held to a CORS preflight this server never grants. The +/// token is the real gate; this one costs nothing. +const IMPORT_TYPES: [&str; 4] = [ + "application/gzip", + "application/x-gzip", + "application/x-tar", + "application/octet-stream", +]; + +/// Apply an uploaded archive. The answer is a stream of JSON lines — progress, +/// then one `done` or `error` line — because applying a large archive takes +/// longer than a proxy waits for a silent connection, and because the page +/// has something better to show than a spinner. +fn route_import(cfg: &Config, q: &Query, head: &Head, body: &mut dyn Read) -> Response { + let refuse = |status: u16, detail: String| { + json_response(status, &json!({ "error": "cannot import", "detail": detail })) + }; + let p = &cfg.transfer; + // Checked here as well as where the policy is built: whatever assembled + // this Config, a route that can rewrite `_users` does not run unguarded. + if p.import && cfg.token.is_none() { + return refuse(403, "import requires QUANTA_DB_DASHBOARD_TOKEN".into()); + } + let spec = match transfer::plan_import(p, &q.get_all("part"), &q.get("mode").unwrap_or_default()) { + Ok(s) => s, + Err((status, detail)) => return refuse(status, detail), + }; + if head.chunked { + return refuse(411, "send the archive with a Content-Length; chunked uploads are not accepted".into()); + } + let Some(len) = head.content_length else { + return refuse(411, "Content-Length is required".into()); + }; + if len == 0 { + return refuse(400, "the upload is empty".into()); + } + if len > p.max_bytes { + return refuse( + 413, + format!( + "the archive is {} MiB; this dashboard accepts up to {} MiB \ + (QUANTA_DB_DASHBOARD_IMPORT_MAX_MB)", + len.div_ceil(1 << 20), + p.max_bytes >> 20 + ), + ); + } + let ct = head.content_type.as_deref().unwrap_or(""); + let ct = ct.split(';').next().unwrap_or("").trim().to_ascii_lowercase(); + if !IMPORT_TYPES.contains(&ct.as_str()) { + return refuse(415, format!("send the archive as one of: {}", IMPORT_TYPES.join(", "))); + } + let Some(lock) = transfer::ImportLock::try_take() else { + return refuse(409, "another import is running; wait for it to finish".into()); + }; + let spool = match transfer::spool(body, len, &p.spool_dir) { + Ok(s) => s, + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => { + return refuse(400, format!("the upload did not arrive whole: {e}")) + } + Err(e) => return refuse(500, format!("could not store the upload: {e}")), + }; + + // Owned copies: the stream outlives this call's borrows. + let policy = p.clone(); + streamed( + "application/x-ndjson; charset=utf-8", + Box::new(move |w| { + let _lock = lock; + let _ = ndjson(w, &json!({ "phase": "received", "bytes": spool.len() })); + // A client that goes away mid-import does not stop it: an import + // abandoned halfway is worse than one finished unobserved. + let result = transfer::run_import(&policy, &spec, &spool, &mut |v| { + let _ = ndjson(w, &v); + }); + match result { + Ok(v) => ndjson(w, &json!({ "phase": "done", "result": v })), + Err(v) => ndjson(w, &json!({ "phase": "error", "result": v })), + } + }), + ) + // Tells an nginx ingress not to hold the progress lines back. + .with_header("X-Accel-Buffering: no".into()) +} + +fn ndjson(w: &mut dyn Write, v: &Value) -> std::io::Result<()> { + let mut line = serde_json::to_vec(v).unwrap_or_default(); + line.push(b'\n'); + w.write_all(&line)?; + w.flush() +} + fn unwrap_route(r: Result) -> Response { match r { Ok(v) => v, @@ -1223,37 +1447,42 @@ fn unwrap_route(r: Result) -> Response { } } -/// Read the request line and the one header we care about, discarding the rest. +/// Read the request line and the headers we care about, leaving the reader at +/// the first byte of the body. /// /// Returns `None` when the client sent nothing usable — a port scan, a TLS -/// ClientHello, a dropped connection — none of which deserves a reply. -fn read_request(stream: &TcpStream) -> Option<(String, String, Option)> { - let mut r = BufReader::new(stream); +/// ClientHello, a dropped connection, a header section that never ends — +/// none of which deserves a reply. +fn read_head(r: &mut R) -> Option { let mut line = String::new(); - let mut take = (&mut r).take(MAX_LINE as u64); - take.read_line(&mut line).ok()?; + (&mut *r).take(MAX_LINE as u64).read_line(&mut line).ok()?; let mut parts = line.split_whitespace(); - let method = parts.next()?.to_string(); - let target = parts.next()?.to_string(); + let mut head = Head::new(parts.next()?, parts.next()?, None); - let mut auth = None; for _ in 0..MAX_HEADERS { let mut h = String::new(); - let mut take = (&mut r).take(MAX_LINE as u64); - if take.read_line(&mut h).ok()? == 0 { - break; + if (&mut *r).take(MAX_LINE as u64).read_line(&mut h).ok()? == 0 { + return None; } let t = h.trim_end(); if t.is_empty() { - break; + return Some(head); } if let Some((k, v)) = t.split_once(':') { + let v = v.trim(); if k.eq_ignore_ascii_case("authorization") { - auth = Some(v.trim().to_string()); + head.auth = Some(v.to_string()); + } else if k.eq_ignore_ascii_case("content-type") { + head.content_type = Some(v.to_string()); + } else if k.eq_ignore_ascii_case("content-length") { + head.content_length = Some(v.parse().ok()?); + } else if k.eq_ignore_ascii_case("transfer-encoding") { + head.chunked = true; } } } - Some((method, target, auth)) + // Past MAX_HEADERS the rest would be read as the body. + None } /// Serve until killed. @@ -1276,6 +1505,21 @@ pub fn serve(cfg: Config, stats: StatsFn) -> Result<(), String> { content); set QUANTA_DB_DASHBOARD_TOKEN to require a shared secret" ); } + let t = &cfg.transfer; + match (&t.root, t.import) { + (None, _) => eprintln!("qdbstat: export and import are unavailable: no data root"), + (Some(root), true) => eprintln!( + "qdbstat: import is ON: an upload may rewrite {} (up to {} MiB); what it displaces \ + goes to {}", + root.display(), + t.max_bytes >> 20, + t.trash.as_deref().unwrap_or(Path::new("?")).display() + ), + (Some(_), false) => eprintln!( + "qdbstat: import is off. {}", + t.import_off.as_deref().unwrap_or("") + ), + } let cfg = Arc::new(cfg); let inflight = Arc::new(AtomicUsize::new(0)); @@ -1305,10 +1549,14 @@ pub fn serve(cfg: Config, stats: StatsFn) -> Result<(), String> { let spawned = std::thread::Builder::new() .name("qdb-dash".into()) .spawn(move || { - if let Some((method, target, auth)) = read_request(&stream) { - let resp = dispatch(&cfg, stats, &method, &target, auth.as_deref()); - let _ = stream.write_all(&resp.encode(method == "HEAD")); - let _ = stream.flush(); + let mut reader = BufReader::new(&stream); + if let Some(head) = read_head(&mut reader) { + let head_only = head.method == "HEAD"; + let resp = dispatch_request(&cfg, stats, &head, &mut reader); + // Buffered because an export is written as tar headers + // and gzip blocks, and each would otherwise be a syscall. + let mut w = std::io::BufWriter::with_capacity(64 << 10, &stream); + let _ = resp.write_to(&mut w, head_only); } inflight2.fetch_sub(1, Ordering::Relaxed); }); @@ -1482,6 +1730,7 @@ mod tests { data_dir: dir.clone(), token: token.map(str::to_string), base_path: String::new(), + transfer: transfer::Policy::none(), }, dir, } @@ -1721,6 +1970,7 @@ mod tests { data_dir: dir.clone(), token: None, base_path: String::new(), + transfer: transfer::Policy::none(), }, dir, } @@ -1792,6 +2042,7 @@ mod tests { data_dir: dir.clone(), token: None, base_path: String::new(), + transfer: transfer::Policy::none(), }, dir, }; @@ -1807,10 +2058,11 @@ mod tests { } #[test] - fn the_token_gates_every_route_but_liveness() { + fn the_token_gates_every_api_route() { let f = fixture("token", Some("s3cret")); - assert_eq!(dispatch(&f.cfg, stub_stats, "GET", "/api/roots", None).status, 401); - assert_eq!(dispatch(&f.cfg, stub_stats, "GET", "/", None).status, 401); + for route in ["/api/roots", "/api/summary", "/api/stats", "/api/parts", "/api/export?part=db"] { + assert_eq!(dispatch(&f.cfg, stub_stats, "GET", route, None).status, 401, "{route}"); + } // A probe must not need the secret. assert_eq!(dispatch(&f.cfg, stub_stats, "GET", "/healthz", None).status, 200); @@ -1829,6 +2081,28 @@ mod tests { ); } + #[test] + fn the_page_loads_without_the_token_so_it_can_ask_for_it() { + let f = fixture("tokenpage", Some("s3cret")); + for (path, needle) in [("/", "app.js"), ("/index.html", "app.js"), ("/app.css", "--accent"), ("/app.js", "api/")] { + let r = dispatch(&f.cfg, stub_stats, "GET", path, None); + assert_eq!(r.status, 200, "{path}"); + assert!(String::from_utf8(r.body).unwrap().contains(needle), "{path}"); + } + // The page is the same bytes with or without the secret: it carries no + // site data, so serving it reveals nothing the source does not. + let with = dispatch(&f.cfg, stub_stats, "GET", "/?token=s3cret", None).body; + assert_eq!(with, dispatch(&f.cfg, stub_stats, "GET", "/", None).body); + // Served to anyone who reaches the port, so it must not tell them how + // the server is configured: no setting is named in it. + for asset in [INDEX_HTML, APP_CSS, APP_JS] { + assert!(!asset.contains("QUANTA_"), "a public page file names a setting"); + } + // Nothing else rides on that exemption. + assert_eq!(dispatch(&f.cfg, stub_stats, "GET", "/app.js/../api/roots", None).status, 401); + assert_eq!(dispatch(&f.cfg, stub_stats, "GET", "/favicon.ico", None).status, 401); + } + #[test] fn without_a_token_nothing_is_gated() { let f = fixture("open", None); @@ -2008,6 +2282,7 @@ mod tests { data_dir: dir.clone(), token: None, base_path: String::new(), + transfer: transfer::Policy::none(), }, dir, }; @@ -2104,6 +2379,7 @@ mod tests { data_dir: dir.clone(), token: None, base_path: String::new(), + transfer: transfer::Policy::none(), }, dir, }; @@ -2243,4 +2519,168 @@ mod tests { assert!(head.contains("default-src 'none'")); assert!(head.contains("Cache-Control: no-store")); } + + // -- export / import routes --------------------------------------------- + + /// A Fixture whose transfer policy points at a real directory tree. + fn transfer_fixture(tag: &str, token: Option<&str>, import: bool) -> (Fixture, PathBuf) { + let mut f = fixture(tag, token); + let root = f.dir.join("site"); + let users = root.join("db/_users/alice"); + std::fs::create_dir_all(&users).unwrap(); + std::fs::write(users.join("data.json"), br#"{"name":"alice"}"#).unwrap(); + std::fs::create_dir_all(root.join("db/pages/home")).unwrap(); + std::fs::write(root.join("db/pages/home/data.json"), br#"{"title":"Home"}"#).unwrap(); + let root = root.canonicalize().unwrap(); + f.cfg.transfer = transfer::Policy { + root: Some(root.clone()), + link_root: Some(root.clone()), + import, + import_off: (!import).then(|| "off in this test".to_string()), + max_bytes: 16 << 20, + trash: Some(f.dir.join("trash")), + spool_dir: f.dir.clone(), + }; + (f, root) + } + + fn run_stream(r: Response) -> Vec { + let mut out = Vec::new(); + r.write_to(&mut out, false).unwrap(); + let split = out.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4; + out.split_off(split) + } + + fn post(f: &Fixture, target: &str, ct: Option<&str>, body: &[u8]) -> Response { + let mut head = Head::new("POST", target, None); + head.content_type = ct.map(str::to_string); + head.content_length = Some(body.len() as u64); + dispatch_request(&f.cfg, stub_stats, &head, &mut &body[..]) + } + + #[test] + fn import_is_the_only_route_that_takes_a_post() { + let (f, _) = transfer_fixture("posts", Some("t"), true); + let r = post(&f, "/api/node?name=home&token=t", Some("application/gzip"), b"x"); + assert_eq!(r.status, 405, "a read route stays read-only"); + let r = dispatch(&f.cfg, stub_stats, "GET", "/api/import?part=db&token=t", None); + assert_eq!(r.status, 405); + assert!(r.extra.iter().any(|h| h == "Allow: POST")); + let r = post(&f, "/api/import?part=db", Some("application/gzip"), b"x"); + assert_eq!(r.status, 401, "the token gates the write route like every other"); + } + + #[test] + fn import_stays_off_without_the_policy_or_the_token() { + let (f, _) = transfer_fixture("importoff", None, false); + let r = post(&f, "/api/import?part=db", Some("application/gzip"), b"x"); + assert_eq!(r.status, 403); + let v: Value = serde_json::from_slice(&r.body).unwrap(); + assert_eq!(v["detail"], "Import is off. off in this test"); + + // A policy that says yes is still refused without a secret to check. + let (f, _) = transfer_fixture("notoken", None, true); + let r = post(&f, "/api/import?part=db", Some("application/gzip"), b"x"); + assert_eq!(r.status, 403); + } + + #[test] + fn an_upload_must_say_what_it_is_and_how_long() { + let (f, _) = transfer_fixture("uploadshape", Some("t"), true); + let r = post(&f, "/api/import?part=db&token=t", Some("multipart/form-data; boundary=x"), b"x"); + assert_eq!(r.status, 415, "a cross-site form cannot label its body as an archive"); + let mut head = Head::new("POST", "/api/import?part=db&token=t", None); + head.content_type = Some("application/gzip".into()); + let r = dispatch_request(&f.cfg, stub_stats, &head, &mut &b"x"[..]); + assert_eq!(r.status, 411); + head.content_length = Some(1 << 30); + let r = dispatch_request(&f.cfg, stub_stats, &head, &mut &b"x"[..]); + assert_eq!(r.status, 413); + let r = post(&f, "/api/import?part=../etc&token=t", Some("application/gzip"), b"x"); + assert_eq!(r.status, 400); + } + + #[test] + fn the_parts_listing_names_what_the_root_holds() { + let (f, _) = transfer_fixture("partslist", None, false); + let (status, v) = get(&f, "/api/parts"); + assert_eq!(status, 200); + assert_eq!(v["available"], true); + assert_eq!(v["indexed"], true, "the fixture's segment weighs the parts"); + assert_eq!(v["groups"][0]["name"], "db"); + assert_eq!(v["import"]["enabled"], false); + assert_eq!(v["import"]["reason"], "off in this test"); + + let f = fixture("partsnone", None); + let (_, v) = get(&f, "/api/parts"); + assert_eq!(v["available"], false, "no root, nothing to offer"); + } + + #[test] + fn an_export_streams_and_a_head_answers_for_it() { + let (f, _) = transfer_fixture("exportroute", None, false); + let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=nope", None); + assert_eq!(r.status, 404, "a missing part is found before the download starts"); + let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=db/../x", None); + assert_eq!(r.status, 400); + + let r = dispatch(&f.cfg, stub_stats, "HEAD", "/api/export?part=db/_users", None); + assert_eq!(r.status, 200); + let head = String::from_utf8(r.encode(true)).unwrap(); + assert!(head.contains("Content-Type: application/gzip")); + assert!(head.contains("attachment; filename=\"qdb-export-")); + assert!(!head.contains("Content-Length"), "a streamed body has no length to promise"); + + let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=db/_users&part=db/pages", None); + let gz = run_stream(r); + let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(&gz[..])); + let names: Vec = ar + .entries() + .unwrap() + .map(|e| e.unwrap().path().unwrap().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names[0], transfer::MANIFEST); + assert!(names.contains(&"db/_users/alice/data.json".to_string())); + assert!(names.contains(&"db/pages/home/data.json".to_string())); + } + + #[test] + fn an_import_streams_its_progress_and_ends_with_the_result() { + let (f, root) = transfer_fixture("importroute", Some("t"), true); + let gz = run_stream(dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=db/_users&token=t", None)); + std::fs::write(root.join("db/_users/alice/data.json"), b"{}").unwrap(); + + let r = post(&f, "/api/import?part=db/_users&mode=merge&token=t", Some("application/gzip"), &gz); + assert_eq!(r.status, 200); + assert!(r.extra.iter().any(|h| h == "X-Accel-Buffering: no")); + let body = String::from_utf8(run_stream(r)).unwrap(); + let lines: Vec = body.lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(lines[0]["phase"], "received"); + let last = lines.last().unwrap(); + assert_eq!(last["phase"], "done", "{body}"); + assert_eq!(last["result"]["written"], 1); + assert_eq!( + std::fs::read_to_string(root.join("db/_users/alice/data.json")).unwrap(), + r#"{"name":"alice"}"# + ); + assert!(transfer::ImportLock::try_take().is_some(), "the lock is released with the stream"); + } + + #[test] + fn the_request_head_keeps_what_a_body_needs() { + let raw = b"POST /api/import?part=db HTTP/1.1\r\nHost: x\r\nContent-Type: application/gzip\r\n\ + Content-Length: 4\r\nAuthorization: Bearer t\r\n\r\nBODY"; + let mut r = BufReader::new(&raw[..]); + let h = read_head(&mut r).unwrap(); + assert_eq!(h.method, "POST"); + assert_eq!(h.content_length, Some(4)); + assert_eq!(h.content_type.as_deref(), Some("application/gzip")); + assert_eq!(h.auth.as_deref(), Some("Bearer t")); + let mut rest = String::new(); + r.read_to_string(&mut rest).unwrap(); + assert_eq!(rest, "BODY", "the reader is left at the first byte of the body"); + + let bad = b"POST / HTTP/1.1\r\nContent-Length: lots\r\n\r\n"; + assert!(read_head(&mut BufReader::new(&bad[..])).is_none()); + } } diff --git a/qdb/src/dashboard/app.css b/qdb/src/dashboard/app.css index afca438c1..11969390e 100644 --- a/qdb/src/dashboard/app.css +++ b/qdb/src/dashboard/app.css @@ -385,3 +385,363 @@ pre.json { } #tip .tip-name { font-family: var(--mono); font-weight: 600; display: block; } #tip .tip-row { color: var(--dim); font-variant-numeric: tabular-nums; } + +/* ---------------------------------------------------------- export/import */ + +/* Text that sits ON the accent / danger fills. White on the light-mode blue + and red; near-black on the dark-mode ones, which are light enough that + white text on them falls under 3:1. */ +:root { --on-accent: #ffffff; --on-bad: #ffffff; } +@media (prefers-color-scheme: dark) { + :root { --on-accent: #08111f; --on-bad: #1a0404; } +} + +#transfer-view .xfer { + width: 100%; + padding: 18px 20px 28px; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 18px; + align-content: start; + align-items: start; +} +@media (max-width: 1100px) { + #transfer-view .xfer { grid-template-columns: minmax(0, 1fr); } +} + +.card { + border: 1px solid var(--line); + border-radius: 12px; + background: var(--bg); + display: flex; + flex-direction: column; + min-width: 0; + box-shadow: 0 1px 2px rgba(0, 0, 0, .05), 0 6px 20px -12px rgba(0, 0, 0, .18); +} +.card-head { display: flex; gap: 12px; align-items: flex-start; padding: 16px 18px 14px; } +.card-icon { + flex: 0 0 36px; + height: 36px; + border-radius: 10px; + display: grid; + place-items: center; + color: var(--accent); + background: color-mix(in srgb, var(--accent) 13%, transparent); +} +.card-icon svg { width: 19px; height: 19px; } +.card-head h3 { margin: 1px 0 0; font-size: 15px; font-weight: 650; } +.card-head .sub { margin: 2px 0 0; color: var(--dim); max-width: 52ch; } +.card-body { padding: 0 18px 16px; display: flex; flex-direction: column; gap: 12px; min-width: 0; } +.card-foot { + margin-top: auto; + padding: 12px 18px; + border-top: 1px solid var(--line); + background: var(--panel); + border-radius: 0 0 12px 12px; + display: flex; + align-items: center; + gap: 10px 14px; + flex-wrap: wrap; + min-height: 58px; +} +.card-foot .summary { color: var(--dim); font-variant-numeric: tabular-nums; min-width: 0; } +.card-foot .summary b { color: var(--fg); font-weight: 600; } +.card-foot .fname { display: block; font-family: var(--mono); font-size: 11px; color: var(--dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.card-foot .spacer { flex: 1 1 auto; } +.card-foot .confirm { font-weight: 600; min-width: 0; } +.card-foot .confirm small { display: block; font-weight: 400; color: var(--dim); } + +/* State chip in a card's head: is this side usable right now. */ +.state { + margin-left: auto; + flex: 0 0 auto; + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 11px; + font-weight: 600; + letter-spacing: .04em; + text-transform: uppercase; + padding: 3px 10px; + border-radius: 999px; + border: 1px solid var(--line); + color: var(--dim); + white-space: nowrap; +} +.state::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; } +.state.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 40%, transparent); } + +.btn { + font: inherit; + font-weight: 600; + line-height: 1.2; + border-radius: 8px; + padding: 8px 14px; + border: 1px solid var(--line); + background: var(--bg); + color: var(--fg); + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 7px; + white-space: nowrap; + transition: background-color .12s, border-color .12s, opacity .12s, filter .12s; +} +.btn svg { width: 15px; height: 15px; flex: 0 0 auto; } +.btn:hover:not(:disabled) { border-color: var(--accent); } +.btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.btn:disabled { opacity: .45; cursor: not-allowed; } +.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); } +.btn.danger { background: var(--bad); border-color: var(--bad); color: var(--on-bad); } +.btn.primary:hover:not(:disabled), .btn.danger:hover:not(:disabled) { filter: brightness(1.08); } +.btn.ghost { background: transparent; border-color: transparent; color: var(--dim); padding: 6px 8px; } +.btn.ghost:hover:not(:disabled) { color: var(--fg); border-color: var(--line); } +.btn.busy svg { animation: spin 1s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } + +/* The parts tree: a select-all bar, then groups and their members. Columns + come from a per-tree custom property, set through the CSSOM by app.js. */ +.ptree { border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: var(--bg); } +.ptree-bar { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + background: var(--panel); + border-bottom: 1px solid var(--line); +} +.ptree-bar label { display: inline-flex; align-items: center; gap: 9px; font-weight: 600; cursor: pointer; user-select: none; } +.ptree-bar .count { color: var(--dim); font-variant-numeric: tabular-nums; font-weight: 400; } +.ptree-bar input[type=search] { + margin-left: auto; + width: 170px; + min-width: 0; + padding: 4px 9px; + border: 1px solid var(--line); + border-radius: 6px; + background: var(--bg); + color: var(--fg); + font: inherit; + font-size: 12px; +} +.ptree-head, .prow { + display: grid; + grid-template-columns: var(--pt-cols, 18px 20px minmax(0, 1fr) 86px 86px); + align-items: center; + column-gap: 8px; +} +.ptree-head { + padding: 5px 12px; + color: var(--dim); + font-size: 10.5px; + font-weight: 600; + letter-spacing: .06em; + text-transform: uppercase; + border-bottom: 1px solid var(--line); +} +.ptree-head .r { text-align: right; } +.ptree-list { max-height: 440px; overflow: auto; } +.prow { padding: 6px 12px; border-bottom: 1px solid var(--line); cursor: pointer; } +.ptree-list > :last-child, .ptree-list > :last-child .prow:last-child { border-bottom: 0; } +.prow:hover { background: var(--panel); } +.prow.member .pname { padding-left: 18px; } +.prow.dim { opacity: .55; } +.prow input[type=checkbox], .ptree-bar input[type=checkbox] { + accent-color: var(--accent); + width: 15px; + height: 15px; + margin: 0; + cursor: pointer; +} +.tw { + width: 18px; + height: 18px; + padding: 0; + border: 0; + border-radius: 4px; + background: none; + color: var(--dim); + cursor: pointer; + display: grid; + place-items: center; + transition: transform .12s; +} +.tw svg { width: 13px; height: 13px; } +.tw:hover { background: var(--line); color: var(--fg); } +.tw.open { transform: rotate(90deg); } +.pname { min-width: 0; display: flex; flex-direction: column; gap: 4px; } +.pname .line { display: flex; align-items: center; gap: 7px; min-width: 0; } +.pname .pn { font-family: var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.prow.group .pname .pn { font-weight: 600; } +.pname .share { height: 3px; border-radius: 2px; background: color-mix(in srgb, var(--line) 70%, transparent); overflow: hidden; max-width: 240px; } +.pname .share i { display: block; height: 100%; background: var(--accent); opacity: .6; border-radius: 2px; } +.pnum { text-align: right; font-variant-numeric: tabular-nums; color: var(--dim); white-space: nowrap; font-size: 12px; } +.prow.group .pnum { color: var(--fg); } +.pmore { padding: 6px 12px 8px 58px; color: var(--dim); font-size: 12px; border-bottom: 1px solid var(--line); } +.ptree-empty { padding: 22px 12px; text-align: center; color: var(--dim); } +.badge.new { background: color-mix(in srgb, var(--accent) 16%, transparent); color: var(--accent); } +.badge.exists { background: transparent; box-shadow: inset 0 0 0 1px var(--line); } + +/* Notes and callouts. */ +.hint { margin: 0; color: var(--dim); font-size: 12px; } +.hint code, .callout code { font-family: var(--mono); font-size: 11.5px; } +.callout { + display: flex; + gap: 10px; + align-items: flex-start; + padding: 10px 12px; + border-radius: 10px; + border: 1px solid var(--line); + background: var(--panel); +} +.callout svg { width: 17px; height: 17px; flex: 0 0 auto; margin-top: 1px; color: var(--dim); } +.callout p { margin: 0; } +.callout p + p { margin-top: 4px; color: var(--dim); } +.callout.warn { border-color: color-mix(in srgb, var(--warn) 45%, transparent); background: color-mix(in srgb, var(--warn) 9%, transparent); } +.callout.warn svg { color: var(--warn); } +.callout.bad { border-color: color-mix(in srgb, var(--bad) 45%, transparent); background: color-mix(in srgb, var(--bad) 8%, transparent); } +.callout.bad svg { color: var(--bad); } +.callout.ok { border-color: color-mix(in srgb, var(--ok) 40%, transparent); background: color-mix(in srgb, var(--ok) 8%, transparent); } +.callout.ok svg { color: var(--ok); } + +/* The drop zone: the whole thing is the target and the button. */ +.drop { + border: 2px dashed var(--line); + border-radius: 12px; + padding: 28px 18px; + text-align: center; + color: var(--dim); + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + cursor: pointer; + transition: border-color .12s, background-color .12s, color .12s; +} +.drop:hover, .drop.over, .drop:focus-visible { + border-color: var(--accent); + background: color-mix(in srgb, var(--accent) 6%, transparent); + outline: none; +} +.drop .drop-icon { + width: 44px; + height: 44px; + border-radius: 50%; + display: grid; + place-items: center; + color: var(--accent); + background: color-mix(in srgb, var(--accent) 12%, transparent); + margin-bottom: 4px; +} +.drop .drop-icon svg { width: 22px; height: 22px; } +.drop strong { color: var(--fg); font-size: 14px; font-weight: 600; } +.drop .link { color: var(--accent); font-weight: 600; } + +.filecard { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 12px; + border: 1px solid var(--line); + border-radius: 10px; + background: var(--panel); + min-width: 0; +} +.filecard .ficon { + flex: 0 0 34px; + height: 34px; + border-radius: 8px; + display: grid; + place-items: center; + background: var(--bg); + border: 1px solid var(--line); + color: var(--dim); +} +.filecard .ficon svg { width: 17px; height: 17px; } +.filecard .fbody { min-width: 0; flex: 1 1 auto; } +.filecard .fname { font-family: var(--mono); font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.filecard .fmeta { color: var(--dim); font-size: 12px; font-variant-numeric: tabular-nums; } + +/* Merge / replace. */ +.modes { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } +@media (max-width: 560px) { .modes { grid-template-columns: 1fr; } } +.mode { + border: 1px solid var(--line); + border-radius: 10px; + padding: 10px 12px; + cursor: pointer; + display: flex; + gap: 10px; + align-items: flex-start; + transition: border-color .12s, background-color .12s, box-shadow .12s; +} +.mode:hover { border-color: color-mix(in srgb, var(--accent) 60%, var(--line)); } +.mode input { margin: 2px 0 0; accent-color: var(--accent); } +.mode b { display: block; font-weight: 600; } +.mode span { color: var(--dim); font-size: 12px; } +.mode.on { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); background: color-mix(in srgb, var(--accent) 6%, transparent); } +.mode.replace.on { border-color: var(--bad); box-shadow: inset 0 0 0 1px var(--bad); background: color-mix(in srgb, var(--bad) 6%, transparent); } +.mode.replace input { accent-color: var(--bad); } + +/* Progress: determinate while a fraction is known, a sweeping bar while not. */ +.progress { display: flex; flex-direction: column; gap: 7px; } +.progress .plabel { display: flex; justify-content: space-between; gap: 12px; font-size: 12px; font-variant-numeric: tabular-nums; } +.progress .plabel span:last-child { color: var(--dim); } +.progress .track { height: 6px; border-radius: 999px; background: var(--line); overflow: hidden; position: relative; } +.progress .fill { height: 100%; width: 0; background: var(--accent); border-radius: 999px; transition: width .25s ease; } +.progress.indet .fill { width: 30%; position: absolute; animation: sweep 1.2s ease-in-out infinite; } +@keyframes sweep { from { left: -30%; } to { left: 100%; } } +@media (prefers-reduced-motion: reduce) { + .progress.indet .fill { animation: none; left: 0; width: 100%; opacity: .5; } + .btn.busy svg { animation: none; } +} + +/* The outcome. */ +.stat-tiles { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; } +@media (max-width: 560px) { .stat-tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +.stat-tile { border: 1px solid var(--line); border-radius: 10px; padding: 9px 11px; background: var(--bg); } +.stat-tile b { display: block; font-size: 19px; font-weight: 650; font-variant-numeric: tabular-nums; line-height: 1.25; } +.stat-tile span { color: var(--dim); font-size: 10.5px; font-weight: 600; text-transform: uppercase; letter-spacing: .06em; } +.stat-tile.hot b { color: var(--warn); } +.pathline { display: flex; align-items: center; gap: 8px; min-width: 0; } +.pathline code { font-family: var(--mono); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +details.skips { border: 1px solid var(--line); border-radius: 10px; overflow: hidden; } +details.skips > summary { padding: 8px 12px; cursor: pointer; background: var(--panel); color: var(--dim); } +details.skips ul { list-style: none; margin: 0; padding: 4px 0; max-height: 220px; overflow: auto; } +details.skips li { padding: 3px 12px; display: flex; gap: 12px; font-size: 12px; } +details.skips li code { font-family: var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 0 1 55%; } +details.skips li span { color: var(--dim); } +.ptree.locked .prow { cursor: default; } +.ptree.locked .prow:hover { background: none; } +.card-body-block { display: flex; flex-direction: column; gap: 10px; } + +/* ---------------------------------------------------------------- sign-in */ + +.signin { + position: fixed; + inset: 0; + z-index: 100; + display: grid; + place-items: center; + padding: 20px; + background: color-mix(in srgb, var(--bg) 72%, transparent); + backdrop-filter: blur(6px); +} +.signin .card { width: min(440px, 100%); box-shadow: 0 20px 60px -20px rgba(0, 0, 0, .45); } +.signin input[type=password] { + font: inherit; + font-family: var(--mono); + padding: 9px 11px; + border: 1px solid var(--line); + border-radius: 8px; + background: var(--panel); + color: var(--fg); + width: 100%; +} +.signin input[type=password]:focus { outline: 2px solid var(--accent); outline-offset: 1px; border-color: var(--accent); } +.signin .check { display: flex; align-items: center; gap: 8px; color: var(--dim); font-size: 12px; cursor: pointer; user-select: none; } +.signin .check input { accent-color: var(--accent); margin: 0; } +.signin .err { margin: 0; min-height: 1.2em; color: var(--bad); font-size: 12px; } +.signin .err:empty { min-height: 0; } +.signin .btn { justify-content: center; } +.signout { margin-left: 4px; } diff --git a/qdb/src/dashboard/app.js b/qdb/src/dashboard/app.js index 38cda1222..6b8c29cdc 100644 --- a/qdb/src/dashboard/app.js +++ b/qdb/src/dashboard/app.js @@ -2,7 +2,8 @@ * * Talks only to this server's /api/* routes. Everything it renders comes from * the shared-memory segment, so what you see here is what a PHP worker would - * be served -- not what is on disk. + * be served -- not what is on disk. (Export / import is the exception: it + * works on the files, see below.) * * No innerHTML is used for anything derived from the index: node names, paths * and document contents are site data, and a browser that pasted them into @@ -10,10 +11,40 @@ */ "use strict"; -// A token supplied in the page URL has to ride along on every fetch -- you -// open this by pasting a link, where setting an Authorization header is not an -// option. Kept out of the DOM so it is not copied into anything rendered. -const TOKEN = new URLSearchParams(location.search).get("token"); +/* The access token, when the server is configured with one. It comes from + the page URL (`?token=`, for a link pasted into a browser) or from the + sign-in card the page shows when the API answers 401, which keeps it for + this tab -- or this browser, if asked -- so a reload does not ask again. + Kept out of the DOM so it is not copied into anything rendered. */ +const tokenStore = { + // Per path: dashboards mounted under different prefixes of one origin are + // different servers with different secrets. + key: "qdb-dashboard-token:" + location.pathname, + get() { + try { return sessionStorage.getItem(this.key) || localStorage.getItem(this.key); } catch { return null; } + }, + set(t, remember) { + this.clear(); + try { (remember ? localStorage : sessionStorage).setItem(this.key, t); } catch { /* storage off: this page only */ } + }, + clear() { + try { sessionStorage.removeItem(this.key); localStorage.removeItem(this.key); } catch { /* nothing kept */ } + }, +}; +const URL_TOKEN = new URLSearchParams(location.search).get("token"); +let TOKEN = URL_TOKEN || tokenStore.get(); +let tokenFrom = URL_TOKEN ? "url" : TOKEN ? "store" : null; + +/* The token goes as an Authorization header wherever the page can set one, so + it stays out of URLs and the access logs they end up in. A header value has + to be printable ASCII; a token that is not goes in the query string, which + the server accepts as well. */ +const headerSafe = (t) => /^[\x21-\x7e]+$/.test(t); +const authHeaders = (t = TOKEN) => (t && headerSafe(t) ? { Authorization: "Bearer " + t } : {}); +function authQuery(u, t = TOKEN) { + if (t && !headerSafe(t)) u.set("token", t); + return u; +} const $ = (sel) => document.querySelector(sel); @@ -24,12 +55,11 @@ const $ = (sel) => document.querySelector(sel); with no build step and nothing to configure in the page. The server's base-path redirect is what guarantees the trailing slash this relies on. */ function api(path, params) { - const u = new URLSearchParams(params || {}); - if (TOKEN) u.set("token", TOKEN); - const qs = u.toString(); - return fetch(path + (qs ? "?" + qs : ""), { headers: { Accept: "application/json" } }) + const qs = authQuery(new URLSearchParams(params || {})).toString(); + return fetch(path + (qs ? "?" + qs : ""), { headers: { Accept: "application/json", ...authHeaders() } }) .then(async (r) => { const body = await r.json().catch(() => ({ error: "unreadable response" })); + if (r.status === 401) signIn.show(); if (!r.ok) throw Object.assign(new Error(body.error || r.statusText), { body, status: r.status }); return body; }); @@ -805,6 +835,1064 @@ function openSize(name) { location.hash = name ? "#/sizes/" + encodeURIComponent(name) : "#/sizes"; } +/* -------------------------------------------------------- export / import */ + +/* This view is the one exception to "everything comes from the segment": an + archive is a backup, so the server builds it from the files under the data + root (payload files and links included) and applies it back to them. The + counts beside each part still come from the segment, when there is one. */ + +/* Icons are stroke paths in a 24-unit box, built through the DOM like the rest + of the page. Presentation attributes, not a style attribute, so the CSP's + style-src has nothing to say about them. */ +const SVG_NS = "http://www.w3.org/2000/svg"; +const ICONS = { + download: ["M12 3v12", "M7 10l5 5 5-5", "M5 21h14"], + upload: ["M12 15V3", "M7 8l5-5 5 5", "M5 21h14"], + archive: ["M4 8h16v12H4z", "M3 4h18v4H3z", "M10 12h4"], + lock: ["M6 11h12v10H6z", "M8 11V7a4 4 0 0 1 8 0v4"], + check: ["M20 6L9 17l-5-5"], + alert: ["M12 9v4", "M12 17h.01", "M10.3 3.9L1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"], + x: ["M18 6L6 18", "M6 6l12 12"], + chev: ["M9 6l6 6-6 6"], + logout: ["M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4", "M16 17l5-5-5-5", "M21 12H9"], + copy: ["M9 9h11v11H9z", "M5 15H4V4h11v1"], + spin: ["M12 3a9 9 0 1 0 9 9"], +}; + +function icon(name) { + const s = document.createElementNS(SVG_NS, "svg"); + for (const [k, v] of Object.entries({ + viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", + "stroke-linecap": "round", "stroke-linejoin": "round", "aria-hidden": "true", + })) s.setAttribute(k, v); + for (const d of ICONS[name]) { + const p = document.createElementNS(SVG_NS, "path"); + p.setAttribute("d", d); + s.append(p); + } + return s; +} + +/* An API URL with repeated keys -- the part lists repeat `part=`, because a + part name can hold any character a directory name can, separators included. */ +function apiUrl(path, pairs) { + const u = new URLSearchParams(); + for (const [k, v] of pairs || []) u.append(k, v); + const qs = authQuery(u).toString(); + return path + (qs ? "?" + qs : ""); +} + +/* The one request the page cannot attach a header to: a download, which is a + plain link so the browser can write the stream to disk itself. Its URL + carries the token, and so does the browser's list of downloads. */ +function downloadUrl(path, pairs) { + const u = new URLSearchParams(); + for (const [k, v] of pairs || []) u.append(k, v); + if (TOKEN) u.set("token", TOKEN); + return path + "?" + u.toString(); +} + +const plural = (n, one, many) => `${count(n)} ${n === 1 ? one : many || one + "s"}`; +const secs = (ms) => (ms < 10000 ? (ms / 1000).toFixed(1) : Math.round(ms / 1000)) + " s"; + +function callout(kind, ic, title, ...text) { + return el("div", { class: "callout " + kind }, icon(ic), + el("div", {}, el("p", {}, el("b", {}, title)), text.length ? el("p", {}, ...text) : null)); +} + +function progressBar() { + const fill = el("div", { class: "fill" }); + const left = el("span"); + const right = el("span"); + const node = el("div", { class: "progress", role: "progressbar" }, + el("div", { class: "plabel" }, left, right), el("div", { class: "track" }, fill)); + return { + el: node, + /* frac null = not known: the bar sweeps instead of lying about a fraction. */ + set(frac, label, note) { + left.textContent = label; + right.textContent = note || ""; + const known = frac !== null && frac !== undefined; + node.classList.toggle("indet", !known); + fill.style.width = known ? (Math.max(0, Math.min(1, frac)) * 100).toFixed(1) + "%" : ""; + if (known) node.setAttribute("aria-valuenow", String(Math.round(frac * 100))); + else node.removeAttribute("aria-valuenow"); + }, + }; +} + +/* ------------------------------------------------------------ parts tree */ + +/* The picker both cards use: groups (the root's directories), their members, + a three-state checkbox per group and one select-all over the lot. + + A group is selected WHOLE or member by member, and the difference is what + gets sent: whole means the group's own path, which also carries the files + directly inside it and any members past the listing's cap; member by member + means exactly those. Ticking a group, or select-all, selects it whole; + unticking any one of its members breaks that. */ +function partsTree(groups, opt) { + const whole = new Set(); + const picked = new Set(); + const open = new Set(); + const checks = []; + let filter = ""; + let locked = false; + const key = (g, m) => g.name + "/" + m.name; + const hasMembers = (g) => g.members.length > 0; + const weight = (r) => (opt.weight ? opt.weight(r) || 0 : 0); + const maxGroup = Math.max(0, ...groups.map(weight)); + + function selectGroup(g, on) { + for (const m of g.members) { + if (on) picked.add(key(g, m)); else picked.delete(key(g, m)); + } + if (on) whole.add(g.name); else whole.delete(g.name); + } + + const sendsWhole = (g) => whole.has(g.name) && (!opt.wholeOk || opt.wholeOk(g)); + + function groupState(g) { + if (whole.has(g.name)) return "all"; + return g.members.some((m) => picked.has(key(g, m))) ? "some" : "none"; + } + + const init = opt.initial; + for (const g of groups) { + if (init === "all" || (init instanceof Set && init.has(g.name))) selectGroup(g, true); + else if (init instanceof Set) for (const m of g.members) if (init.has(key(g, m))) picked.add(key(g, m)); + // A short list reads best open; a long one would bury everything below it. + if (hasMembers(g) && g.members.length <= 40 && groups.length <= 8) open.add(g.name); + } + + const api = { + selected() { + const out = []; + for (const g of groups) { + if (sendsWhole(g)) out.push(g.name); + else for (const m of g.members) if (picked.has(key(g, m))) out.push(key(g, m)); + } + return out; + }, + totals() { + const t = { parts: 0 }; + const add = (r) => { + t.parts++; + for (const [k, v] of Object.entries(opt.sum(r))) t[k] = (t[k] || 0) + (v || 0); + }; + for (const g of groups) { + if (sendsWhole(g)) add(g); + else for (const m of g.members) if (picked.has(key(g, m))) add(m); + } + return t; + }, + /* While an import runs or has run, the selection is history. */ + lock(on) { + locked = on; + node.classList.toggle("locked", on); + sync(false); + }, + }; + + const all = el("input", { type: "checkbox", "aria-label": "Select all parts" }); + all.addEventListener("change", () => { + const every = groups.every((g) => groupState(g) === "all"); + for (const g of groups) selectGroup(g, !every); + sync(); + }); + const countEl = el("span", { class: "count" }); + const rows = groups.reduce((n, g) => n + 1 + g.members.length, 0); + const search = rows > 14 ? el("input", { type: "search", placeholder: "Filter parts", "aria-label": "Filter parts" }) : null; + if (search) { + search.addEventListener("input", () => { filter = search.value.trim().toLowerCase(); build(); }); + } + const list = el("div", { class: "ptree-list" }); + const node = el("div", { class: "ptree" }, + el("div", { class: "ptree-bar" }, el("label", {}, all, "Select all", countEl), search), + el("div", { class: "ptree-head", "aria-hidden": "true" }, + el("span"), el("span"), el("span", {}, "part"), + ...opt.cols.map((c) => el("span", { class: "r" }, c.label))), + list); + node.style.setProperty("--pt-cols", `18px 20px minmax(0, 1fr) ${opt.cols.map((c) => c.width || "86px").join(" ")}`); + + function nameCell(g, m) { + const r = m || g; + const max = m ? weight(g) : maxGroup; + const share = el("i"); + const w = weight(r); + share.style.width = (max > 0 ? Math.max(w > 0 ? 1.5 : 0, (w / max) * 100) : 0).toFixed(1) + "%"; + return el("div", { class: "pname" }, + el("div", { class: "line" }, + el("span", { class: "pn", title: m ? key(g, m) : g.name }, r.name), + !m && g.link && el("span", { class: "badge link", title: "a symlink on the server, exported as the directory it points to" }, "link"), + opt.badge && opt.badge(g, m)), + opt.weight && el("div", { class: "share" }, share)); + } + + const nums = (r) => opt.cols.map((c) => el("span", { class: "pnum" }, c.value(r))); + + /* Clicking anywhere on a row toggles it; the checkbox itself and the + expander are left to do their own thing. */ + const rowClick = (cb) => (e) => { + if (locked || e.target === cb || e.target.closest(".tw")) return; + cb.click(); + }; + + function groupRow(g) { + const cb = el("input", { type: "checkbox", "aria-label": "Select " + g.name }); + cb.addEventListener("change", () => { selectGroup(g, groupState(g) !== "all"); sync(); }); + checks.push([cb, () => groupState(g)]); + const isOpen = open.has(g.name) || (filter && !g.name.toLowerCase().includes(filter)); + const tw = hasMembers(g) + ? el("button", { + class: "tw" + (isOpen ? " open" : ""), type: "button", + "aria-expanded": String(!!isOpen), "aria-label": (isOpen ? "Collapse " : "Expand ") + g.name, + onclick: () => { if (open.has(g.name)) open.delete(g.name); else open.add(g.name); build(); }, + }, icon("chev")) + : el("span"); + return el("div", { class: "prow group" }, tw, cb, nameCell(g, null), ...nums(g)); + } + + function memberRow(g, m) { + const k = key(g, m); + const cb = el("input", { type: "checkbox", "aria-label": "Select " + k }); + cb.addEventListener("change", () => { + if (picked.has(k)) { + picked.delete(k); + whole.delete(g.name); + } else { + picked.add(k); + // Every member ticked by hand is the whole group -- unless the + // listing was capped, when "every member" is only every one shown. + if (!g.more && g.members.every((x) => picked.has(key(g, x)))) whole.add(g.name); + } + sync(); + }); + checks.push([cb, () => (picked.has(k) ? "all" : "none")]); + return el("div", { class: "prow member" }, el("span"), cb, nameCell(g, m), ...nums(m)); + } + + function build() { + checks.length = 0; + const blocks = []; + for (const g of groups) { + const gHit = !filter || g.name.toLowerCase().includes(filter); + const ms = g.members.filter((m) => gHit || m.name.toLowerCase().includes(filter)); + if (!gHit && !ms.length) continue; + const block = el("div", { class: "pgroup" }, groupRow(g)); + if (hasMembers(g) && (open.has(g.name) || !gHit)) { + for (const m of ms) block.append(memberRow(g, m)); + if (g.more && gHit) { + block.append(el("div", { class: "pmore" }, + `and ${count(g.more)} more, which travel with ${g.name} when it is selected whole`)); + } + } + for (const r of block.querySelectorAll(".prow")) { + const cb = r.querySelector("input[type=checkbox]"); + r.addEventListener("click", rowClick(cb)); + } + blocks.push(block); + } + list.replaceChildren(...(blocks.length ? blocks + : [el("div", { class: "ptree-empty" }, filter ? "No part matches the filter." : opt.empty)])); + sync(); + } + + function sync(notify = true) { + for (const [cb, st] of checks) { + const s = st(); + cb.checked = s === "all"; + cb.indeterminate = s === "some"; + cb.disabled = locked; + } + const states = groups.map(groupState); + all.checked = states.length > 0 && states.every((s) => s === "all"); + all.indeterminate = !all.checked && states.some((s) => s !== "none"); + all.disabled = locked || groups.length === 0; + const n = api.selected().length; + countEl.textContent = n ? `${n} selected` : ""; + if (notify && opt.onChange) opt.onChange(api); + } + + api.el = node; + build(); + return api; +} + +/* ---------------------------------------------------------------- export */ + +const xfer = { parts: null, exportTree: null, exportFoot: null, exportFlash: null }; + +/* The name the server gives the download (its Content-Disposition, which a + browser prefers to anything the page suggests), stamped in UTC as it is. */ +function exportName() { + const d = new Date(); + const p = (n) => String(n).padStart(2, "0"); + return `qdb-export-${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}` + + `-${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}.tar.gz`; +} + +function cardHead(id, ic, title, sub, extra) { + return el("header", { class: "card-head" }, + el("div", { class: "card-icon" }, icon(ic)), + el("div", {}, el("h3", { id }, title), el("p", { class: "sub" }, sub)), + extra); +} + +function renderExport(d) { + const head = cardHead("export-title", "download", "Export", + "Download parts of the data root as a .tar.gz — documents, payload files and links, read from the files on disk."); + const body = el("div", { class: "card-body" }); + const foot = el("footer", { class: "card-foot" }); + $("#export-card").replaceChildren(head, body, foot); + xfer.exportFoot = foot; + + if (!d.available) { + body.append(callout("warn", "alert", "There is nothing to export from.", d.reason)); + foot.append(el("span", { class: "summary" }, "Export unavailable"), el("span", { class: "spacer" }), + el("button", { class: "btn primary", type: "button", disabled: true }, icon("download"), "Download archive")); + return; + } + + // Re-weighing the parts after an import must not undo the selection. + const prev = xfer.exportTree ? new Set(xfer.exportTree.selected()) : "all"; + xfer.exportTree = partsTree(d.groups, { + cols: d.indexed + ? [{ label: "nodes", value: (r) => count(r.nodes) }, { label: "documents", value: (r) => bytes(r.doc_bytes) }] + : [], + weight: d.indexed ? (r) => r.doc_bytes : null, + sum: (r) => ({ nodes: r.nodes, docs: r.doc_bytes }), + initial: prev, + empty: "The data root holds no directories that are part of the database.", + onChange: paintExportFoot, + }); + xfer.exportFlash = el("div"); + body.append( + xfer.exportTree.el, + xfer.exportFlash, + el("p", { class: "hint" }, d.indexed + ? "Nodes and document sizes come from the segment (epoch " + d.epoch + "). The archive itself is read from disk, " + + "so payload files and links travel too. Dot-files and _modules never do." + : "No segment is published, so the parts are not weighed. The export reads the files regardless.")); + paintExportFoot(xfer.exportTree); +} + +function paintExportFoot(t) { + const foot = xfer.exportFoot; + if (!foot) return; + const sel = t.selected(); + const tot = t.totals(); + const indexed = xfer.parts && xfer.parts.indexed; + const btn = el("button", { + class: "btn primary", type: "button", disabled: !sel.length, + onclick: () => startExport(sel, btn), + }, icon("download"), "Download archive"); + foot.replaceChildren( + el("div", { class: "summary" }, + sel.length + ? [el("b", {}, plural(tot.parts, "part")), + indexed ? ` · ${plural(tot.nodes, "node")} · ${bytes(tot.docs)} of documents` : ""] + : "Select the parts to export.", + sel.length ? el("span", { class: "fname" }, exportName()) : null), + el("span", { class: "spacer" }), + btn); +} + +function flashExport(kind, ic, title, text) { + const host = xfer.exportFlash; + if (!host) return; + const c = callout(kind, ic, title, text); + host.replaceChildren(c); + if (kind === "ok") setTimeout(() => { if (c.isConnected) c.remove(); }, 9000); +} + +/* A HEAD first: the route checks everything about the request before it + starts streaming, so this is where a bad selection is caught -- rather + than as a .tar.gz file that turns out to hold a JSON error. Then a plain + link, so the browser writes the stream to disk itself, however large. */ +async function startExport(sel, btn) { + const pairs = sel.map((p) => ["part", p]); + const url = apiUrl("api/export", pairs); + btn.disabled = true; + btn.replaceChildren(icon("spin"), "Preparing…"); + btn.classList.add("busy"); + try { + const h = await fetch(url, { method: "HEAD", headers: authHeaders() }); + if (h.status === 401) signIn.show(); + if (!h.ok) { + const b = await fetch(url, { headers: authHeaders() }).then((r) => r.json()).catch(() => ({})); + throw new Error(b.detail || b.error || `HTTP ${h.status}`); + } + const a = el("a", { href: downloadUrl("api/export", pairs), download: true, hidden: true }); + document.body.append(a); + a.click(); + a.remove(); + flashExport("ok", "check", "Download started.", + "The archive is written as it streams, so the browser cannot show its size in advance."); + } catch (e) { + flashExport("bad", "alert", "The export could not start.", e.message); + } finally { + btn.disabled = false; + btn.classList.remove("busy"); + btn.replaceChildren(icon("download"), "Download archive"); + } +} + +/* ------------------------------------------------------- archive reading */ + +/* Exact-length reads over a ReadableStream, so tar headers can be taken 512 + bytes at a time without holding the archive. */ +class ByteReader { + constructor(reader) { this.r = reader; this.chunks = []; this.have = 0; this.done = false; } + async fill(n) { + while (this.have < n && !this.done) { + const { value, done } = await this.r.read(); + if (done) { this.done = true; break; } + if (value.length) { this.chunks.push(value); this.have += value.length; } + } + return this.have >= n; + } + async read(n) { + if (!(await this.fill(n))) return null; + const out = new Uint8Array(n); + let off = 0; + while (off < n) { + const c = this.chunks[0]; + const take = Math.min(c.length, n - off); + out.set(c.subarray(0, take), off); + off += take; + if (take === c.length) this.chunks.shift(); else this.chunks[0] = c.subarray(take); + } + this.have -= n; + return out; + } + async skip(n) { + while (n > 0) { + if (!this.chunks.length && !(await this.fill(1))) return false; + const c = this.chunks[0]; + const take = Math.min(c.length, n); + if (take === c.length) this.chunks.shift(); else this.chunks[0] = c.subarray(take); + this.have -= take; + n -= take; + } + return true; + } + cancel() { this.r.cancel().catch(() => {}); } +} + +const UTF8 = new TextDecoder(); +const cstr = (b, off, len) => { + let end = off; + while (end < off + len && b[end] !== 0) end++; + return UTF8.decode(b.subarray(off, end)); +}; +function octal(b, off, len) { + if (b[off] & 0x80) { // GNU base-256, for sizes past 8 GiB + let v = 0; + for (let i = off + 1; i < off + len; i++) v = v * 256 + b[i]; + return v; + } + const s = cstr(b, off, len).trim(); + return s ? parseInt(s, 8) : 0; +} +function paxRecords(b) { + const out = {}; + let i = 0; + while (i < b.length) { + let sp = i; + while (sp < b.length && b[sp] !== 0x20) sp++; + const len = parseInt(UTF8.decode(b.subarray(i, sp)), 10); + if (!len) break; + const rec = UTF8.decode(b.subarray(sp + 1, i + len - 1)); + const eq = rec.indexOf("="); + if (eq > 0) out[rec.slice(0, eq)] = rec.slice(eq + 1); + i += len; + } + return out; +} + +/* Entries of a tar stream: ustar, GNU long names and PAX paths -- the three + spellings a long path comes in. Data not read by the consumer is skipped. */ +async function* tarEntries(br) { + let longName = null; + let paxPath = null; + for (;;) { + const h = await br.read(512); + if (!h || h.every((x) => x === 0)) return; + let sum = 0; + for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : h[i]; + if (sum !== octal(h, 148, 8)) throw new Error("this is not a tar archive, or it is damaged"); + const size = octal(h, 124, 12); + const type = String.fromCharCode(h[156] || 48); + const padded = Math.ceil(size / 512) * 512; + if (type === "L") { const d = await br.read(padded); longName = d && cstr(d, 0, size); continue; } + if (type === "x") { const d = await br.read(padded); paxPath = d && paxRecords(d.subarray(0, size)).path; continue; } + if (type === "g" || type === "K") { await br.skip(padded); continue; } + let name = cstr(h, 0, 100); + // POSIX ustar splits long names into prefix + name; GNU uses the same + // bytes for other fields, and says so with a different magic. + if (cstr(h, 257, 6) === "ustar") { const pre = cstr(h, 345, 155); if (pre) name = pre + "/" + name; } + if (longName) { name = longName; longName = null; } + if (paxPath) { name = paxPath; paxPath = null; } + let consumed = false; + yield { + name, size, type, + async read() { consumed = true; const d = await br.read(padded); return d ? d.subarray(0, size) : null; }, + }; + if (!consumed && !(await br.skip(padded))) return; + } +} + +const MANIFEST_NAME = ".qdb-export.json"; + +/* What an archive holds, read here so its parts can be offered before a byte + is uploaded. An export leads with its manifest, so for one of ours this + stops after the first entry however large the file; any other tar is read + to the end, decompressed as a stream and never held whole. The server + checks everything again: this is for choosing, not for trusting. */ +async function inspectArchive(file, onProgress) { + const magic = new Uint8Array(await file.slice(0, 2).arrayBuffer()); + const gz = magic[0] === 0x1f && magic[1] === 0x8b; + let seen = 0; + let stream = file.stream().pipeThrough(new TransformStream({ + transform(chunk, ctl) { seen += chunk.byteLength; onProgress(seen / (file.size || 1)); ctl.enqueue(chunk); }, + })); + if (gz) { + if (typeof DecompressionStream !== "function") { + throw new Error("This browser cannot read .gz files. Use a current browser, or gunzip the archive to a .tar first."); + } + stream = stream.pipeThrough(new DecompressionStream("gzip")); + } + const br = new ByteReader(stream.getReader()); + const groups = new Map(); + let manifest = null; + let unsafe = false; + let first = true; + const bump = (t, kind, size) => { + t[kind]++; + if (kind === "files") t.bytes += size; + }; + try { + for await (const e of tarEntries(br)) { + const isFirst = first; + first = false; + if (e.name.startsWith("/")) { unsafe = true; continue; } + const comps = e.name.split("/").filter((c) => c && c !== "."); + if (!comps.length) continue; + if (comps.includes("..")) { unsafe = true; continue; } + if (isFirst && comps.length === 1 && comps[0] === MANIFEST_NAME) { + const data = await e.read(); + try { + const m = JSON.parse(UTF8.decode(data)); + if (m && m.format === "qdb-export" && Array.isArray(m.groups)) { manifest = m; break; } + } catch { /* not ours after all: read on */ } + continue; + } + if (comps.some((c) => c.startsWith(".") || c === "_modules")) continue; + const kind = { 5: "dirs", 2: "links", 0: "files", 7: "files" }[e.type]; + if (!kind) continue; + let g = groups.get(comps[0]); + if (!g) groups.set(comps[0], (g = { name: comps[0], files: 0, dirs: 0, links: 0, bytes: 0, loose: 0, members: new Map() })); + bump(g, kind, e.size); + if (comps.length === 2 && kind !== "dirs") g.loose++; + if (comps.length > 1) { + let m = g.members.get(comps[1]); + if (!m) g.members.set(comps[1], (m = { name: comps[1], files: 0, dirs: 0, links: 0, bytes: 0, dir: false })); + bump(m, kind, e.size); + // As on the server: a member is a directory. A file directly in a + // group is counted toward it and travels with it whole. + if (comps.length > 2 || kind === "dirs") m.dir = true; + } + } + } catch (e) { + throw new Error(`The archive could not be read: ${e.message || e}`); + } finally { + br.cancel(); + } + const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0); + const list = manifest + ? manifest.groups.map((g) => ({ ...g, members: (g.members || []).slice(), more: 0 })) + : [...groups.values()].map((g) => ({ ...g, members: [...g.members.values()].filter((m) => m.dir), more: 0 })); + list.sort(byName); + for (const g of list) g.members.sort(byName); + return { gz, manifest, unsafe, groups: list }; +} + +/* ---------------------------------------------------------------- import */ + +const imp = { + file: null, archive: null, error: null, tree: null, reading: null, readBar: null, readToken: null, + mode: "merge", confirm: false, run: null, runBar: null, result: null, xhr: null, foot: null, +}; + +const importPolicy = () => (xfer.parts && xfer.parts.import) || { enabled: false, reason: null }; + +/* Parts the server does not have yet carry a "new" badge; absence of a badge + means the part exists and the import writes into it. */ +function serverBadge(g, m) { + if (!xfer.parts || !xfer.parts.available) return null; + const sg = xfer.parts.groups.find((x) => x.name === g.name); + const isNew = m ? sg && !sg.more && !sg.members.some((x) => x.name === m.name) : !sg; + return isNew ? el("span", { class: "badge new", title: "not on this server yet" }, "new") : null; +} + +function resetImport() { + if (imp.xhr) imp.xhr.abort(); + Object.assign(imp, { file: null, archive: null, error: null, tree: null, reading: null, readToken: null, + confirm: false, run: null, result: null, xhr: null }); + paintImport(); +} + +async function openArchive(file) { + const token = {}; + Object.assign(imp, { file, archive: null, error: null, tree: null, reading: 0, readToken: token, + confirm: false, run: null, result: null }); + paintImport(); + let frame = 0; + try { + const a = await inspectArchive(file, (f) => { + if (imp.readToken !== token || frame) return; + frame = requestAnimationFrame(() => { + frame = 0; + if (imp.readBar) imp.readBar.set(f, "Reading the archive", Math.round(f * 100) + "%"); + }); + }); + if (imp.readToken !== token) return; + imp.archive = a; + imp.tree = partsTree(a.groups, { + cols: [{ label: "files", value: (r) => count(r.files) }, { label: "size", value: (r) => bytes(r.bytes) }], + weight: (r) => r.bytes, + sum: (r) => ({ files: r.files, bytes: r.bytes }), + initial: "all", + badge: serverBadge, + // An export of db/_users holds every member of db it lists, yet not db: + // sending db would let a replace remove the rest of it. So a group goes + // as one part only when the archive was taken at it, and as its ticked + // members otherwise. A tar without a manifest does not say, so it gets + // the narrow reading: the group itself only when nothing narrower + // would carry it (no members, or files directly inside it). + wholeOk: (g) => (a.manifest + ? a.manifest.parts.some((p) => p === g.name) + : g.members.length === 0 || g.loose > 0), + empty: "The archive holds nothing this dashboard would import.", + onChange: () => { imp.confirm = false; paintImportFoot(); }, + }); + } catch (e) { + if (imp.readToken !== token) return; + imp.error = e.message; + } + imp.reading = null; + paintImport(); +} + +function dropZone() { + const input = el("input", { type: "file", accept: ".gz,.tgz,.tar,application/gzip,application/x-tar", hidden: true }); + input.addEventListener("change", () => { if (input.files[0]) openArchive(input.files[0]); }); + const z = el("div", { class: "drop", tabindex: "0", role: "button", "aria-label": "Choose an archive to import" }, + el("div", { class: "drop-icon" }, icon("archive")), + el("strong", {}, "Drop an export here"), + el("span", {}, "or ", el("span", { class: "link" }, "choose a file"), " · .tar.gz or .tar"), + input); + z.addEventListener("click", (e) => { if (e.target !== input) input.click(); }); + z.addEventListener("keydown", (e) => { + if (e.key === "Enter" || e.key === " ") { e.preventDefault(); input.click(); } + }); + z.addEventListener("dragover", (e) => { e.preventDefault(); z.classList.add("over"); }); + z.addEventListener("dragleave", () => z.classList.remove("over")); + z.addEventListener("drop", (e) => { + e.preventDefault(); + z.classList.remove("over"); + const f = e.dataTransfer && e.dataTransfer.files[0]; + if (f) openArchive(f); + }); + return z; +} + +function fileCard() { + const a = imp.archive; + const meta = [bytes(imp.file.size)]; + if (a && a.manifest) { + meta.push("exported " + when(a.manifest.created)); + meta.push(plural(a.manifest.parts.length, "part")); + } else if (a) { + meta.push("plain tar archive, no manifest"); + } + return el("div", { class: "filecard" }, + el("div", { class: "ficon" }, icon("archive")), + el("div", { class: "fbody" }, + el("div", { class: "fname", title: imp.file.name }, imp.file.name), + el("div", { class: "fmeta" }, meta.join(" · "))), + !imp.run && el("button", { + class: "btn ghost", type: "button", title: "Choose a different file", "aria-label": "Remove this file", + onclick: resetImport, + }, icon("x"))); +} + +function modeCards() { + const card = (mode, title, text) => { + const r = el("input", { type: "radio", name: "imp-mode", value: mode }); + r.checked = imp.mode === mode; + r.addEventListener("change", () => { imp.mode = mode; imp.confirm = false; paintImport(); }); + return el("label", { class: `mode ${mode}` + (imp.mode === mode ? " on" : "") }, + r, el("div", {}, el("b", {}, title), el("span", {}, text))); + }; + return el("div", { class: "modes", role: "radiogroup", "aria-label": "Import mode" }, + card("merge", "Merge", "Add and overwrite what the archive has. Everything else stays as it is."), + card("replace", "Replace", "Each selected part becomes exactly the archive's copy; what it lacks is removed.")); +} + +function tile(label, n, hot) { + return el("div", { class: "stat-tile" + (hot ? " hot" : "") }, el("b", {}, count(n || 0)), el("span", {}, label)); +} + +function resultPanel() { + const r = imp.result; + const kids = []; + const counted = r.applied !== undefined; + if (r.failed) { + kids.push(callout("bad", "alert", + counted && r.applied > 0 ? "The import stopped partway." : "Nothing was imported.", + r.detail || r.error)); + } else { + kids.push(callout("ok", "check", + `Imported ${plural(r.parts.length, "part")} in ${secs(r.ms)}.`, + r.mode === "replace" ? "Each selected part now matches the archive." : "Merged into what was already there.")); + } + if (counted) { + kids.push(el("div", { class: "stat-tiles" }, + tile("written", r.written + r.links), tile("unchanged", r.unchanged), + tile("removed", r.removed), tile("skipped", r.skipped_total, r.skipped_total > 0))); + if (r.trash) { + kids.push(el("div", { class: "pathline" }, + el("span", { class: "hint" }, "Displaced files are in"), + el("code", { title: r.trash }, r.trash), + navigator.clipboard && el("button", { + class: "btn ghost", type: "button", title: "Copy the path", "aria-label": "Copy the path", + onclick: () => navigator.clipboard.writeText(r.trash).catch(() => {}), + }, icon("copy")))); + } + if (r.skipped_total) { + kids.push(el("details", { class: "skips" }, + el("summary", {}, `${plural(r.skipped_total, "entry", "entries")} not imported`), + el("ul", {}, + ...r.skipped.map((s) => el("li", {}, el("code", { title: s.path }, s.path), el("span", {}, s.reason))), + r.skipped_total > r.skipped.length + ? el("li", {}, el("span", {}, `and ${count(r.skipped_total - r.skipped.length)} more`)) : null))); + } + if (!r.failed) { + kids.push(el("p", { class: "hint" }, + "The daemon picks the change up through inotify; the counts in the header follow as it does.")); + } + } + return el("div", { class: "card-body-block" }, ...kids); +} + +function paintImport() { + const pol = importPolicy(); + const state = xfer.parts + ? el("span", { class: "state" + (pol.enabled ? " ok" : ""), title: pol.enabled ? "uploads are accepted" : pol.reason || "" }, + pol.enabled ? "enabled" : "off") + : null; + const head = cardHead("import-title", "upload", "Import", + "Apply an export back to this server. The whole archive is checked before anything is written.", state); + const body = el("div", { class: "card-body" }); + const foot = el("footer", { class: "card-foot" }); + imp.foot = foot; + $("#import-card").replaceChildren(head, body, foot); + + if (xfer.parts && !pol.enabled && !imp.result) { + body.append(callout("warn", "lock", "Import is off on this dashboard.", + (pol.reason || "") + " You can still open an archive here to see what it holds.")); + } + if (!imp.file) { + body.append(dropZone()); + paintImportFoot(); + return; + } + body.append(fileCard()); + if (imp.reading !== null) { + imp.readBar = progressBar(); + imp.readBar.set(imp.reading || null, "Reading the archive", ""); + body.append(imp.readBar.el); + } else if (imp.error) { + body.append(callout("bad", "alert", "This file cannot be imported.", imp.error)); + } else if (imp.tree) { + if (imp.archive.unsafe) { + body.append(callout("bad", "alert", "This archive holds paths that climb out of its root.", + "The server refuses such an archive outright, so importing it will fail.")); + } + imp.tree.lock(!!(imp.run || imp.result)); + body.append(imp.tree.el); + if (!imp.run && !imp.result) { + body.append(modeCards(), el("p", { class: "hint" }, + "Everything an import overwrites or removes is moved to the trash bin", + pol.trash ? [" at ", el("code", {}, pol.trash)] : "", ", so a mistake can be undone by hand.")); + } + if (imp.run) { + imp.runBar = progressBar(); + imp.runBar.set(imp.run.frac, imp.run.label, imp.run.note); + body.append(imp.runBar.el); + } + if (imp.result) body.append(resultPanel()); + } + paintImportFoot(); +} + +function paintImportFoot() { + const foot = imp.foot; + if (!foot) return; + const pol = importPolicy(); + const summary = (...k) => el("div", { class: "summary" }, ...k); + const spacer = el("span", { class: "spacer" }); + // replaceChildren, unlike el(), would print a null child as "null". + const put = (...kids) => foot.replaceChildren(...kids.filter((k) => k)); + + if (!imp.file || !imp.tree) { + put(summary(imp.file ? (imp.error ? "Choose another file." : "Reading…") : "Choose an archive to see its parts."), + spacer, imp.error ? el("button", { class: "btn", type: "button", onclick: resetImport }, "Choose another file") : null); + return; + } + if (imp.run) { + put(summary(el("b", {}, imp.mode === "replace" ? "Replacing…" : "Importing…"), + " Keep this page open until it finishes."), spacer, + imp.run.phase === "upload" + ? el("button", { class: "btn ghost", type: "button", onclick: () => imp.xhr && imp.xhr.abort() }, "Cancel upload") + : null); + return; + } + if (imp.result) { + put(summary(imp.result.failed ? "Import failed." : el("b", {}, "Done.")), spacer, + el("button", { class: "btn", type: "button", onclick: resetImport }, icon("upload"), "Import another archive")); + return; + } + + const sel = imp.tree.selected(); + const tot = imp.tree.totals(); + const replace = imp.mode === "replace"; + if (imp.confirm) { + const verb = replace ? "Replace" : "Merge"; + put( + el("div", { class: "confirm" }, + replace ? `Replace ${plural(sel.length, "part")} with the archive's copy?` : `Merge ${plural(sel.length, "part")} into this server?`, + el("small", { title: sel.join(", ") }, sel.length > 4 ? sel.slice(0, 4).join(", ") + ", …" : sel.join(", "))), + spacer, + el("button", { class: "btn", type: "button", onclick: () => { imp.confirm = false; paintImportFoot(); } }, "Cancel"), + el("button", { class: "btn " + (replace ? "danger" : "primary"), type: "button", onclick: startImport }, + icon("upload"), `${verb} now`)); + return; + } + const why = !pol.enabled ? pol.reason || "import is off" + : !sel.length ? "select at least one part" : null; + put( + summary(sel.length + ? [el("b", {}, plural(tot.parts, "part")), ` · ${plural(tot.files, "file")} · ${bytes(tot.bytes)}`] + : "Select the parts to import."), + spacer, + el("button", { + class: "btn " + (replace ? "danger" : "primary"), type: "button", disabled: !!why, title: why, + onclick: () => { imp.confirm = true; paintImportFoot(); }, + }, icon("upload"), replace ? "Replace…" : "Import…")); +} + +function setRun(phase, frac, label, note) { + imp.run = { phase, frac, label, note }; + if (imp.runBar) imp.runBar.set(frac, label, note); + if (phase !== "upload") paintImportFoot(); +} + +/* The upload goes through XHR for its upload-progress events; the answer is a + stream of JSON lines (progress, then one done/error line), read as it + arrives from responseText. */ +function startImport() { + const pairs = imp.tree.selected().map((p) => ["part", p]); + pairs.push(["mode", imp.mode]); + imp.confirm = false; + imp.result = null; + imp.run = { phase: "upload", frac: 0, label: "Uploading", note: "" }; + paintImport(); + + const xhr = new XMLHttpRequest(); + imp.xhr = xhr; + xhr.open("POST", apiUrl("api/import", pairs)); + for (const [k, v] of Object.entries(authHeaders())) xhr.setRequestHeader(k, v); + xhr.setRequestHeader("Content-Type", imp.archive.gz ? "application/gzip" : "application/x-tar"); + xhr.upload.onprogress = (e) => { + if (e.lengthComputable) setRun("upload", e.loaded / e.total, "Uploading", `${bytes(e.loaded)} of ${bytes(e.total)}`); + }; + xhr.upload.onload = () => setRun("wait", null, "Waiting for the server", ""); + let seen = 0; + let finished = false; + const consume = () => { + if (xhr.status !== 200) return; + const text = xhr.responseText || ""; + let nl; + while ((nl = text.indexOf("\n", seen)) !== -1) { + const line = text.slice(seen, nl); + seen = nl + 1; + let m; + try { m = JSON.parse(line); } catch { continue; } + if (m.phase === "received") setRun("scan", 0, "Checking the archive", ""); + else if (m.phase === "scan") setRun("scan", m.total ? m.done / m.total : null, "Checking the archive", m.total ? pct(m.done, m.total) : ""); + else if (m.phase === "apply") setRun("apply", m.total ? m.done / m.total : null, "Applying", `${count(m.done)} of ${count(m.total)}`); + else if (m.phase === "prune") setRun("prune", null, "Removing what the archive lacks", ""); + else if (m.phase === "done" || m.phase === "error") { finished = true; finishImport(m.result, m.phase === "error"); } + } + }; + xhr.onprogress = consume; + xhr.onload = () => { + if (xhr.status === 401) signIn.show(); + if (xhr.status !== 200) { + let d = {}; + try { d = JSON.parse(xhr.responseText); } catch { /* not JSON */ } + finishImport({ error: d.error || `HTTP ${xhr.status}`, detail: d.detail || xhr.statusText }, true); + return; + } + consume(); + if (!finished) { + finishImport({ error: "no result", detail: "The connection closed before the server reported a result. " + + "Check the dashboard's log, and the trash bin for anything already displaced." }, true); + } + }; + xhr.onerror = () => finishImport({ error: "upload failed", detail: "The connection failed. With a large archive, " + + "a proxy in front of the dashboard may be capping the request size." }, true); + xhr.onabort = () => { imp.run = null; imp.xhr = null; paintImport(); }; + xhr.send(imp.file); +} + +function finishImport(result, failed) { + if (!imp.run) return; + imp.xhr = null; + imp.run = null; + imp.runBar = null; + imp.result = Object.assign({}, result, { failed }); + paintImport(); + pollStatus(); + // The daemon applies the change through inotify; give it a moment before + // the parts are weighed again. + setTimeout(loadParts, 1500); +} + +function loadParts() { + return api("api/parts") + .then((d) => { + xfer.parts = d; + renderExport(d); + if (!imp.run) paintImport(); + }) + .catch((e) => { + $("#export-card").replaceChildren( + cardHead("export-title", "download", "Export", "Download parts of the data root as a .tar.gz."), + el("div", { class: "card-body" }, callout("bad", "alert", "The parts could not be listed.", (e.body && e.body.detail) || e.message))); + }); +} + +/* ---------------------------------------------------------------- sign-in */ + +/* Shown when the API answers 401: the server is configured with a token and + this page has none, or one it no longer accepts. The token is tried against + the server before it is kept, so a typo is caught here rather than as a + page full of errors. The wording names no setting: this script is served to + anyone who can reach the port, before any token is checked. */ +const signIn = { + node: null, + + show() { + if (this.node) return; + const rejected = !!TOKEN; + // A kept token the server turned down must not come back on reload. + if (rejected && tokenFrom === "store") tokenStore.clear(); + + const input = el("input", { + type: "password", name: "token", autocomplete: "current-password", spellcheck: "false", + placeholder: "Paste the access token", "aria-label": "Access token", + }); + const remember = el("input", { type: "checkbox" }); + const err = el("p", { class: "err", role: "alert" }); + const btn = el("button", { class: "btn primary", type: "submit" }, icon("lock"), "Unlock"); + const form = el("form", { class: "card-body", novalidate: true }, + input, + el("label", { class: "check" }, remember, "Keep me signed in on this browser"), + err, + btn); + form.addEventListener("submit", (e) => { + e.preventDefault(); + this.submit(input, remember.checked, err, btn); + }); + const card = el("section", { class: "card", role: "dialog", "aria-modal": "true", "aria-labelledby": "signin-title" }, + cardHead("signin-title", "lock", + rejected ? "That token is not accepted" : "Sign in to the qdb dashboard", + rejected + ? "The server's token has changed, or the one this page had was wrong. Paste the current one." + : "This dashboard is protected. Paste its access token to continue."), + form); + this.node = el("div", { class: "signin" }, card); + document.body.append(this.node); + input.focus(); + }, + + async submit(input, remember, err, btn) { + const t = input.value.trim(); + if (!t) { + err.textContent = "Paste the token first."; + input.focus(); + return; + } + btn.disabled = true; + err.textContent = ""; + try { + const qs = authQuery(new URLSearchParams(), t).toString(); + const r = await fetch("api/summary" + (qs ? "?" + qs : ""), + { headers: { Accept: "application/json", ...authHeaders(t) } }); + if (r.status === 401) { + err.textContent = "That is not the token this server expects."; + input.select(); + return; + } + // Anything but 401 means the token passed: the gate runs before any + // route, and a route that then fails reports that in its own view. + this.accept(t, remember); + } catch { + err.textContent = "The server could not be reached."; + } finally { + btn.disabled = false; + } + }, + + accept(t, remember) { + TOKEN = t; + tokenFrom = "store"; + tokenStore.set(t, remember); + // A token in the address that the server turned down would win again on + // the next reload; the one just accepted replaces it. + if (URL_TOKEN !== null) { + const u = new URL(location.href); + u.searchParams.delete("token"); + history.replaceState(null, "", u.pathname + u.search + u.hash); + } + this.node.remove(); + this.node = null; + paintSignOut(); + pollStatus(); + renderBrowser(); + route(); + }, +}; + +/* Signing out forgets a token the page kept. One that came in the address is + the address's to keep, so there is nothing here to undo for it. A reload + then starts clean, with nothing of the site left on screen. */ +function paintSignOut() { + const old = $("#signout"); + if (old) old.remove(); + if (tokenFrom !== "store") return; + $("#status").append(el("button", { + id: "signout", class: "btn ghost signout", type: "button", + title: "Sign out: forget the token on this browser", "aria-label": "Sign out", + onclick: () => { tokenStore.clear(); location.reload(); }, + }, icon("logout"))); +} + /* --------------------------------------------------------------- routing */ let statsTimer = null; @@ -814,11 +1902,13 @@ function route() { const node = h.match(/^#\/node\/(.*)$/); const sizes = h.match(/^#\/sizes(?:\/(.*))?$/); const stats = h === "#/stats"; - const view = stats ? "stats" : sizes ? "sizes" : "files"; + const transfer = h === "#/transfer"; + const view = stats ? "stats" : sizes ? "sizes" : transfer ? "transfer" : "files"; $("#files-view").hidden = view !== "files"; $("#sizes-view").hidden = view !== "sizes"; $("#stats-view").hidden = view !== "stats"; + $("#transfer-view").hidden = view !== "transfer"; document.querySelectorAll("#bar nav a").forEach((a) => a.classList.toggle("on", (a.dataset.view || "files") === view)); @@ -836,6 +1926,11 @@ function route() { loadSizes(); return; } + if (view === "transfer") { + if (!xfer.parts) paintImport(); + loadParts(); + return; + } if (node) showNode(decodeURIComponent(node[1])); } @@ -883,6 +1978,7 @@ function init() { }); window.addEventListener("hashchange", route); + paintSignOut(); pollStatus(); setInterval(pollStatus, 5000); renderBrowser(); diff --git a/qdb/src/dashboard/index.html b/qdb/src/dashboard/index.html index 281e138f1..fc3754d80 100644 --- a/qdb/src/dashboard/index.html +++ b/qdb/src/dashboard/index.html @@ -10,6 +10,7 @@ Files Size Stats + Export / Import
connecting @@ -59,4 +60,14 @@
+ +
+
+
+
+
+
+ diff --git a/qdb/src/transfer.rs b/qdb/src/transfer.rs new file mode 100644 index 000000000..76c80310e --- /dev/null +++ b/qdb/src/transfer.rs @@ -0,0 +1,2061 @@ +//! Export and import for `qdbstat --dashboard`: parts of the data root as a +//! plain `.tar.gz`, and the same archive applied back. +//! +//! Everything else the dashboard shows comes from the segment. This does not, +//! and on purpose: an archive is a backup, and a backup of "what PHP is being +//! served" would miss the payload files (`assets`, `files`), every document +//! over `quanta_db.image_max_doc_kb`, and the links as links. The files are +//! the source of truth (see the README), so the files are what is archived. +//! +//! The rules that shape it: +//! +//! * **A part is a directory under the root.** The listing offers two +//! levels — the root's directories (`db`) and theirs (`db/_users`) — +//! because the first level alone is too coarse on a Quanta site, whose +//! root holds `db/` and `_tpl/` and nothing a person would pick between. +//! * **What the daemon never indexes is never exported or imported**: +//! dot-prefixed names and `_modules`, the same rule as `store::skip_dir`. +//! That rule is what keeps module code, `.env` and VCS metadata out of an +//! archive, and — on the way in — keeps an archive from planting them. +//! * **Links survive a move.** Quanta writes container links as absolute +//! paths. An export rewrites the ones that point inside the root as +//! relative, so the archive does not carry one deployment's paths; an +//! import turns them back into absolute paths under *its* root, and drops +//! any link that would land outside it. +//! * **An import validates the whole archive before it writes a byte.** The +//! upload is spooled to a temp file and read twice: once to check every +//! entry (paths, types, sizes, the gzip trailer), once to apply it. A +//! truncated or hostile archive is refused with nothing changed. +//! * **Nothing an import displaces is lost.** Every file it overwrites and +//! everything a replace removes goes to the trash bin, under one +//! `-import` directory per run. The trash is *outside* the site +//! directory, as Quanta's own is: the legacy `find` fallback does not skip +//! dot-directories, so a trash folder inside the root would offer stale +//! copies of nodes to every name lookup that reached it. +//! * Each file lands by temp file + rename in its own directory, so a reader +//! sees the old document or the new one, never half of one. The import as +//! a whole is not a transaction: it is a maintenance operation, and the +//! daemon picks the changes up through inotify like any other write. +#![allow(dead_code)] + +use std::cell::Cell; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::OsStr; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, BufReader, Read, Seek, SeekFrom, Write}; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; +use std::os::unix::io::AsRawFd; +use std::path::{Component, Path, PathBuf}; +use std::rc::Rc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use serde_json::{json, Value}; + +use crate::own; +use crate::shm::SegmentReader; + +/// First entry of every export: what it holds, so an import page can list the +/// parts without reading the rest of a multi-gigabyte archive. +pub const MANIFEST: &str = ".qdb-export.json"; +/// Last entry of an export that could not read everything it was asked for. +/// The status line went out before the walk, so this is the only place left +/// to say so. +pub const ERRORS_FILE: &str = ".qdb-export-errors.txt"; +pub const FORMAT: &str = "qdb-export"; +pub const FORMAT_VERSION: u64 = 1; + +/// Default cap on an import's *uncompressed* size, in MiB. The uncompressed +/// size is the one that matters: it is what lands on disk, and a small gzip +/// can expand into a full one. +pub const DEFAULT_IMPORT_MAX_MB: u64 = 2048; + +/// Members listed per group. A root that is itself `db/` has a group per +/// top-level node, and `_users` alone can hold tens of thousands; the rest +/// still travel with their group, they just are not offered one by one. +const MEMBERS_MAX: usize = 500; +/// Nesting beyond this is taken as a loop or an attack, not a node tree. +const MAX_DEPTH: usize = 128; +/// Entries per archive. Bounds the replace-mode path set as much as anything. +const MAX_ENTRIES: u64 = 5_000_000; +/// Files up to this size are compared with what is on disk, so re-importing +/// an export changes nothing (no write, no inotify event, no trash entry). +/// Larger ones are written unconditionally rather than buffered. +const COMPARE_MAX: u64 = 8 << 20; +/// Skipped entries itemised in a result; the rest are only counted. +const SKIPPED_SHOWN: usize = 200; +/// A manifest is a few KB; anything far larger is not ours. +const MANIFEST_MAX: u64 = 4 << 20; +/// Progress lines at most this often. +const PROGRESS_EVERY: Duration = Duration::from_millis(250); + +/// What the dashboard may do with the root. Built once at startup. +#[derive(Clone)] +pub struct Policy { + /// Canonical data root, or `None` when qdbstat was pointed at a segment + /// (`--shm` + `--data-dir`) without naming the root it came from. + pub root: Option, + /// The root as configured, before canonicalisation. Symlink targets are + /// written with this spelling because it is the one Quanta writes them + /// with (`Environment->dir['docroot']`), and a reader comparing link + /// targets textually should not see an import as a change. + pub link_root: Option, + pub import: bool, + /// Why import is off, in words an operator can act on. + pub import_off: Option, + /// Cap on an import's uncompressed size, and therefore on its upload. + pub max_bytes: u64, + /// Trash bin root; each import makes `-import` under it. + pub trash: Option, + /// Where uploads are spooled before they are validated. + pub spool_dir: PathBuf, +} + +impl Policy { + /// Export only, no root: what a dashboard started without one gets. + pub fn none() -> Policy { + Policy { + root: None, + link_root: None, + import: false, + import_off: Some("qdbstat was started without a data root.".into()), + max_bytes: DEFAULT_IMPORT_MAX_MB << 20, + trash: None, + spool_dir: std::env::temp_dir(), + } + } + + /// The spelling symlink targets are written with. + fn link_spelling(&self) -> Option<&Path> { + self.link_root.as_deref().or(self.root.as_deref()) + } +} + +/// The daemon's rule for what is not a node (`store::skip_dir`), applied to +/// every name an archive carries in either direction. +pub fn excluded(name: &str) -> bool { + name.starts_with('.') || name == "_modules" +} + +/// `path` is `ancestor` or below it, component-wise: `db` covers `db/_users` +/// but not `db2`. +fn covers(ancestor: &str, path: &str) -> bool { + path == ancestor + || (path.len() > ancestor.len() + && path.starts_with(ancestor) + && path.as_bytes()[ancestor.len()] == b'/') +} + +/// One part name from a request, as a clean root-relative path. +/// +/// A part reaches the filesystem, unlike a node name elsewhere in the +/// dashboard, so this is the traversal check: plain components only, none +/// of them a name the daemon would not index. +pub fn parse_part(raw: &str) -> Result { + let t = raw.trim_matches('/'); + if t.is_empty() { + return Err("an empty part would name the whole root; select its parts instead".into()); + } + if t.len() > 4096 || t.contains('\0') { + return Err(format!("{raw:?} is not a usable part name")); + } + for c in t.split('/') { + if c.is_empty() || c == "." || c == ".." { + return Err(format!("{raw:?} is not a plain relative path")); + } + if excluded(c) { + return Err(format!( + "{raw:?}: dot-prefixed names and _modules are not part of the database" + )); + } + } + Ok(t.to_string()) +} + +/// Parse, sort and de-overlap a request's parts: `db` and `db/_users` +/// together mean `db`, and an archive must not hold the subtree twice. +pub fn normalize_parts(raw: &[String]) -> Result, String> { + let mut v = raw.iter().map(|r| parse_part(r)).collect::, _>>()?; + if v.is_empty() { + return Err("select at least one part".into()); + } + // Sorted, an ancestor always precedes its descendants (it is their prefix). + v.sort(); + v.dedup(); + let mut out: Vec = Vec::new(); + for p in v { + if !out.iter().any(|a| covers(a, &p)) { + out.push(p); + } + } + Ok(out) +} + +/// A part may be reached through symlinks above it — a `db` that is a link to +/// a mounted volume is deployment layout — but below the first level it must +/// not BE one. A link at `db/x` is a Quanta container link: archiving it as a +/// part would copy its target under the link's name, and importing that +/// would create a second directory with the target's node name. +fn check_part_on_disk(root: &Path, part: &str) -> Result<(), String> { + if part.contains('/') { + if let Ok(md) = fs::symlink_metadata(root.join(part)) { + if md.file_type().is_symlink() { + return Err(format!( + "{part} is a link on this server; export or import the directory that holds it" + )); + } + } + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Listing +// --------------------------------------------------------------------------- + +#[derive(Default, Clone, Copy)] +struct Weight { + nodes: u64, + doc_bytes: u64, +} + +/// Node count and document bytes per first-level and second-level path, +/// from the segment. Keys borrow the mapping, so the pass allocates one map +/// entry per distinct part and nothing per node. +fn weights<'a>(seg: &'a SegmentReader) -> (HashMap<&'a str, Weight>, HashMap<&'a str, Weight>) { + let mut groups: HashMap<&'a str, Weight> = HashMap::new(); + let mut members: HashMap<&'a str, Weight> = HashMap::new(); + seg.for_each_live(|rec| { + let rp: &'a str = rec.rel_path(); + if rp.is_empty() { + return; + } + let docs: u64 = rec.langs().iter().map(|l| l.doc_size.max(0) as u64).sum(); + let mut slashes = rp.match_indices('/').map(|(i, _)| i); + let g_end = slashes.next().unwrap_or(rp.len()); + let m_end = slashes.next().unwrap_or(rp.len()); + let g = groups.entry(&rp[..g_end]).or_default(); + g.nodes += 1; + g.doc_bytes += docs; + if g_end < rp.len() { + let m = members.entry(&rp[..m_end]).or_default(); + m.nodes += 1; + m.doc_bytes += docs; + } + }); + (groups, members) +} + +/// Directories a part can be, directly inside `dir`, sorted by name. +/// `follow_links` admits symlinks to directories (the first level, where a +/// link is deployment layout) or not (below it, where a link is a container +/// link; see `check_part_on_disk`). Non-UTF-8 names are left out: they cannot +/// travel through a query string or the JSON this is rendered from. +fn list_dirs(dir: &Path, follow_links: bool) -> Vec<(String, bool)> { + let Ok(rd) = fs::read_dir(dir) else { return Vec::new() }; + let mut out = Vec::new(); + for e in rd.flatten() { + let Ok(name) = e.file_name().into_string() else { continue }; + if excluded(&name) { + continue; + } + let Ok(ft) = e.file_type() else { continue }; + let link = ft.is_symlink(); + let is_dir = if link { + follow_links && fs::metadata(e.path()).map(|m| m.is_dir()).unwrap_or(false) + } else { + ft.is_dir() + }; + if is_dir { + out.push((name, link)); + } + } + out.sort(); + out +} + +/// `/api/parts`: what can be exported, weighed from the segment when there is +/// one, and what this dashboard will accept back. +pub fn parts_json(p: &Policy, seg: Option<&SegmentReader>) -> Value { + let import = json!({ + "enabled": p.import, + "reason": p.import_off, + "max_bytes": p.max_bytes, + "trash": p.trash.as_ref().map(|t| t.display().to_string()), + }); + let Some(root) = &p.root else { + return json!({ + "available": false, + "reason": "qdbstat was started without a data root (--root or QUANTA_DB_ROOT), \ + so there is no directory to export from", + "import": import, + "groups": [], + }); + }; + + let (gw, mw) = seg.map(weights).unwrap_or_default(); + let weigh = |w: Option<&Weight>| match (seg, w) { + (None, _) => (Value::Null, Value::Null), + (Some(_), Some(w)) => (json!(w.nodes), json!(w.doc_bytes)), + (Some(_), None) => (json!(0), json!(0)), + }; + + let mut groups = Vec::new(); + for (name, link) in list_dirs(root, true) { + let mut members = list_dirs(&root.join(&name), false); + let more = members.len().saturating_sub(MEMBERS_MAX); + members.truncate(MEMBERS_MAX); + let members: Vec = members + .into_iter() + .map(|(m, _)| { + let key = format!("{name}/{m}"); + let (nodes, docs) = weigh(mw.get(key.as_str())); + json!({ "name": m, "nodes": nodes, "doc_bytes": docs }) + }) + .collect(); + let (nodes, docs) = weigh(gw.get(name.as_str())); + groups.push(json!({ + "name": name, + "link": link, + "nodes": nodes, + "doc_bytes": docs, + "members": members, + "more": more, + })); + } + + json!({ + "available": true, + "indexed": seg.is_some(), + "epoch": seg.map(|s| s.epoch), + "import": import, + "groups": groups, + }) +} + +// --------------------------------------------------------------------------- +// Walking +// --------------------------------------------------------------------------- + +/// What a walk callback is told about one entry. +type Visit<'v> = dyn FnMut(&str, &Path, &fs::Metadata, &mut Vec) -> io::Result<()> + 'v; + +/// Visit `part` and, when it is a directory, everything below it that is part +/// of the database. The part itself is reached through symlinks (see +/// `check_part_on_disk`); nothing below it is — a link there is visited as a +/// link. Problems reading the tree are collected in `errors`; an error from +/// `visit` aborts, because that is the archive's writer failing. +fn walk_part(root: &Path, part: &str, errors: &mut Vec, visit: &mut Visit<'_>) -> io::Result<()> { + let abs = root.join(part); + let md = match fs::metadata(&abs) { + Ok(m) => m, + Err(e) => { + errors.push(format!("{part}: {e}")); + return Ok(()); + } + }; + visit(part, &abs, &md, errors)?; + if md.is_dir() { + walk_dir(&abs, part, 1, errors, visit)?; + } + Ok(()) +} + +fn walk_dir( + dir: &Path, + rel: &str, + depth: usize, + errors: &mut Vec, + visit: &mut Visit<'_>, +) -> io::Result<()> { + let rd = match fs::read_dir(dir) { + Ok(r) => r, + Err(e) => { + errors.push(format!("{rel}: {e}")); + return Ok(()); + } + }; + let mut names: Vec = Vec::new(); + for e in rd { + match e { + Ok(e) => match e.file_name().into_string() { + Ok(n) if !excluded(&n) => names.push(n), + Ok(_) => {} + Err(raw) => errors.push(format!( + "{rel}/{}: name is not UTF-8, skipped", + raw.to_string_lossy() + )), + }, + Err(e) => errors.push(format!("{rel}: {e}")), + } + } + // Sorted so two exports of the same tree are the same archive. + names.sort(); + for name in names { + let abs = dir.join(&name); + let r = format!("{rel}/{name}"); + let md = match fs::symlink_metadata(&abs) { + Ok(m) => m, + Err(e) => { + errors.push(format!("{r}: {e}")); + continue; + } + }; + visit(&r, &abs, &md, errors)?; + if md.is_dir() { + if depth + 1 >= MAX_DEPTH { + errors.push(format!("{r}: nested deeper than {MAX_DEPTH} levels, not descended")); + continue; + } + walk_dir(&abs, &r, depth + 1, errors, visit)?; + } + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Export +// --------------------------------------------------------------------------- + +/// A validated export request. Building it touches nothing but `stat`, so a +/// bad request is answered with a status code before the download starts. +pub struct ExportPlan { + root: PathBuf, + link_root: PathBuf, + parts: Vec, +} + +impl ExportPlan { + pub fn parts(&self) -> &[String] { + &self.parts + } +} + +pub fn plan_export(p: &Policy, raw_parts: &[String]) -> Result { + let Some(root) = &p.root else { + return Err((503, "no data root configured".into())); + }; + let parts = normalize_parts(raw_parts).map_err(|e| (400, e))?; + for part in &parts { + check_part_on_disk(root, part).map_err(|e| (400, e))?; + if fs::metadata(root.join(part)).is_err() { + return Err((404, format!("{part} does not exist under the data root"))); + } + } + Ok(ExportPlan { + root: root.clone(), + link_root: p.link_spelling().unwrap_or(root).to_path_buf(), + parts, + }) +} + +#[derive(Default, Clone, Copy)] +struct Tally { + files: u64, + dirs: u64, + links: u64, + bytes: u64, +} + +impl Tally { + fn add(&mut self, md: &fs::Metadata) { + let ft = md.file_type(); + if ft.is_symlink() { + self.links += 1; + } else if ft.is_dir() { + self.dirs += 1; + } else if ft.is_file() { + self.files += 1; + self.bytes += md.len(); + } + } + + fn json(&self) -> serde_json::Map { + let mut m = serde_json::Map::new(); + m.insert("files".into(), json!(self.files)); + m.insert("dirs".into(), json!(self.dirs)); + m.insert("links".into(), json!(self.links)); + m.insert("bytes".into(), json!(self.bytes)); + m + } +} + +/// The manifest's tree: the same two levels the listing offers, so an import +/// page can offer any of them from an archive exported at either. As in the +/// listing, a member is a real directory; a file or link directly inside a +/// group counts toward the group and travels with it whole. +fn manifest(plan: &ExportPlan, created: u64) -> Value { + let mut groups: BTreeMap)> = BTreeMap::new(); + let mut ignored = Vec::new(); + for part in &plan.parts { + let _ = walk_part(&plan.root, part, &mut ignored, &mut |rel, _abs, md, _errs| { + let mut it = rel.splitn(3, '/'); + let g = it.next().unwrap_or_default(); + let entry = groups.entry(g.to_string()).or_default(); + entry.0.add(md); + if let Some(m) = it.next() { + let member = entry.1.entry(m.to_string()).or_default(); + member.0.add(md); + // Below the part the walk does not follow links, so this is + // the entry itself: a directory, not a link to one. + if it.next().is_some() || md.file_type().is_dir() { + member.1 = true; + } + } + Ok(()) + }); + } + let groups: Vec = groups + .into_iter() + .map(|(name, (t, members))| { + let mut g = t.json(); + g.insert("name".into(), json!(name)); + g.insert( + "members".into(), + Value::Array( + members + .into_iter() + .filter(|(_, (_, dir))| *dir) + .map(|(m, (t, _))| { + let mut v = t.json(); + v.insert("name".into(), json!(m)); + Value::Object(v) + }) + .collect(), + ), + ); + Value::Object(g) + }) + .collect(); + json!({ + "format": FORMAT, + "version": FORMAT_VERSION, + "created": created, + "generator": "qdbstat", + "parts": plan.parts, + "groups": groups, + }) +} + +/// `/a/b` → `a/b`, for a link target that resolves inside the root by +/// any of its spellings: the canonical root, the root as configured (a site +/// alias is a symlink to the site), or the target's own resolved path (`db` +/// may be a link to a volume while Quanta writes targets through it). +fn inside_root<'p>(root: &Path, link_root: &Path, target: &'p Path) -> Option { + if let Ok(real) = fs::canonicalize(target) { + if let Ok(inner) = real.strip_prefix(root) { + return Some(inner.to_path_buf()); + } + } + let lex = lexical(target)?; + lex.strip_prefix(root) + .or_else(|_| lex.strip_prefix(link_root)) + .ok() + .map(Path::to_path_buf) +} + +/// The path from directory `from` to `to`, both root-relative. +fn relative_path(from: &Path, to: &Path) -> PathBuf { + let f: Vec<_> = from.components().collect(); + let t: Vec<_> = to.components().collect(); + let common = f.iter().zip(&t).take_while(|(a, b)| a == b).count(); + let mut out = PathBuf::new(); + for _ in common..f.len() { + out.push(".."); + } + for c in &t[common..] { + out.push(c.as_os_str()); + } + if out.as_os_str().is_empty() { + out.push("."); + } + out +} + +/// Normalise `.` and `..` without touching the filesystem. `None` for a path +/// that climbs above `/`, which no target worth keeping does. +fn lexical(p: &Path) -> Option { + let mut out = PathBuf::new(); + for c in p.components() { + match c { + Component::RootDir => out.push("/"), + Component::CurDir => {} + Component::ParentDir => { + if !out.pop() { + return None; + } + } + Component::Normal(s) => out.push(s), + Component::Prefix(_) => return None, + } + } + Some(out) +} + +fn gnu_header(kind: tar::EntryType, mode: u32, mtime: i64, size: u64) -> tar::Header { + let mut h = tar::Header::new_gnu(); + h.set_entry_type(kind); + h.set_mode(mode); + h.set_mtime(mtime.max(0) as u64); + h.set_size(size); + h +} + +/// Stream the archive into `out`. Errors reading the tree are written into +/// the archive itself (`ERRORS_FILE`); an error writing `out` aborts, since +/// that is the client going away. +pub fn write_export(plan: &ExportPlan, out: &mut dyn Write) -> io::Result<()> { + let created = unix_now(); + let gz = flate2::write::GzEncoder::new(out, flate2::Compression::default()); + let mut tb = tar::Builder::new(gz); + + let man = serde_json::to_vec_pretty(&manifest(plan, created)).unwrap_or_default(); + let mut h = gnu_header(tar::EntryType::Regular, 0o644, created as i64, man.len() as u64); + tb.append_data(&mut h, MANIFEST, man.as_slice())?; + + let mut errors: Vec = Vec::new(); + for part in &plan.parts { + walk_part(&plan.root, part, &mut errors, &mut |rel, abs, md, errs| { + let ft = md.file_type(); + if ft.is_symlink() { + let target = match fs::read_link(abs) { + Ok(t) => t, + Err(e) => { + errs.push(format!("{rel}: {e}")); + return Ok(()); + } + }; + let portable = if target.is_absolute() { + match inside_root(&plan.root, &plan.link_root, &target) { + Some(inner) => { + let from = Path::new(rel).parent().unwrap_or(Path::new("")); + relative_path(from, &inner) + } + // Kept verbatim: it is what is on disk. An import + // will refuse it, and say so. + None => target, + } + } else { + target + }; + let mut h = gnu_header(tar::EntryType::Symlink, 0o777, md.mtime(), 0); + tb.append_link(&mut h, rel, &portable) + } else if ft.is_dir() { + let mut h = gnu_header(tar::EntryType::Directory, 0o755, md.mtime(), 0); + tb.append_data(&mut h, rel, io::empty()) + } else if ft.is_file() { + let f = match File::open(abs) { + Ok(f) => f, + Err(e) => { + errs.push(format!("{rel}: {e}")); + return Ok(()); + } + }; + // Sized from the open handle, and padded to that size: a + // file rewritten in place mid-read must still leave a + // well-formed archive (Quanta replaces by rename, so the + // handle normally keeps the old inode whole). + let fmd = f.metadata()?; + let size = fmd.len(); + let mode = if fmd.mode() & 0o100 != 0 { 0o755 } else { 0o644 }; + let mut h = gnu_header(tar::EntryType::Regular, mode, fmd.mtime(), size); + let data = (&f).take(size).chain(io::repeat(0)).take(size); + tb.append_data(&mut h, rel, data) + } else { + errs.push(format!("{rel}: not a file, directory or symlink; skipped")); + Ok(()) + } + })?; + } + + if !errors.is_empty() { + let mut text = format!( + "{} entries could not be read while this archive was written:\n\n", + errors.len() + ); + for e in &errors { + text.push_str(e); + text.push('\n'); + } + let mut h = gnu_header(tar::EntryType::Regular, 0o644, unix_now() as i64, text.len() as u64); + tb.append_data(&mut h, ERRORS_FILE, text.as_bytes())?; + } + + let gz = tb.into_inner()?; + gz.finish()?.flush() +} + +/// `qdb-export-20261201-130455.tar.gz`, in UTC. +pub fn export_filename(unix: u64) -> String { + format!("qdb-export-{}.tar.gz", stamp(unix)) +} + +/// `YYYYMMDD-HHMMSS`, UTC: sorts as time does and reads as a date in a +/// downloads folder. +fn stamp(unix: u64) -> String { + let days = (unix / 86_400) as i64; + let secs = unix % 86_400; + // Howard Hinnant's civil_from_days. + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!( + "{y:04}{m:02}{d:02}-{:02}{:02}{:02}", + secs / 3600, + secs / 60 % 60, + secs % 60 + ) +} + +pub fn unix_now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +// --------------------------------------------------------------------------- +// Import +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum Mode { + /// Write what the archive has; leave everything else alone. + Merge, + /// Make each selected part exactly the archive's copy: what it does not + /// have is removed (to the trash, like everything else displaced). + Replace, +} + +impl Mode { + pub fn parse(s: &str) -> Result { + match s { + "" | "merge" => Ok(Mode::Merge), + "replace" => Ok(Mode::Replace), + other => Err(format!("unknown mode {other:?}; use merge or replace")), + } + } + + fn label(self) -> &'static str { + match self { + Mode::Merge => "merge", + Mode::Replace => "replace", + } + } +} + +pub struct ImportSpec { + pub parts: Vec, + pub mode: Mode, +} + +/// Validate an import request against the policy and the disk. Nothing is +/// read from the body yet. +pub fn plan_import(p: &Policy, raw_parts: &[String], mode: &str) -> Result { + if !p.import { + let why = p.import_off.as_deref().unwrap_or_default(); + return Err((403, format!("Import is off. {why}").trim_end().to_string())); + } + let Some(root) = &p.root else { + return Err((503, "no data root configured".into())); + }; + let mode = Mode::parse(mode).map_err(|e| (400, e))?; + let parts = normalize_parts(raw_parts).map_err(|e| (400, e))?; + for part in &parts { + check_part_on_disk(root, part).map_err(|e| (400, e))?; + } + Ok(ImportSpec { parts, mode }) +} + +static IMPORT_BUSY: AtomicBool = AtomicBool::new(false); + +/// One import at a time per process. Two interleaved imports into the same +/// tree would each trash the other's files as "displaced". +pub struct ImportLock(()); + +impl ImportLock { + pub fn try_take() -> Option { + IMPORT_BUSY + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .ok() + .map(|_| ImportLock(())) + } +} + +impl Drop for ImportLock { + fn drop(&mut self) { + IMPORT_BUSY.store(false, Ordering::Release); + } +} + +/// The upload, on disk, removed when dropped. +pub struct Spool { + path: PathBuf, + len: u64, +} + +impl Spool { + pub fn len(&self) -> u64 { + self.len + } +} + +impl Drop for Spool { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + +/// Copy exactly `len` bytes of `body` to a private temp file. +pub fn spool(body: &mut dyn Read, len: u64, dir: &Path) -> io::Result { + let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let path = dir.join(format!("qdb-import-{}-{nanos}.upload", std::process::id())); + let mut f = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(&path)?; + // Built before the copy so a short read still removes the file. + let s = Spool { path, len }; + let n = io::copy(&mut body.take(len), &mut f)?; + if n != len { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + format!("the upload ended after {n} of {len} bytes"), + )); + } + Ok(s) +} + +/// Counts what the decoder pulls from the spool, for scan progress. +struct Counted { + inner: R, + n: Rc>, +} + +impl Read for Counted { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let k = self.inner.read(buf)?; + self.n.set(self.n.get() + k as u64); + Ok(k) + } +} + +/// Fails the read once the decompressed stream passes `left` bytes. +struct Limited { + inner: R, + left: u64, + max: u64, +} + +impl Read for Limited { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let k = self.inner.read(buf)?; + if k as u64 > self.left { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("the archive expands past the {} MiB import limit", self.max >> 20), + )); + } + self.left -= k as u64; + Ok(k) + } +} + +fn open_archive(path: &Path, max: u64, counter: Rc>) -> io::Result>> { + let mut f = File::open(path)?; + let mut magic = [0u8; 2]; + let mut got = 0; + while got < 2 { + match f.read(&mut magic[got..])? { + 0 => break, + k => got += k, + } + } + f.seek(SeekFrom::Start(0))?; + let counted = Counted { inner: BufReader::with_capacity(256 << 10, f), n: counter }; + let decoded: Box = if got == 2 && magic == [0x1f, 0x8b] { + // Multi-member: `pigz` and `cat a.gz b.gz` both produce more than one. + Box::new(flate2::read::MultiGzDecoder::new(counted)) + } else { + Box::new(counted) + }; + Ok(tar::Archive::new(Box::new(Limited { inner: decoded, left: max, max }) as Box)) +} + +/// What one archive entry means for this import. +enum Decision { + /// Not under a selected part (or the archive's own `./`). + Ignore, + /// The export manifest. + Manifest, + /// Under a selected part, and deliberately not written. + Skip(String), + Dir, + File { size: u64, exec: bool }, + /// The target to write: absolute, under the root, in `link_root` spelling. + Link(PathBuf), +} + +/// Classify an entry. `Err` is reserved for an archive that is hostile rather +/// than merely untidy — a path that is absolute or climbs out — which +/// refuses the whole import, not just the entry. +fn classify( + e: &tar::Entry<'_, R>, + parts: &[String], + root: &Path, + link_root: &Path, +) -> Result<(String, Option, Decision), String> { + let raw = e.path_bytes(); + let utf8 = std::str::from_utf8(&raw).is_ok(); + let lossy = String::from_utf8_lossy(&raw); + if lossy.starts_with('/') { + return Err(format!("the archive holds an absolute path ({lossy}); refusing it")); + } + let mut comps: Vec<&str> = Vec::new(); + for c in lossy.split('/') { + match c { + "" | "." => {} + ".." => { + return Err(format!( + "the archive holds a path that climbs out of its root ({lossy}); refusing it" + )) + } + c => comps.push(c), + } + } + if comps.is_empty() { + return Ok((String::new(), None, Decision::Ignore)); + } + let rel = comps.join("/"); + if comps.len() == 1 && comps[0] == MANIFEST { + return Ok((rel, None, Decision::Manifest)); + } + let Some(pi) = parts.iter().position(|p| covers(p, &rel)) else { + return Ok((rel, None, Decision::Ignore)); + }; + let skip = |why: &str| Ok((rel.clone(), Some(pi), Decision::Skip(why.to_string()))); + if !utf8 { + return skip("the name is not valid UTF-8"); + } + if comps.iter().any(|c| excluded(c)) { + return skip("dot-prefixed names and _modules are never part of the database"); + } + if comps.len() > MAX_DEPTH { + return skip("nested too deep"); + } + + let t = e.header().entry_type(); + let d = if t.is_dir() { + Decision::Dir + } else if t.is_file() || t.is_contiguous() { + let exec = e.header().mode().map(|m| m & 0o100 != 0).unwrap_or(false); + Decision::File { size: e.size(), exec } + } else if t.is_symlink() { + let Some(target) = e.link_name_bytes() else { + return skip("a symlink with no target"); + }; + match link_target(root, link_root, &rel, Path::new(OsStr::from_bytes(&target))) { + Ok(t) => Decision::Link(t), + Err(why) => Decision::Skip(why), + } + } else if t.is_hard_link() { + Decision::Skip("hard links are not imported".into()) + } else if t.is_gnu_sparse() { + Decision::Skip("sparse files are not imported".into()) + } else { + Decision::Skip("only files, directories and symlinks are imported".into()) + }; + Ok((rel, Some(pi), d)) +} + +/// Where a symlink at `rel` may point, as the absolute target to write. +fn link_target(root: &Path, link_root: &Path, rel: &str, target: &Path) -> Result { + let abs = if target.is_absolute() { + let t = lexical(target).ok_or("the link target does not resolve")?; + if let Ok(inner) = t.strip_prefix(root) { + root.join(inner) + } else if let Ok(inner) = t.strip_prefix(link_root) { + root.join(inner) + } else { + return Err("the link points outside the data root".into()); + } + } else { + let parent = Path::new(rel).parent().unwrap_or(Path::new("")); + lexical(&root.join(parent).join(target)).ok_or("the link target does not resolve")? + }; + let inner = abs + .strip_prefix(root) + .map_err(|_| "the link points outside the data root".to_string())?; + if inner.as_os_str().is_empty() { + return Err("the link points at the data root itself".into()); + } + for c in inner.components() { + match c { + Component::Normal(s) if !excluded(&s.to_string_lossy()) => {} + Component::Normal(_) => { + return Err("the link points at something that is not part of the database".into()) + } + _ => return Err("the link target does not resolve".into()), + } + } + Ok(link_root.join(inner)) +} + +/// Insert `rel` and its ancestors down to `part`, so a replace keeps the +/// directories an archive only implies. +fn want(wanted: &mut HashSet, part: &str, rel: &str) { + let mut r = rel; + loop { + if !wanted.insert(r.to_string()) && r != rel { + break; + } + if r.len() <= part.len() { + break; + } + match r.rfind('/') { + Some(i) if i >= part.len() => r = &r[..i], + _ => break, + } + } +} + +#[derive(Default)] +struct Counts { + written: u64, + unchanged: u64, + dirs: u64, + links: u64, + removed: u64, + preserved: u64, + bytes: u64, + applied: u64, +} + +/// The run's corner of the trash bin, made on first use. +struct Trash { + base: PathBuf, + dir: Option, +} + +impl Trash { + fn dir(&mut self) -> io::Result { + if let Some(d) = &self.dir { + return Ok(d.clone()); + } + // ``, as Quanta's own deletes and the extension's name theirs + // in the same bin, so the two sort together in one time order. + let stamp = unix_now(); + let mut d = self.base.join(format!("{stamp}-import")); + let mut n = 1; + while fs::symlink_metadata(&d).is_ok() { + n += 1; + d = self.base.join(format!("{stamp}-import-{n}")); + } + { + let _as = own::of(&d); + fs::create_dir_all(&d)?; + } + self.dir = Some(d.clone()); + Ok(d) + } + + /// A free path for `rel` inside the run's trash, its parents made. + fn slot(&mut self, rel: &str) -> io::Result { + let mut d = self.dir()?.join(rel); + if fs::symlink_metadata(&d).is_ok() { + let base = d.clone(); + let mut n = 1; + while fs::symlink_metadata(&d).is_ok() { + n += 1; + d = PathBuf::from(format!("{}~{n}", base.display())); + } + } + if let Some(parent) = d.parent() { + let _as = own::of(parent); + fs::create_dir_all(parent)?; + } + Ok(d) + } + + /// Move `live` into the trash. A rename when the trash shares the + /// filesystem; a copy and a delete when it does not — the usual case in + /// the container, where the site's `db/` and `static/` are separate mounts. + fn retire(&mut self, live: &Path, rel: &str) -> io::Result<()> { + let d = self.slot(rel)?; + match fs::rename(live, &d) { + Ok(()) => Ok(()), + Err(e) if e.raw_os_error() == Some(libc::EXDEV) => { + { + let _as = own::of(d.parent().unwrap_or(&d)); + copy_tree(live, &d)?; + } + if fs::symlink_metadata(live)?.is_dir() { + fs::remove_dir_all(live) + } else { + fs::remove_file(live) + } + } + Err(e) => Err(e), + } + } + + /// Keep a copy of a file or link that is about to be replaced in place. + /// A hard link when it can be (same filesystem, and the kernel's + /// protected_hardlinks lets us), a copy otherwise. + fn preserve(&mut self, live: &Path, rel: &str) -> io::Result<()> { + let d = self.slot(rel)?; + let _as = own::of(d.parent().unwrap_or(&d)); + if fs::symlink_metadata(live)?.file_type().is_symlink() { + return std::os::unix::fs::symlink(fs::read_link(live)?, &d); + } + if fs::hard_link(live, &d).is_ok() { + return Ok(()); + } + fs::copy(live, &d).map(|_| ()) + } +} + +/// Recursive copy that never follows a link. +fn copy_tree(src: &Path, dst: &Path) -> io::Result<()> { + let md = fs::symlink_metadata(src)?; + let ft = md.file_type(); + if ft.is_symlink() { + std::os::unix::fs::symlink(fs::read_link(src)?, dst) + } else if ft.is_dir() { + fs::create_dir(dst)?; + for e in fs::read_dir(src)? { + let e = e?; + copy_tree(&e.path(), &dst.join(e.file_name()))?; + } + Ok(()) + } else if ft.is_file() { + fs::copy(src, dst).map(|_| ()) + } else { + // A fifo or socket holds nothing worth keeping. + Ok(()) + } +} + +/// Pass two: the writes. +struct Apply<'a> { + root: &'a Path, + trash: Trash, + /// Directories already proven real this run. An archive is depth-first, + /// so most entries share their parent with the previous one. + ok_dirs: HashSet, + seq: u64, + n: Counts, +} + +impl Apply<'_> { + fn retire(&mut self, live: &Path, rel: &str) -> io::Result<()> { + if fs::symlink_metadata(live).map(|m| m.is_dir()).unwrap_or(false) { + // Anything cached at or below it is about to stop existing. + self.ok_dirs.retain(|d| !d.starts_with(live)); + } + self.trash.retire(live, rel) + } + + fn mkdir(&mut self, path: &Path) -> io::Result<()> { + let _as = own::of(path); + fs::DirBuilder::new().mode(0o755).create(path)?; + self.n.dirs += 1; + Ok(()) + } + + /// The part's own directory: reached through links (deployment layout), + /// made if missing. + fn part_dir(&mut self, part: &str) -> io::Result { + let cur = self.root.join(part); + if self.ok_dirs.contains(&cur) { + return Ok(cur); + } + match fs::metadata(&cur) { + Ok(m) if m.is_dir() => {} + Ok(_) => { + self.retire(&cur, part)?; + self.mkdir(&cur)?; + } + Err(e) if e.kind() == io::ErrorKind::NotFound => { + let _as = own::of(&cur); + fs::DirBuilder::new().recursive(true).mode(0o755).create(&cur)?; + self.n.dirs += 1; + } + Err(e) => return Err(e), + } + self.ok_dirs.insert(cur.clone()); + Ok(cur) + } + + /// `part/sub…` as real directories. Below the part nothing is followed: a + /// link where the archive has a directory is the archive's call to make, + /// and writing through it would write into whatever it points at. + fn dirs(&mut self, part: &str, sub: &[&str]) -> io::Result { + let mut cur = self.part_dir(part)?; + let mut rel = part.to_string(); + for c in sub { + cur.push(c); + rel.push('/'); + rel.push_str(c); + if self.ok_dirs.contains(&cur) { + continue; + } + match fs::symlink_metadata(&cur) { + Ok(m) if m.is_dir() => {} + Ok(_) => { + self.retire(&cur, &rel)?; + self.mkdir(&cur)?; + } + Err(e) if e.kind() == io::ErrorKind::NotFound => self.mkdir(&cur)?, + Err(e) => return Err(e), + } + self.ok_dirs.insert(cur.clone()); + } + Ok(cur) + } + + /// The directory an entry's last component goes in. + fn parent_of(&mut self, part: &str, comps: &[&str]) -> io::Result { + let k = part.split('/').count(); + if comps.len() > k { + return self.dirs(part, &comps[k..comps.len() - 1]); + } + // The entry IS the part (a part that is a file): its parent is + // deployment layout, reached through links and made if missing. + let abs = self.root.join(part); + let parent = abs.parent().unwrap_or(self.root).to_path_buf(); + if !parent.is_dir() { + let _as = own::of(&parent); + fs::DirBuilder::new().recursive(true).mode(0o755).create(&parent)?; + } + Ok(parent) + } + + fn tmp(&mut self, dir: &Path) -> PathBuf { + self.seq += 1; + dir.join(format!(".qdb-tmp-{}-{}", std::process::id(), self.seq)) + } + + fn file(&mut self, dir: &Path, name: &str, rel: &str, data: &mut dyn Read, size: u64, exec: bool) -> io::Result<()> { + let live = dir.join(name); + let md = match fs::symlink_metadata(&live) { + Ok(m) => Some(m), + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + Err(e) => return Err(e), + }; + + let mut buf: Option> = None; + if size <= COMPARE_MAX { + let mut v = Vec::with_capacity(size as usize); + (&mut *data).take(size).read_to_end(&mut v)?; + if v.len() as u64 != size { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, format!("{rel}: entry is short"))); + } + if let Some(m) = &md { + if m.is_file() && m.len() == size && fs::read(&live)? == v { + self.n.unchanged += 1; + return Ok(()); + } + } + buf = Some(v); + } + + match &md { + Some(m) if m.is_dir() => self.retire(&live, rel)?, + Some(m) if m.is_file() || m.file_type().is_symlink() => { + self.trash.preserve(&live, rel)?; + self.n.preserved += 1; + } + Some(_) => self.retire(&live, rel)?, + None => {} + } + + let tmp = self.tmp(dir); + let res = (|| -> io::Result<()> { + let mut f = { + let _as = own::of(dir); + OpenOptions::new() + .write(true) + .create_new(true) + .mode(if exec { 0o755 } else { 0o644 }) + .custom_flags(libc::O_NOFOLLOW) + .open(&tmp)? + }; + let n = match &buf { + Some(v) => { + f.write_all(v)?; + v.len() as u64 + } + None => io::copy(&mut (&mut *data).take(size), &mut f)?, + }; + if n != size { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, format!("{rel}: entry is short"))); + } + fs::rename(&tmp, &live) + })(); + if res.is_err() { + let _ = fs::remove_file(&tmp); + } + res?; + self.n.written += 1; + self.n.bytes += size; + Ok(()) + } + + fn link(&mut self, dir: &Path, name: &str, rel: &str, target: &Path) -> io::Result<()> { + let live = dir.join(name); + match fs::symlink_metadata(&live) { + Ok(m) if m.file_type().is_symlink() => { + if fs::read_link(&live)? == target { + self.n.unchanged += 1; + return Ok(()); + } + self.trash.preserve(&live, rel)?; + self.n.preserved += 1; + } + Ok(m) if m.is_dir() => self.retire(&live, rel)?, + Ok(_) => { + self.trash.preserve(&live, rel)?; + self.n.preserved += 1; + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + let tmp = self.tmp(dir); + { + let _as = own::of(dir); + std::os::unix::fs::symlink(target, &tmp)?; + } + if let Err(e) = fs::rename(&tmp, &live) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + self.n.links += 1; + Ok(()) + } + + /// Replace mode: retire whatever under `part` the archive did not have. + fn prune(&mut self, part: &str, wanted: &HashSet) -> io::Result<()> { + let dir = self.root.join(part); + match fs::metadata(&dir) { + Ok(m) if m.is_dir() => self.prune_dir(&dir, part, wanted), + _ => Ok(()), + } + } + + fn prune_dir(&mut self, dir: &Path, rel: &str, wanted: &HashSet) -> io::Result<()> { + let mut names: Vec = Vec::new(); + for e in fs::read_dir(dir)? { + // A name that is not UTF-8 can never have been in an archive, and + // a replace has no business guessing about it: left alone. + if let Ok(n) = e?.file_name().into_string() { + if !excluded(&n) { + names.push(n); + } + } + } + names.sort(); + for name in names { + let abs = dir.join(&name); + let r = format!("{rel}/{name}"); + if !wanted.contains(&r) { + self.retire(&abs, &r)?; + self.n.removed += 1; + continue; + } + if fs::symlink_metadata(&abs)?.is_dir() { + self.prune_dir(&abs, &r, wanted)?; + } + } + Ok(()) + } +} + +/// What pass one learned. +struct Scan { + total: u64, + bytes: u64, + present: HashSet, + wanted: HashSet, + skipped: Vec, + skipped_total: u64, + manifest: Option, +} + +/// Run an import: validate the spooled archive end to end, then apply it. +/// +/// `emit` receives progress objects (`{"phase": "scan"|"apply"|"prune", …}`) +/// at most every 250 ms. The return value is the result object, or an error +/// object carrying whatever was already done — once pass two has started, +/// what it wrote stays written, and the caller has to be told so. +pub fn run_import(p: &Policy, spec: &ImportSpec, spool: &Spool, emit: &mut dyn FnMut(Value)) -> Result { + let started = Instant::now(); + let fail = |msg: String| json!({ "error": "import failed", "detail": msg }); + let Some(root) = p.root.as_deref() else { + return Err(fail("no data root configured".into())); + }; + let link_root = p.link_spelling().unwrap_or(root); + let Some(trash_base) = p.trash.clone() else { + return Err(fail("no trash bin configured".into())); + }; + + // ---- pass one: read everything, write nothing ------------------------- + let scan = scan(p, spec, spool, root, link_root, emit).map_err(fail)?; + let missing: Vec<&str> = spec + .parts + .iter() + .enumerate() + .filter(|(i, _)| !scan.present.contains(i)) + .map(|(_, s)| s.as_str()) + .collect(); + if !missing.is_empty() { + // Refused rather than treated as empty: a replace of a part the + // archive does not have would empty it. + return Err(fail(format!( + "not in this archive: {}. Nothing was changed.", + missing.join(", ") + ))); + } + // An export records the parts it was taken at. Replacing a broader part + // with it would remove everything the export never set out to carry: an + // archive of `db/_users` that replaced `db` would empty the rest of `db`. + // A merge removes nothing, so it may apply the archive at any level. + if spec.mode == Mode::Replace { + let taken: Option> = scan + .manifest + .as_ref() + .and_then(|m| m.get("parts")) + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).collect()); + if let Some(taken) = taken { + let broader: Vec<&str> = spec + .parts + .iter() + .map(String::as_str) + .filter(|part| !taken.iter().any(|t| covers(t, part))) + .collect(); + if !broader.is_empty() { + return Err(fail(format!( + "this archive was exported as {}, so replacing {} with it would remove what it never held. \ + Replace those parts instead, or merge. Nothing was changed.", + taken.join(", "), + broader.join(", ") + ))); + } + } + } + + // ---- pass two: apply -------------------------------------------------- + let mut ap = Apply { + root, + trash: Trash { base: trash_base, dir: None }, + ok_dirs: HashSet::new(), + seq: 0, + n: Counts::default(), + }; + let mut last = Instant::now(); + let res = (|| -> Result<(), String> { + let counter = Rc::new(Cell::new(0u64)); + let mut ar = open_archive(&spool.path, p.max_bytes, counter).map_err(|e| e.to_string())?; + let entries = ar.entries().map_err(|e| e.to_string())?; + for e in entries { + let mut e = e.map_err(|e| format!("the archive is damaged: {e}"))?; + let (rel, pi, d) = classify(&e, &spec.parts, root, link_root)?; + let Some(pi) = pi else { continue }; + let part = spec.parts[pi].as_str(); + let comps: Vec<&str> = rel.split('/').collect(); + let name = comps[comps.len() - 1]; + let step = match d { + Decision::Dir => { + let k = part.split('/').count(); + ap.dirs(part, &comps[k..]).map(|_| ()) + } + Decision::File { size, exec } => ap + .parent_of(part, &comps) + .and_then(|dir| ap.file(&dir, name, &rel, &mut e, size, exec)), + Decision::Link(target) => { + ap.parent_of(part, &comps).and_then(|dir| ap.link(&dir, name, &rel, &target)) + } + Decision::Ignore | Decision::Manifest | Decision::Skip(_) => continue, + }; + step.map_err(|err| format!("{rel}: {err}"))?; + ap.n.applied += 1; + if last.elapsed() >= PROGRESS_EVERY { + last = Instant::now(); + emit(json!({ "phase": "apply", "done": ap.n.applied, "total": scan.total })); + } + } + Ok(()) + })(); + + let res = res.and_then(|()| { + if spec.mode == Mode::Replace { + emit(json!({ "phase": "prune", "done": 0, "total": spec.parts.len() })); + for part in &spec.parts { + ap.prune(part, &scan.wanted).map_err(|e| format!("{part}: {e}"))?; + } + } + Ok(()) + }); + + // Once, at the end, rather than an fsync per file: an import of a whole + // tree would otherwise spend its time waiting on the disk. + if let Ok(f) = File::open(root) { + unsafe { libc::syncfs(f.as_raw_fd()) }; + } + + let mut out = json!({ + "mode": spec.mode.label(), + "parts": spec.parts, + "entries": scan.total, + "applied": ap.n.applied, + "written": ap.n.written, + "unchanged": ap.n.unchanged, + "dirs": ap.n.dirs, + "links": ap.n.links, + "removed": ap.n.removed, + "preserved": ap.n.preserved, + "bytes": ap.n.bytes, + "skipped": scan.skipped, + "skipped_total": scan.skipped_total, + "trash": ap.trash.dir.as_ref().map(|d| d.display().to_string()), + "manifest": scan.manifest.as_ref().map(|m| json!({ + "created": m.get("created"), + "parts": m.get("parts"), + })), + "ms": started.elapsed().as_millis() as u64, + }); + match res { + Ok(()) => Ok(out), + Err(msg) => { + if let Value::Object(m) = &mut out { + m.insert("error".into(), json!("import stopped")); + m.insert( + "detail".into(), + json!(format!( + "{msg}. What was applied before this point stays; anything it displaced is in the trash bin." + )), + ); + } + Err(out) + } + } +} + +fn scan( + p: &Policy, + spec: &ImportSpec, + spool: &Spool, + root: &Path, + link_root: &Path, + emit: &mut dyn FnMut(Value), +) -> Result { + let counter = Rc::new(Cell::new(0u64)); + let mut ar = open_archive(&spool.path, p.max_bytes, counter.clone()).map_err(|e| e.to_string())?; + let mut s = Scan { + total: 0, + bytes: 0, + present: HashSet::new(), + wanted: HashSet::new(), + skipped: Vec::new(), + skipped_total: 0, + manifest: None, + }; + let mut seen = 0u64; + let mut last = Instant::now(); + { + let entries = ar.entries().map_err(|e| format!("not a tar archive: {e}"))?; + for e in entries { + let mut e = e.map_err(|e| damaged(&e))?; + seen += 1; + if seen > MAX_ENTRIES { + return Err(format!("the archive holds more than {MAX_ENTRIES} entries")); + } + let (rel, pi, d) = classify(&e, &spec.parts, root, link_root)?; + match (pi, d) { + (_, Decision::Manifest) => { + if e.size() <= MANIFEST_MAX { + let mut buf = Vec::new(); + (&mut e).take(MANIFEST_MAX).read_to_end(&mut buf).map_err(|e| damaged(&e))?; + s.manifest = serde_json::from_slice::(&buf) + .ok() + .filter(|m| m.get("format").and_then(Value::as_str) == Some(FORMAT)); + } + } + (Some(pi), Decision::Skip(why)) => { + s.present.insert(pi); + s.skipped_total += 1; + if s.skipped.len() < SKIPPED_SHOWN { + s.skipped.push(json!({ "path": rel, "reason": why })); + } + // Kept by a replace: the archive has something there, + // just nothing this import will write. + if spec.mode == Mode::Replace { + want(&mut s.wanted, &spec.parts[pi], &rel); + } + } + (Some(pi), d @ (Decision::Dir | Decision::File { .. } | Decision::Link(_))) => { + s.present.insert(pi); + s.total += 1; + if let Decision::File { size, .. } = d { + s.bytes += size; + } + if spec.mode == Mode::Replace { + want(&mut s.wanted, &spec.parts[pi], &rel); + } + } + _ => {} + } + if last.elapsed() >= PROGRESS_EVERY { + last = Instant::now(); + emit(json!({ "phase": "scan", "done": counter.get(), "total": spool.len })); + } + } + } + // The tar end marker can come before the end of the gzip stream, and the + // CRC is checked only at the end of it: read to the end, or a corrupt + // trailer would go unnoticed. + io::copy(&mut ar.into_inner(), &mut io::sink()).map_err(|e| damaged(&e))?; + emit(json!({ "phase": "scan", "done": spool.len, "total": spool.len })); + Ok(s) +} + +fn damaged(e: &io::Error) -> String { + // The limit is the one read error that is not damage. + if e.kind() == io::ErrorKind::InvalidData && e.to_string().contains("import limit") { + return e.to_string(); + } + format!("the archive is damaged or not a tar/tar.gz file: {e}") +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::symlink; + + /// A throwaway directory, removed on drop. + struct Tmp(PathBuf); + + impl Tmp { + fn new(tag: &str) -> Tmp { + let nanos = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let d = std::env::temp_dir().join(format!("qdb_xfer_{tag}_{}_{nanos}", std::process::id())); + fs::create_dir_all(&d).unwrap(); + Tmp(d.canonicalize().unwrap()) + } + } + + impl Drop for Tmp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn put(path: &Path, body: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, body).unwrap(); + } + + fn policy(root: &Path, trash: &Path) -> Policy { + Policy { + root: Some(root.to_path_buf()), + link_root: Some(root.to_path_buf()), + import: true, + import_off: None, + max_bytes: 64 << 20, + trash: Some(trash.to_path_buf()), + spool_dir: trash.parent().unwrap().to_path_buf(), + } + } + + /// A small Quanta-shaped site: users, pages with a container link, a + /// payload dir, and the things that must never travel. + fn site(root: &Path) { + put(&root.join("db/_users/alice/data.json"), r#"{"name":"alice"}"#); + put(&root.join("db/_users/bob/data.json"), r#"{"name":"bob"}"#); + put(&root.join("db/pages/home/data.json"), r#"{"title":"Home"}"#); + put(&root.join("db/pages/home/data_it.json"), r#"{"title":"Casa"}"#); + put(&root.join("db/items/item-a/data.json"), r#"{"title":"A"}"#); + fs::create_dir_all(root.join("db/cats")).unwrap(); + // Quanta's container link: absolute, into the root. + symlink(root.join("db/items/item-a"), root.join("db/cats/item-a")).unwrap(); + put(&root.join("db/pages/assets/logo.png"), "PNG"); + put(&root.join("db/pages/home/.secret"), "nope"); + put(&root.join("_modules/evil/evil.php"), ""); + } + + fn export(p: &Policy, parts: &[&str]) -> Vec { + let parts: Vec = parts.iter().map(|s| s.to_string()).collect(); + let plan = plan_export(p, &parts).unwrap_or_else(|e| panic!("{e:?}")); + let mut out = Vec::new(); + write_export(&plan, &mut out).unwrap(); + out + } + + fn import(p: &Policy, bytes: &[u8], parts: &[&str], mode: &str) -> Result { + let parts: Vec = parts.iter().map(|s| s.to_string()).collect(); + let spec = plan_import(p, &parts, mode).unwrap_or_else(|e| panic!("{e:?}")); + let sp = spool(&mut &bytes[..], bytes.len() as u64, &p.spool_dir).unwrap(); + run_import(p, &spec, &sp, &mut |_| {}) + } + + fn names(bytes: &[u8]) -> Vec { + let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(bytes)); + ar.entries() + .unwrap() + .map(|e| e.unwrap().path().unwrap().to_string_lossy().into_owned()) + .collect() + } + + #[test] + fn parts_are_plain_relative_paths_of_the_database() { + assert_eq!(parse_part("/db/_users/").unwrap(), "db/_users"); + for bad in ["", "/", "..", "db/../etc", "db/./x", ".env", "db/.git", "_modules", "db/_modules", "a//b"] { + assert!(parse_part(bad).is_err(), "{bad:?} must be refused"); + } + let v = normalize_parts(&["db/_users".into(), "db".into(), "db2".into(), "db".into()]).unwrap(); + assert_eq!(v, vec!["db".to_string(), "db2".to_string()], "db covers db/_users but not db2"); + } + + #[test] + fn the_listing_offers_two_levels_and_hides_what_is_not_the_database() { + let t = Tmp::new("list"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let v = parts_json(&p, None); + assert_eq!(v["available"], true); + let groups: Vec<&str> = v["groups"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect(); + assert_eq!(groups, vec!["_tpl", "db"], "no _modules, no dot entries, no top-level files"); + let db = v["groups"].as_array().unwrap().iter().find(|g| g["name"] == "db").unwrap(); + let members: Vec<&str> = db["members"].as_array().unwrap().iter().map(|m| m["name"].as_str().unwrap()).collect(); + assert_eq!(members, vec!["_users", "cats", "items", "pages"]); + assert_eq!(db["nodes"], Value::Null, "no segment, no weights -- not zeros"); + assert_eq!(v["import"]["enabled"], true); + } + + #[test] + fn an_export_is_a_plain_tar_gz_led_by_its_manifest() { + let t = Tmp::new("export"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let bytes = export(&p, &["db/_users", "db/pages", "db/cats", "_tpl"]); + let n = names(&bytes); + assert_eq!(n[0], MANIFEST, "the manifest comes first so a page can stop reading there"); + assert!(n.contains(&"db/_users/alice/data.json".to_string())); + assert!(n.contains(&"db/pages/assets/logo.png".to_string()), "payload files travel"); + assert!(!n.iter().any(|x| x.contains(".secret")), "dot-prefixed names never travel"); + assert!(!n.iter().any(|x| x.contains("items")), "an unselected part stays out"); + + let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(&bytes[..])); + let mut manifest = None; + for e in ar.entries().unwrap() { + let mut e = e.unwrap(); + let path = e.path().unwrap().to_string_lossy().into_owned(); + if path == MANIFEST { + let mut s = String::new(); + e.read_to_string(&mut s).unwrap(); + manifest = Some(serde_json::from_str::(&s).unwrap()); + } + if path == "db/cats/item-a" { + assert!(e.header().entry_type().is_symlink()); + assert_eq!( + e.link_name().unwrap().unwrap().to_string_lossy(), + "../items/item-a", + "an in-root link is made relative, so the archive carries no deployment path" + ); + } + } + let m = manifest.unwrap(); + assert_eq!(m["format"], FORMAT); + let group = |name: &str| m["groups"].as_array().unwrap().iter().find(|g| g["name"] == name).unwrap().clone(); + let db = group("db"); + let users = db["members"].as_array().unwrap().iter().find(|x| x["name"] == "_users").unwrap(); + assert_eq!(users["files"], 2); + let tpl = group("_tpl"); + assert_eq!(tpl["files"], 1, "a file directly in a group counts toward it"); + assert_eq!(tpl["members"], json!([]), "but is not a member: members are directories, as in the listing"); + } + + #[test] + fn a_round_trip_lands_in_another_root_with_its_links_rebased() { + let src = Tmp::new("rt_src"); + let dst = Tmp::new("rt_dst"); + let sroot = src.0.join("site"); + let droot = dst.0.join("site"); + site(&sroot); + fs::create_dir_all(&droot).unwrap(); + let bytes = export(&policy(&sroot, &src.0.join("trash")), &["db"]); + + let p = policy(&droot, &dst.0.join("trash")); + let r = import(&p, &bytes, &["db"], "merge").unwrap(); + assert_eq!(fs::read_to_string(droot.join("db/pages/home/data_it.json")).unwrap(), r#"{"title":"Casa"}"#); + assert_eq!(fs::read_to_string(droot.join("db/pages/assets/logo.png")).unwrap(), "PNG"); + assert_eq!( + fs::read_link(droot.join("db/cats/item-a")).unwrap(), + droot.join("db/items/item-a"), + "the link is absolute again, under the importing root" + ); + assert!(!droot.join("_modules").exists()); + assert!(!droot.join("db/pages/home/.secret").exists()); + assert_eq!(r["removed"], 0); + assert_eq!(r["trash"], Value::Null, "a fresh import displaces nothing"); + + // The same archive again changes nothing at all. + let again = import(&p, &bytes, &["db"], "merge").unwrap(); + assert_eq!(again["written"], 0); + assert_eq!(again["links"], 0); + assert!(again["unchanged"].as_u64().unwrap() >= 6); + assert_eq!(again["trash"], Value::Null); + } + + #[test] + fn a_merge_overwrites_into_the_trash_and_keeps_the_rest() { + let t = Tmp::new("merge"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let bytes = export(&p, &["db/_users"]); + + put(&root.join("db/_users/alice/data.json"), r#"{"name":"alice","admin":true}"#); + put(&root.join("db/_users/carol/data.json"), r#"{"name":"carol"}"#); + + let r = import(&p, &bytes, &["db/_users"], "merge").unwrap(); + assert_eq!(fs::read_to_string(root.join("db/_users/alice/data.json")).unwrap(), r#"{"name":"alice"}"#); + assert!(root.join("db/_users/carol/data.json").exists(), "a merge removes nothing"); + assert_eq!(r["written"], 1); + assert_eq!(r["preserved"], 1); + let trash = PathBuf::from(r["trash"].as_str().unwrap()); + assert!(trash.starts_with(t.0.join("trash"))); + assert_eq!( + fs::read_to_string(trash.join("db/_users/alice/data.json")).unwrap(), + r#"{"name":"alice","admin":true}"#, + "what was overwritten is kept" + ); + } + + #[test] + fn a_replace_removes_what_the_archive_lacks_into_the_trash() { + let t = Tmp::new("replace"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let bytes = export(&p, &["db/_users"]); + + put(&root.join("db/_users/carol/data.json"), r#"{"name":"carol"}"#); + put(&root.join("db/_users/.keep"), ""); + + let r = import(&p, &bytes, &["db/_users"], "replace").unwrap(); + assert!(!root.join("db/_users/carol").exists()); + assert!(root.join("db/_users/alice/data.json").exists()); + assert!(root.join("db/_users/.keep").exists(), "a replace leaves what is not the database alone"); + assert!(root.join("db/pages/home/data.json").exists(), "and every other part"); + assert_eq!(r["removed"], 1); + let trash = PathBuf::from(r["trash"].as_str().unwrap()); + assert!(trash.join("db/_users/carol/data.json").exists()); + } + + #[test] + fn a_link_below_a_part_is_replaced_not_written_through() { + let t = Tmp::new("nofollow"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + // An archive that has db/cats/item-a as a real directory. + let mut tb = tar::Builder::new(Vec::new()); + let body = br#"{"title":"not A"}"#; + let mut h = gnu_header(tar::EntryType::Regular, 0o644, 0, body.len() as u64); + tb.append_data(&mut h, "db/cats/item-a/data.json", &body[..]).unwrap(); + let bytes = tb.into_inner().unwrap(); + + import(&p, &bytes, &["db/cats"], "merge").unwrap(); + assert_eq!( + fs::read_to_string(root.join("db/items/item-a/data.json")).unwrap(), + r#"{"title":"A"}"#, + "the link's target is untouched" + ); + assert!(fs::symlink_metadata(root.join("db/cats/item-a")).unwrap().is_dir()); + } + + fn raw_tar(entries: &[(&str, tar::EntryType, &str, &[u8])]) -> Vec { + // Headers built by hand, because the builder refuses the hostile + // paths these tests need. + let mut out = Vec::new(); + for (path, kind, link, body) in entries { + let mut h = tar::Header::new_old(); + { + let raw = h.as_old_mut(); + raw.name[..path.len()].copy_from_slice(path.as_bytes()); + raw.linkname[..link.len()].copy_from_slice(link.as_bytes()); + } + h.set_entry_type(*kind); + h.set_mode(0o644); + h.set_size(body.len() as u64); + h.set_cksum(); + out.extend_from_slice(h.as_bytes()); + out.extend_from_slice(body); + out.resize(out.len().div_ceil(512) * 512, 0); + } + out.resize(out.len() + 1024, 0); + out + } + + #[test] + fn a_hostile_path_refuses_the_whole_archive() { + let t = Tmp::new("hostile"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + for bad in ["db/_users/../../../etc/x", "/db/_users/x"] { + let bytes = raw_tar(&[ + ("db/_users/zed/data.json", tar::EntryType::Regular, "", b"{}"), + (bad, tar::EntryType::Regular, "", b"pwned"), + ]); + let e = import(&p, &bytes, &["db/_users"], "merge").unwrap_err(); + assert!(e["detail"].as_str().unwrap().contains("refusing"), "{e}"); + assert!(!root.join("db/_users/zed").exists(), "validation comes before any write"); + } + } + + #[test] + fn links_out_of_the_root_and_planted_names_are_skipped() { + let t = Tmp::new("skips"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let bytes = raw_tar(&[ + ("db/_users/zed/data.json", tar::EntryType::Regular, "", b"{}"), + ("db/_users/zed/passwd", tar::EntryType::Symlink, "/etc/passwd", b""), + ("db/_users/zed/up", tar::EntryType::Symlink, "../../../../..", b""), + ("db/_users/zed/env", tar::EntryType::Symlink, "../../../.env", b""), + ("db/_users/zed/.user.ini", tar::EntryType::Regular, "", b"auto_prepend_file=x"), + ("db/_users/zed/hard", tar::EntryType::Link, "db/_users/zed/data.json", b""), + ("db/_users/zed/peer", tar::EntryType::Symlink, "../alice", b""), + ]); + let r = import(&p, &bytes, &["db/_users"], "merge").unwrap(); + assert!(root.join("db/_users/zed/data.json").exists()); + for gone in ["passwd", "up", "env", ".user.ini", "hard"] { + assert!(fs::symlink_metadata(root.join("db/_users/zed").join(gone)).is_err(), "{gone}"); + } + assert_eq!(r["skipped_total"], 5); + assert_eq!( + fs::read_link(root.join("db/_users/zed/peer")).unwrap(), + root.join("db/_users/alice"), + "an in-root relative link is written absolute" + ); + } + + #[test] + fn a_damaged_archive_changes_nothing() { + let t = Tmp::new("damaged"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let mut bytes = export(&p, &["db/_users"]); + put(&root.join("db/_users/alice/data.json"), "changed"); + let cut = bytes.len() - 12; + bytes.truncate(cut); + let e = import(&p, &bytes, &["db/_users"], "merge").unwrap_err(); + assert!(e["detail"].as_str().unwrap().contains("damaged"), "{e}"); + assert_eq!(fs::read_to_string(root.join("db/_users/alice/data.json")).unwrap(), "changed"); + } + + #[test] + fn a_selected_part_missing_from_the_archive_is_refused() { + let t = Tmp::new("missing"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let bytes = export(&p, &["db/_users"]); + let e = import(&p, &bytes, &["db/pages"], "replace").unwrap_err(); + assert!(e["detail"].as_str().unwrap().contains("not in this archive"), "{e}"); + assert!(root.join("db/pages/home/data.json").exists(), "a replace of an absent part empties nothing"); + } + + #[test] + fn a_replace_reaches_no_wider_than_the_export_was_taken() { + let t = Tmp::new("wider"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let bytes = export(&p, &["db/_users"]); + // `db` is in the archive (as the parent of `db/_users`), so it passes + // the presence check; it is the manifest that says it was never whole. + let e = import(&p, &bytes, &["db"], "replace").unwrap_err(); + assert!(e["detail"].as_str().unwrap().contains("exported as db/_users"), "{e}"); + assert!(root.join("db/pages/home/data.json").exists(), "the rest of db is untouched"); + // At the level it was taken, or below it, a replace goes through, + // and a merge may go wider since it removes nothing. + import(&p, &bytes, &["db/_users"], "replace").unwrap(); + import(&p, &bytes, &["db/_users/alice"], "replace").unwrap(); + import(&p, &bytes, &["db"], "merge").unwrap(); + assert!(root.join("db/pages/home/data.json").exists()); + } + + #[test] + fn the_size_limit_counts_what_the_archive_expands_to() { + let t = Tmp::new("limit"); + let root = t.0.join("site"); + site(&root); + let mut p = policy(&root, &t.0.join("trash")); + put(&root.join("db/_users/big/data.json"), &"x".repeat(3 << 20)); + let bytes = export(&p, &["db/_users"]); + assert!(bytes.len() < 1 << 20, "it compresses well below the limit"); + p.max_bytes = 1 << 20; + let e = import(&p, &bytes, &["db/_users"], "merge").unwrap_err(); + assert!(e["detail"].as_str().unwrap().contains("import limit"), "{e}"); + } + + #[test] + fn import_needs_the_policy_to_allow_it() { + let t = Tmp::new("policy"); + let root = t.0.join("site"); + site(&root); + let mut p = policy(&root, &t.0.join("trash")); + p.import = false; + p.import_off = Some("off for the test".into()); + let (status, why) = plan_import(&p, &["db".into()], "merge").err().unwrap(); + assert_eq!(status, 403); + assert_eq!(why, "Import is off. off for the test", "the reason, said after what it is the reason for"); + } + + #[test] + fn a_link_member_is_not_a_part() { + let t = Tmp::new("linkpart"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let err = plan_export(&p, &["db/cats/item-a".into()]).err().unwrap(); + assert_eq!(err.0, 400); + // A first-level link is deployment layout and is followed. + symlink(root.join("db"), root.join("data")).unwrap(); + assert!(plan_export(&p, &["data/_users".into()]).is_ok()); + } + + #[test] + fn export_names_are_dated_in_utc() { + assert_eq!(export_filename(0), "qdb-export-19700101-000000.tar.gz"); + assert_eq!(export_filename(1_796_130_295), "qdb-export-20261201-130455.tar.gz"); + } + + #[test] + fn relative_links_climb_only_as_far_as_they_need() { + assert_eq!(relative_path(Path::new("db/cats"), Path::new("db/items/a")), PathBuf::from("../items/a")); + assert_eq!(relative_path(Path::new("db"), Path::new("db/x")), PathBuf::from("x")); + assert_eq!(lexical(Path::new("/a/b/../c/./d")), Some(PathBuf::from("/a/c/d"))); + assert_eq!(lexical(Path::new("/..")), None); + } +} From e65f873e25c0ac48d1f5bc3775d226e950c9a6a1 Mon Sep 17 00:00:00 2001 From: daylioti Date: Tue, 1 Dec 2026 14:30:09 +0200 Subject: [PATCH 2/2] Require the token for export and keep imports off symlinked parts Export is now off unless QUANTA_DB_DASHBOARD_TOKEN is set, as import already was. A dashboard without a token is reachable from any web page open in the same browser through DNS rebinding, and one archive is the whole site. The route checks the token itself, /api/parts reports the export state, and the page shows why export is off. An archive entry that would turn a selected part into a symlink is skipped, so writes and a replace's pruning cannot follow it outside the part. Parts are checked for symlinks at every level below the first, at planning, again before the first write, and when each part is written. --- Dockerfile | 4 +- docker/qdbstat-dashboard.sh | 8 ++- docker/supervisord.conf | 3 +- qdb/README.md | 14 ++-- qdb/docs/usage.md | 2 +- qdb/src/bin/qdbstat.rs | 14 ++++ qdb/src/dashboard.rs | 44 ++++++++++-- qdb/src/dashboard/app.js | 15 +++- qdb/src/transfer.rs | 139 ++++++++++++++++++++++++++++++++---- 9 files changed, 212 insertions(+), 31 deletions(-) diff --git a/Dockerfile b/Dockerfile index a92a44d6f..57be21075 100644 --- a/Dockerfile +++ b/Dockerfile @@ -371,8 +371,8 @@ COPY --link --from=qdb-builder /out/quanta_db.so /usr/local/lib/php/extensions/q # by supervisord when QUANTA_DB_DASHBOARD_LISTEN is set # (docker/qdbstat-dashboard.sh). That one carries node paths and document # content rather than counters, so it binds loopback unless told otherwise and -# takes an optional QUANTA_DB_DASHBOARD_TOKEN. It exports parts of the site, and -# imports them only with QUANTA_DB_DASHBOARD_IMPORT=on plus the token. Neither +# takes an optional QUANTA_DB_DASHBOARD_TOKEN. With the token it exports parts of +# the site, and imports them only with QUANTA_DB_DASHBOARD_IMPORT=on as well. Neither # port is EXPOSEd: this image is a base for deployments that never asked to # open one. # diff --git a/docker/qdbstat-dashboard.sh b/docker/qdbstat-dashboard.sh index c70aa655b..63cc209d1 100755 --- a/docker/qdbstat-dashboard.sh +++ b/docker/qdbstat-dashboard.sh @@ -4,8 +4,8 @@ # `qdbstat --dashboard` serves a browser for the index: every node, its place in # the tree, its links, and the document files themselves, rendered out of the # shared-memory segment. It answers "what is in the DB" where /metrics answers -# "is the DB healthy". It also exports parts of the site as a .tar.gz and, only -# when switched on, imports one back (see below). +# "is the DB healthy". With a token it also exports parts of the site as a +# .tar.gz and, only when switched on, imports one back (see below). # # It runs INSIDE this container for the same reason the exporter does: the # metrics arena is under /tmp/quanta_db, on the container's own filesystem, so @@ -25,7 +25,9 @@ # * QUANTA_DB_DASHBOARD_TOKEN, if set, is required for everything the page # loads from the site (the page itself loads without it and asks for it). # Set it for anything wider than loopback -- an address is not access -# control. +# control. Export is off without it: one archive is the whole site, and a +# loopback port is reachable from any web page in the browser through DNS +# rebinding. # # QUANTA_DB_DASHBOARD_BASE_PATH is read by qdbstat itself (not here) and names # the URL prefix the dashboard is reached at, for an ingress that routes a diff --git a/docker/supervisord.conf b/docker/supervisord.conf index 75fdff8e2..99f9637c7 100644 --- a/docker/supervisord.conf +++ b/docker/supervisord.conf @@ -87,7 +87,8 @@ stdout_logfile_maxbytes = 0 stderr_logfile_maxbytes = 0 ; The web dashboard: a browser for what the index actually holds, plus export -; and (only with QUANTA_DB_DASHBOARD_IMPORT=on and a token) import of the site. +; (only with a token) and import (only with QUANTA_DB_DASHBOARD_IMPORT=on and a +; token) of the site. ; Opt-in on QUANTA_DB_DASHBOARD_LISTEN, same EXITED-when-unset shape as the ; exporter above, and last for the same reason -- it inspects the other ; programs and must never be what keeps them from starting. diff --git a/qdb/README.md b/qdb/README.md index 1835d33df..f9f93553d 100644 --- a/qdb/README.md +++ b/qdb/README.md @@ -150,7 +150,7 @@ serving changes when it is on. | | | |---|---| | `QUANTA_DB_DASHBOARD_LISTEN` | `host:port` to serve on. Unset (or `off`/`0`/`false`) means the dashboard does not start | -| `QUANTA_DB_DASHBOARD_TOKEN` | Optional shared secret. When set, every `/api/*` route requires `Authorization: Bearer ` or `?token=`. The page itself loads without it and asks for the token when the URL does not carry one | +| `QUANTA_DB_DASHBOARD_TOKEN` | Optional shared secret. When set, every `/api/*` route requires `Authorization: Bearer ` or `?token=`. The page itself loads without it and asks for the token when the URL does not carry one. Required for export and import | | `QUANTA_DB_DASHBOARD_BASE_PATH` | URL prefix it is served under, e.g. `/qdb`. Empty (default) means the root | | `QUANTA_DB_DASHBOARD_IMPORT` | `on` (or `--allow-import`) turns on import, the one route that writes. Needs the token too | | `QUANTA_DB_DASHBOARD_IMPORT_MAX_MB` | Largest archive an import accepts, counted as what it expands to. Default `2048` | @@ -204,8 +204,8 @@ with a select-all: the root's directories (`db`, `_tpl`, …) and, under each, its subdirectories (`db/_users`, `db/_translations`, …). A whole group also carries the files directly inside it. -- **Export** reads the files on disk, not the segment: an archive is a backup, - so payload files and links travel too. Dot-prefixed names and `_modules` +- **Export** needs a token. It reads the files on disk, not the segment: an + archive is a backup, so payload files and links travel too. Dot-prefixed names and `_modules` never do. A container link that points inside the root is written relative and made absolute again under the importing site's root, so an archive holds no deployment path. The archive leads with a manifest (`.qdb-export.json`) @@ -244,13 +244,17 @@ in every deployment, naming no setting) and `/healthz` are served without it; the page asks for the token, checks it against the server, and keeps it for the tab, or for the browser if asked. It then sends it as an `Authorization` header, so it stays out of URLs and access logs, except on an export download, -which is a plain link. Without import the dashboard is read-only by construction (a +which is a plain link. Export and import are never served without a token: a +dashboard on loopback is still reachable from any web page open in the same +browser, through DNS rebinding, and one archive is the whole site, users +included. Without import the dashboard is read-only by construction (a `PROT_READ` mapping, no mutating route, and a node name from the URL is only ever a hash key, never a path), so the risk it carries is disclosure, not damage. Import changes that, hence its two switches: the opt-in, and the token, which the write route checks again itself. A part name from the URL does reach the filesystem there, so it is checked component by component (no `..`, no -dot-names, no `_modules`), and the upload has to declare a gzip or tar content +dot-names, no `_modules`, no symlink below the first level, checked again +before the first write), and the upload has to declare a gzip or tar content type, which no cross-site form can send. ## Build & test (Docker) diff --git a/qdb/docs/usage.md b/qdb/docs/usage.md index b213e9ea8..61df093c4 100644 --- a/qdb/docs/usage.md +++ b/qdb/docs/usage.md @@ -123,7 +123,7 @@ are not. The extension has no `enabled` key and never reads any of these: | `QUANTA_DB_DAEMON=off` | `docker/qdbd-run.sh` | The supervisord wrapper exits immediately, so no daemon runs. The extension still loads and serves in fallback mode. | | `QUANTA_DB_METRICS_LISTEN` | `docker/qdbstat-exporter.sh` | `host:port` for the Prometheus `/metrics` exporter. Unset, the wrapper exits 0 and no port is opened. | | `QUANTA_DB_DASHBOARD_LISTEN` | `docker/qdbstat-dashboard.sh` | `host:port` for the web file browser. Unset, the wrapper exits 0 and no port is opened. | -| `QUANTA_DB_DASHBOARD_TOKEN` | `qdbstat --dashboard` | Optional shared secret for that dashboard; when set, every `/api/*` route requires it, and the page asks for it if the URL has no `?token=`. Required for import. | +| `QUANTA_DB_DASHBOARD_TOKEN` | `qdbstat --dashboard` | Optional shared secret for that dashboard; when set, every `/api/*` route requires it, and the page asks for it if the URL has no `?token=`. Required for export and import. | | `QUANTA_DB_DASHBOARD_BASE_PATH` | `qdbstat --dashboard` | URL prefix it is served under (e.g. `/qdb`), for an ingress that routes a sub-path to it. Empty = the root. | | `QUANTA_DB_DASHBOARD_IMPORT=on` | `qdbstat --dashboard` | Turns on the dashboard's import, the one route that writes to the data root. Also needs `QUANTA_DB_DASHBOARD_TOKEN`. Same as `--allow-import`. | | `QUANTA_DB_DASHBOARD_IMPORT_MAX_MB` | `qdbstat --dashboard` | Largest archive an import accepts, counted as the size it expands to. Default `2048`. | diff --git a/qdb/src/bin/qdbstat.rs b/qdb/src/bin/qdbstat.rs index 8b0870e24..d649c720d 100644 --- a/qdb/src/bin/qdbstat.rs +++ b/qdb/src/bin/qdbstat.rs @@ -1713,7 +1713,21 @@ fn transfer_policy(a: &Args, has_token: bool) -> transfer::Policy { } else { None }; + // An archive is the whole site in one download, payload files and + // templates included. A dashboard with no token on loopback can be read + // by any web page open in the same browser, through DNS rebinding, so + // export takes the token as import does. + let export_off = if !has_token { + Some( + "It needs QUANTA_DB_DASHBOARD_TOKEN: an archive is the whole site in one download, and \ + without a token any web page open in the same browser could fetch it.", + ) + } else { + None + }; transfer::Policy { + export: export_off.is_none(), + export_off: export_off.map(str::to_string), root, link_root, import: off.is_none(), diff --git a/qdb/src/dashboard.rs b/qdb/src/dashboard.rs index dde5770c4..97b6a1ce2 100644 --- a/qdb/src/dashboard.rs +++ b/qdb/src/dashboard.rs @@ -1333,6 +1333,15 @@ pub fn dispatch_request(cfg: &Config, stats: StatsFn, head: &Head, body: &mut dy /// is found before the head goes out, so a HEAD (which the page sends first) /// answers for the GET. fn route_export(cfg: &Config, q: &Query) -> Response { + // Checked here as well as where the policy is built, as import is: an + // archive of the whole site is never served by a dashboard without a + // token, which a web page can reach through DNS rebinding. + if cfg.token.is_none() { + return json_response( + 403, + &json!({ "error": "cannot export", "detail": "export requires QUANTA_DB_DASHBOARD_TOKEN" }), + ); + } let plan = match transfer::plan_export(&cfg.transfer, &q.get_all("part")) { Ok(p) => p, Err((status, detail)) => { @@ -1520,6 +1529,9 @@ pub fn serve(cfg: Config, stats: StatsFn) -> Result<(), String> { t.import_off.as_deref().unwrap_or("") ), } + if t.root.is_some() && !t.export { + eprintln!("qdbstat: export is off. {}", t.export_off.as_deref().unwrap_or("")); + } let cfg = Arc::new(cfg); let inflight = Arc::new(AtomicUsize::new(0)); @@ -2535,6 +2547,8 @@ mod tests { f.cfg.transfer = transfer::Policy { root: Some(root.clone()), link_root: Some(root.clone()), + export: true, + export_off: None, import, import_off: (!import).then(|| "off in this test".to_string()), max_bytes: 16 << 20, @@ -2570,6 +2584,26 @@ mod tests { assert_eq!(r.status, 401, "the token gates the write route like every other"); } + #[test] + fn export_stays_off_without_the_token() { + // An archive is the whole site in one download. Without a token, any + // page the browser has open can reach a loopback dashboard by DNS + // rebinding, so export, like import, is never served without one -- + // whatever the policy it was handed says. + let (f, _) = transfer_fixture("exportnotoken", None, false); + let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=db", None); + assert_eq!(r.status, 403); + assert!(r.stream.is_none(), "nothing is streamed"); + + let (mut f, _) = transfer_fixture("exportoff", Some("t"), false); + f.cfg.transfer.export = false; + f.cfg.transfer.export_off = Some("off in this test".into()); + let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=db&token=t", None); + assert_eq!(r.status, 403); + let v: Value = serde_json::from_slice(&r.body).unwrap(); + assert_eq!(v["detail"], "Export is off. off in this test"); + } + #[test] fn import_stays_off_without_the_policy_or_the_token() { let (f, _) = transfer_fixture("importoff", None, false); @@ -2618,20 +2652,20 @@ mod tests { #[test] fn an_export_streams_and_a_head_answers_for_it() { - let (f, _) = transfer_fixture("exportroute", None, false); - let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=nope", None); + let (f, _) = transfer_fixture("exportroute", Some("t"), false); + let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=nope&token=t", None); assert_eq!(r.status, 404, "a missing part is found before the download starts"); - let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=db/../x", None); + let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=db/../x&token=t", None); assert_eq!(r.status, 400); - let r = dispatch(&f.cfg, stub_stats, "HEAD", "/api/export?part=db/_users", None); + let r = dispatch(&f.cfg, stub_stats, "HEAD", "/api/export?part=db/_users&token=t", None); assert_eq!(r.status, 200); let head = String::from_utf8(r.encode(true)).unwrap(); assert!(head.contains("Content-Type: application/gzip")); assert!(head.contains("attachment; filename=\"qdb-export-")); assert!(!head.contains("Content-Length"), "a streamed body has no length to promise"); - let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=db/_users&part=db/pages", None); + let r = dispatch(&f.cfg, stub_stats, "GET", "/api/export?part=db/_users&part=db/pages&token=t", None); let gz = run_stream(r); let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(&gz[..])); let names: Vec = ar diff --git a/qdb/src/dashboard/app.js b/qdb/src/dashboard/app.js index 6b8c29cdc..f58dec5cb 100644 --- a/qdb/src/dashboard/app.js +++ b/qdb/src/dashboard/app.js @@ -1141,8 +1141,13 @@ function cardHead(id, ic, title, sub, extra) { } function renderExport(d) { + const pol = exportPolicy(); + const state = d.available && !pol.enabled + ? el("span", { class: "state", title: pol.reason || "" }, "off") + : null; const head = cardHead("export-title", "download", "Export", - "Download parts of the data root as a .tar.gz — documents, payload files and links, read from the files on disk."); + "Download parts of the data root as a .tar.gz — documents, payload files and links, read from the files on disk.", + state); const body = el("div", { class: "card-body" }); const foot = el("footer", { class: "card-foot" }); $("#export-card").replaceChildren(head, body, foot); @@ -1168,6 +1173,11 @@ function renderExport(d) { onChange: paintExportFoot, }); xfer.exportFlash = el("div"); + // The parts are still listed and weighed: what is here is worth seeing + // even where it cannot be downloaded. + if (!pol.enabled) { + body.append(callout("warn", "lock", "Export is off on this dashboard.", pol.reason || "")); + } body.append( xfer.exportTree.el, xfer.exportFlash, @@ -1185,7 +1195,7 @@ function paintExportFoot(t) { const tot = t.totals(); const indexed = xfer.parts && xfer.parts.indexed; const btn = el("button", { - class: "btn primary", type: "button", disabled: !sel.length, + class: "btn primary", type: "button", disabled: !sel.length || !exportPolicy().enabled, onclick: () => startExport(sel, btn), }, icon("download"), "Download archive"); foot.replaceChildren( @@ -1427,6 +1437,7 @@ const imp = { }; const importPolicy = () => (xfer.parts && xfer.parts.import) || { enabled: false, reason: null }; +const exportPolicy = () => (xfer.parts && xfer.parts.export) || { enabled: false, reason: null }; /* Parts the server does not have yet carry a "new" badge; absence of a badge means the part exists and the import writes into it. */ diff --git a/qdb/src/transfer.rs b/qdb/src/transfer.rs index 76c80310e..7822a1291 100644 --- a/qdb/src/transfer.rs +++ b/qdb/src/transfer.rs @@ -101,6 +101,9 @@ pub struct Policy { /// with (`Environment->dir['docroot']`), and a reader comparing link /// targets textually should not see an import as a change. pub link_root: Option, + pub export: bool, + /// Why export is off, in words an operator can act on. + pub export_off: Option, pub import: bool, /// Why import is off, in words an operator can act on. pub import_off: Option, @@ -118,6 +121,8 @@ impl Policy { Policy { root: None, link_root: None, + export: false, + export_off: Some("qdbstat was started without a data root.".into()), import: false, import_off: Some("qdbstat was started without a data root.".into()), max_bytes: DEFAULT_IMPORT_MAX_MB << 20, @@ -192,19 +197,35 @@ pub fn normalize_parts(raw: &[String]) -> Result, String> { Ok(out) } -/// A part may be reached through symlinks above it — a `db` that is a link to -/// a mounted volume is deployment layout — but below the first level it must -/// not BE one. A link at `db/x` is a Quanta container link: archiving it as a -/// part would copy its target under the link's name, and importing that -/// would create a second directory with the target's node name. +/// The first component of a part may be a symlink — a `db` that is a link to +/// a mounted volume is deployment layout — but nothing below it may be: not +/// the part itself, and not a directory on the way to it. A link at `db/x` is +/// a Quanta container link: archiving it as a part would copy its target +/// under the link's name (and importing that copy would make a second +/// directory with the target's node name); importing into it would write +/// into whatever it points at, and a replace would prune that. +/// +/// Checked when an export or import is planned, again before an import's +/// first write (the tree can change while an upload arrives), and once more +/// for each part as it is written to. fn check_part_on_disk(root: &Path, part: &str) -> Result<(), String> { - if part.contains('/') { - if let Ok(md) = fs::symlink_metadata(root.join(part)) { - if md.file_type().is_symlink() { + let mut cur = root.to_path_buf(); + for (i, c) in part.split('/').enumerate() { + cur.push(c); + if i == 0 { + continue; + } + match fs::symlink_metadata(&cur) { + Ok(md) if md.file_type().is_symlink() => { + let at: Vec<&str> = part.split('/').take(i + 1).collect(); return Err(format!( - "{part} is a link on this server; export or import the directory that holds it" + "{} is a link on this server; export or import the directory that holds it", + at.join("/") )); } + Ok(_) => {} + // Nothing exists from here down, so nothing here is a link. + Err(_) => break, } } Ok(()) @@ -278,6 +299,7 @@ fn list_dirs(dir: &Path, follow_links: bool) -> Vec<(String, bool)> { /// `/api/parts`: what can be exported, weighed from the segment when there is /// one, and what this dashboard will accept back. pub fn parts_json(p: &Policy, seg: Option<&SegmentReader>) -> Value { + let export = json!({ "enabled": p.export, "reason": p.export_off }); let import = json!({ "enabled": p.import, "reason": p.import_off, @@ -289,6 +311,7 @@ pub fn parts_json(p: &Policy, seg: Option<&SegmentReader>) -> Value { "available": false, "reason": "qdbstat was started without a data root (--root or QUANTA_DB_ROOT), \ so there is no directory to export from", + "export": export, "import": import, "groups": [], }); @@ -329,6 +352,7 @@ pub fn parts_json(p: &Policy, seg: Option<&SegmentReader>) -> Value { "available": true, "indexed": seg.is_some(), "epoch": seg.map(|s| s.epoch), + "export": export, "import": import, "groups": groups, }) @@ -433,6 +457,10 @@ impl ExportPlan { } pub fn plan_export(p: &Policy, raw_parts: &[String]) -> Result { + if !p.export { + let why = p.export_off.as_deref().unwrap_or_default(); + return Err((403, format!("Export is off. {why}").trim_end().to_string())); + } let Some(root) = &p.root else { return Err((503, "no data root configured".into())); }; @@ -957,6 +985,12 @@ fn classify( let exec = e.header().mode().map(|m| m & 0o100 != 0).unwrap_or(false); Decision::File { size: e.size(), exec } } else if t.is_symlink() { + // A part is imported as its contents. Made a link, it would carry + // every write below it, and a replace's pruning, into whatever the + // link points at. + if rel == parts[pi] { + return skip("a part is imported as a directory, never replaced by a link"); + } let Some(target) = e.link_name_bytes() else { return skip("a symlink with no target"); }; @@ -1176,7 +1210,11 @@ impl Apply<'_> { if self.ok_dirs.contains(&cur) { return Ok(cur); } - match fs::metadata(&cur) { + // Only the first component is followed if it is a link; below it the + // part, and every directory on the way to it, must be real. + check_part_on_disk(self.root, part).map_err(io::Error::other)?; + let md = if part.contains('/') { fs::symlink_metadata(&cur) } else { fs::metadata(&cur) }; + match md { Ok(m) if m.is_dir() => {} Ok(_) => { self.retire(&cur, part)?; @@ -1227,7 +1265,8 @@ impl Apply<'_> { return self.dirs(part, &comps[k..comps.len() - 1]); } // The entry IS the part (a part that is a file): its parent is - // deployment layout, reached through links and made if missing. + // reached as the part's own directories are. + check_part_on_disk(self.root, part).map_err(io::Error::other)?; let abs = self.root.join(part); let parent = abs.parent().unwrap_or(self.root).to_path_buf(); if !parent.is_dir() { @@ -1342,8 +1381,10 @@ impl Apply<'_> { /// Replace mode: retire whatever under `part` the archive did not have. fn prune(&mut self, part: &str, wanted: &HashSet) -> io::Result<()> { + check_part_on_disk(self.root, part).map_err(io::Error::other)?; let dir = self.root.join(part); - match fs::metadata(&dir) { + let md = if part.contains('/') { fs::symlink_metadata(&dir) } else { fs::metadata(&dir) }; + match md { Ok(m) if m.is_dir() => self.prune_dir(&dir, part, wanted), _ => Ok(()), } @@ -1451,6 +1492,13 @@ pub fn run_import(p: &Policy, spec: &ImportSpec, spool: &Spool, emit: &mut dyn F } } + // The parts were checked when the import was planned, but the tree can + // have changed while the upload arrived. Checked again with nothing yet + // written; `Apply` checks each part once more as it starts on it. + for part in &spec.parts { + check_part_on_disk(root, part).map_err(|e| fail(format!("{e}. Nothing was changed.")))?; + } + // ---- pass two: apply -------------------------------------------------- let mut ap = Apply { root, @@ -1670,6 +1718,8 @@ mod tests { Policy { root: Some(root.to_path_buf()), link_root: Some(root.to_path_buf()), + export: true, + export_off: None, import: true, import_off: None, max_bytes: 64 << 20, @@ -1958,6 +2008,71 @@ mod tests { ); } + #[test] + fn an_archive_cannot_turn_a_part_into_a_link() { + // The archive makes the part itself a link to another part, then + // writes beneath it: followed, the writes would land in db/pages and a + // replace would prune db/pages. + let bytes = raw_tar(&[ + ("db/_users", tar::EntryType::Symlink, "pages", b""), + ("db/_users/zed/data.json", tar::EntryType::Regular, "", b"{}"), + ]); + for mode in ["merge", "replace"] { + let t = Tmp::new(&format!("partlink-{mode}")); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let r = import(&p, &bytes, &["db/_users"], mode).unwrap(); + let md = fs::symlink_metadata(root.join("db/_users")).unwrap(); + assert!(md.is_dir() && !md.file_type().is_symlink(), "{mode}: the part stays a directory"); + assert!(root.join("db/_users/zed/data.json").exists(), "{mode}: what is under it lands in it"); + assert!(!root.join("db/pages/zed").exists(), "{mode}: nothing is written through a link"); + assert!(root.join("db/pages/home/data.json").exists(), "{mode}: nor pruned through one"); + assert_eq!(r["skipped_total"], 1, "{mode}: {r}"); + } + } + + #[test] + fn a_part_that_is_a_link_by_the_time_the_import_runs_is_refused() { + let t = Tmp::new("swap"); + let root = t.0.join("site"); + site(&root); + let p = policy(&root, &t.0.join("trash")); + let bytes = export(&p, &["db/_users"]); + let spec = plan_import(&p, &["db/_users".into()], "replace").unwrap(); + // Between the plan and the writes, the part is swapped for a link. + fs::rename(root.join("db/_users"), t.0.join("users-aside")).unwrap(); + symlink(root.join("db/pages"), root.join("db/_users")).unwrap(); + let sp = spool(&mut &bytes[..], bytes.len() as u64, &p.spool_dir).unwrap(); + let e = run_import(&p, &spec, &sp, &mut |_| {}).unwrap_err(); + assert!(e["detail"].as_str().unwrap().contains("is a link"), "{e}"); + assert!(root.join("db/pages/home/data.json").exists(), "nothing is pruned through the link"); + assert!(!root.join("db/pages/alice").exists(), "nothing is written through it"); + assert!(t.0.join("trash").read_dir().map(|mut d| d.next().is_none()).unwrap_or(true), "nothing was displaced"); + + // A link anywhere below the first level is held to the same rule, not + // only at the part's own name. + for part in ["db/_users/alice", "db/_users/alice/data.json"] { + let parts = vec![part.to_string()]; + assert_eq!(plan_import(&p, &parts, "merge").err().map(|e| e.0), Some(400), "{part}"); + assert_eq!(plan_export(&p, &parts).err().map(|e| e.0), Some(400), "{part}"); + } + } + + #[test] + fn export_needs_the_policy_to_allow_it() { + let t = Tmp::new("exportoff"); + let root = t.0.join("site"); + site(&root); + let mut p = policy(&root, &t.0.join("trash")); + p.export = false; + p.export_off = Some("off for the test".into()); + let (status, why) = plan_export(&p, &["db".into()]).err().unwrap(); + assert_eq!(status, 403); + assert_eq!(why, "Export is off. off for the test"); + assert_eq!(parts_json(&p, None)["export"]["enabled"], false); + } + #[test] fn a_damaged_archive_changes_nothing() { let t = Tmp::new("damaged");