Compare commits

..

39 Commits

Author SHA1 Message Date
e44213599c style: rustfmt after merging the release branches
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:41:51 +07:00
1909803df7 merge: worktree-agent-a3b66cf8ba01274e5 2026-11-16 21:37:44 +07:00
f012e664a7 merge: worktree-agent-ae4267aa66ffa0b0a 2026-11-16 21:37:44 +07:00
facaa43753 merge: worktree-agent-ac03eb441ec9759b0
# Conflicts:
#	docs/auth-endpoint-contract.md
2026-11-16 21:37:44 +07:00
6ab788fcda test: cover legacy-import with a stand-in aws (inventory, import, resume, history)
The AWS program becomes a skipped clap field so tests can substitute a fake; run is split
into reconcile (returns the report) and a printing wrapper. No behaviour change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:30:24 +07:00
d98d8354db test: pairing negatives (auth, bad names, malformed bodies, replay, expiry, audit)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:28:19 +07:00
460f6f4db6 fix: reserve disk for admitted exports so concurrent downloads cannot share the same free space
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:26:32 +07:00
f4e42178e6 test: boundary and property tests for the retention and decay evaluators
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:24:40 +07:00
ed6296a9c5 fix: a failed heartbeat no longer abandons a restore once the apply permit is spent
Before the permit the lease is still given up on; after it the failure is logged and the
apply runs to its terminal report instead of being killed mid-flight.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:22:52 +07:00
d14b27669a fix: evict finished reconstitute sessions, keep the mTLS listener alive on accept errors, drop dead code
Also removes OperatorActor.browser, unused since reconstitute targets are confined for every caller.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:19:58 +07:00
6d2b882b3d fix: use a reserved example.invalid host in the postgres URL test fixture
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:19:58 +07:00
8a025b10e4 fix: require 16 characters for a new vault passphrase and warn when an existing one is weaker
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:19:19 +07:00
7d7ebdc172 fix: describe the OpenAPI route as sign-in only in the endpoint contract
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:19:19 +07:00
5b8aec0591 fix: require sign-in for the OpenAPI document unless TESSERA_PUBLIC_OPENAPI is set
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:15:31 +07:00
63a70b9eb8 build: verified image runs non-root on a read-only rootfs; drop --system uid warning; plain Rest Server restart instruction
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:13:58 +07:00
06cfb91434 fix: log request paths only, never query strings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:13:29 +07:00
3fa9a765ce fix: add security headers, correct MIME types and long-cache hashed assets
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:12:48 +07:00
edc74d79c0 fix: confine every reconstitute target to the exports directory and never overwrite an existing file
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:11:34 +07:00
c18815eb5d fix: give each auth-contract request its own source so the token throttle cannot mask a 401
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:11:34 +07:00
9219319ff3 fix: refuse admin tokens under 32 characters and throttle wrong token attempts per source
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:07:37 +07:00
0c141b7038 build: digest-pinned, non-root image with healthcheck; hardened compose with full env passthrough
NOT yet built or run: the Docker daemon's storage was failing at commit time.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:05:31 +07:00
4804ac1f61 docs: Docker deployment notes, admin token length, session lifetime, reverse proxy example
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:05:27 +07:00
a16ff48000 ci: pin actions to commit SHAs, restrict token permissions, add tag-driven release workflow
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:05:01 +07:00
2931032ab7 fix: throttle denied-authentication audit rows per source, never turn a denial into a 500, prune old audit events
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:04:46 +07:00
30ec762324 test: cover the agent restore sequence with fakes
Safety failure never applies, identity and source guards, rollback
exception, per-step timeouts, lost apply permit, crash after permit,
poll lease checks, and the heartbeat-failure behaviour.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:58:32 +07:00
5f7a702a34 fix: avoid self-matching and version-pin false positives in the export checks
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:55:56 +07:00
70ebaed8a2 fix: make the public export fail closed and add e-mail, host and tooling checks
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:55:15 +07:00
b2d5e4d71a test: add trait seams to the agent restore flow (no behaviour change)
RestoreTarget, RestoreHub and BackupSource let the destructive restore
sequence be driven by fakes. poll takes the heartbeat interval as a
parameter instead of reading the constant.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:55:13 +07:00
7953876689 docs: drop the published passphrase from the spec and bring the auth section up to date
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:44 +07:00
a46020c123 fix: allow pinch zoom by dropping the viewport zoom lock
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:43 +07:00
a423f6c064 docs: restructure the changelog as Keep a Changelog for 0.1.0
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:43 +07:00
24cc721e41 docs: point vulnerability reports at GitHub private reporting and add a support window
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:43 +07:00
57738ce714 chore: use a neutral crate author
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:43 +07:00
8c5256ca26 chore: remove tooling leftovers and the dev prototype page from the tree
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:37 +07:00
d99da607b3 chore: use a neutral application name and time zone in the download-name tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:53:17 +07:00
a4fc35a5ea docs: translate the authorization contract to English and drop internal milestone codes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:53:17 +07:00
170b4130d9 chore: rustfmt the refresh modules
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:48:44 +07:00
d356c313ce feat: restore history, undo and redo in the Activity log for everyone who may refresh
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
- Activity lists restores from refresh runs, so the Refresh permission is enough to see them; an administrator's
  restore jobs add the database, the person and the snapshot
- an undo is listed under the restore it reverses, and a redo under that undo; opening a restore or an undo opens
  its undo or redo dialog
- the dialog has an explicit undo mode: it describes what is put back instead of the snapshot that was open, and
  an interrupted restore offers Roll back
- a restore whose safety backup retention has forgotten shows "Safety backup expired" instead of a link, and the
  dialog says how long a safety copy is kept

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:37:21 +07:00
62f0c68e89 feat: roll back a failed restore and say when a safety copy is gone
- a restore whose apply failed can be undone from its safety copy, which is its recovery: the failed apply stops
  fencing the target in the transaction that starts the undo (job phase rolled_back, audited restore.rolled_back);
  an apply whose agent went silent still waits for an administrator to reconcile it; reconciled restores can be undone
- run views carry undo_state (available, superseded, expired), undo_kept_until, undo_of and restore_job_id
- undo state for a list is worked out in one database pass and a file lookup per copy; the vault is read only for the
  newest restore of each target
- eligibility is checked again inside the transaction that creates the run

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:37:21 +07:00
64 changed files with 4322 additions and 999 deletions

View File

@@ -1 +0,0 @@
{"version":"0.0.1","configurations":[{"name":"web","runtimeExecutable":"npm","runtimeArgs":["--prefix","web","run","dev"],"port":5173}]}

View File

@@ -1,17 +1,19 @@
name: ci name: ci
on: [push, pull_request] on: [push, pull_request]
permissions:
contents: read
jobs: jobs:
rust: rust:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with: { node-version: 22, cache: npm, cache-dependency-path: web/package-lock.json } with: { node-version: 22, cache: npm, cache-dependency-path: web/package-lock.json }
- run: npm ci && npm run build - run: npm ci && npm run build
working-directory: web working-directory: web
- uses: dtolnay/rust-toolchain@1.89.0 - uses: dtolnay/rust-toolchain@d92bbbb03544f480ed5c7ba4b54020e4ed2c4f65 # 1.89.0
with: { components: "rustfmt, clippy" } with: { components: "rustfmt, clippy" }
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2
- run: sudo apt-get update && sudo apt-get install -y restic postgresql-client - run: sudo apt-get update && sudo apt-get install -y restic postgresql-client
- run: cargo fmt --all -- --check - run: cargo fmt --all -- --check
- run: cargo clippy --workspace --all-targets -- -D warnings - run: cargo clippy --workspace --all-targets -- -D warnings
@@ -19,15 +21,15 @@ jobs:
supply-chain: supply-chain:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: EmbarkStudios/cargo-deny-action@v2 - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2
- run: cargo install cargo-audit --locked && cargo audit - run: cargo install cargo-audit --version 0.23.0 --locked && cargo audit
web: web:
runs-on: ubuntu-latest runs-on: ubuntu-latest
defaults: { run: { working-directory: web } } defaults: { run: { working-directory: web } }
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with: { node-version: 22, cache: npm, cache-dependency-path: web/package-lock.json } with: { node-version: 22, cache: npm, cache-dependency-path: web/package-lock.json }
- run: npm ci - run: npm ci
- run: npm run typecheck - run: npm run typecheck

68
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,68 @@
name: release
on:
push:
tags: ["v*"]
permissions:
contents: read
jobs:
image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
binaries:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with: { node-version: 22, cache: npm, cache-dependency-path: web/package-lock.json }
- run: npm ci && npm run build
working-directory: web
- uses: dtolnay/rust-toolchain@d92bbbb03544f480ed5c7ba4b54020e4ed2c4f65 # 1.89.0
- run: cargo build --release --locked -p tessera-hub -p tessera-cli -p tessera-agent
- run: |
mkdir dist
cp target/release/tessera-hub target/release/tessera target/release/tessera-agent dist/
tar -C dist -czf "tessera-${GITHUB_REF_NAME}-linux-x86_64.tar.gz" .
sha256sum "tessera-${GITHUB_REF_NAME}-linux-x86_64.tar.gz" > SHA256SUMS
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: linux-x86_64
path: |
tessera-*.tar.gz
SHA256SUMS
publish:
needs: [image, binaries]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with: { name: linux-x86_64 }
- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with:
files: |
tessera-*.tar.gz
SHA256SUMS
generate_release_notes: true

8
.gitignore vendored
View File

@@ -9,5 +9,11 @@ web/dist/
*.part *.part
.DS_Store .DS_Store
# graft's local graph cache — regenerable, not committed (run `graft build`). # Local tooling and editor/agent state: never part of the repository.
/.serena/
/.claude/
/.ignore
/graft/ /graft/
/floorplan/
/web/AGENTS.md
/web/blackhole-proto.html

View File

@@ -1,5 +0,0 @@
# graft's cards are gitignored but should stay greppable: ripgrep reads
# .ignore before .gitignore, so this re-admits the tree to search only.
!graft/
graft/.cache/
graft/.graph/

2
.serena/.gitignore vendored
View File

@@ -1,2 +0,0 @@
/cache
/project.local.yml

View File

@@ -1,189 +0,0 @@
# the name by which the project can be referenced within Serena/when chatting with the LLM.
project_name: "tessera"
# list of language servers to start when using the LSP backend; choose from:
# ada al angular ansible astro
# bash bsl clojure cpp cpp_ccls
# crystal csharp csharp_omnisharp cue dart
# deno elixir elm erlang fortran
# fsharp gdscript gleam go groovy
# haskell haxe hlsl html java
# json julia julia_fatou kotlin latex
# lean4 lua lua_emmylua luau markdown
# matlab msl nextflow nix ocaml
# pascal perl php php_devsense php_phpactor
# php_phpantom powershell python python_basedpyright python_jedi
# python_pyrefly python_ty qml r rego
# ruby ruby_solargraph rust scala scss
# solidity svelte swift systemverilog terraform
# toml typescript typescript_tsgo typescript_vts vue
# vbnet wolfram yaml zig
# (This list may be outdated; generated with scripts/print_language_list.py;
# For the current list, see values of the LanguageServerId enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py)
# For some languages, there are several alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Angular projects, use angular (subsumes typescript+html; requires `npm install` in the project root)
# - For Astro projects, use astro (subsumes typescript/javascript for .astro projects; requires npm)
# - For Svelte projects, use svelte (subsumes typescript/javascript for .svelte projects; requires npm)
# - For Deno projects, use deno (serves the same .ts/.js files as typescript; requires the deno CLI on PATH)
# - For SCSS / Sass / plain CSS, use scss (some-sass-language-server handles all three)
# - For Free Pascal/Lazarus, use pascal
# - External Python adapters may add further registered IDs; install the adapter package first
# and then use its ID here, for example: example
# Special requirements:
# Some language servers require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple language servers, the first language server that supports a given file will be used for that file.
# The first language server is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
language_servers:
- typescript
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# optional shell command to run before the language backend (LSP or JetBrains) is initialised.
# the command runs in the project root directory and is only executed if the project is trusted
# (see trusted_project_path_patterns in the global configuration).
# serena waits for the command to exit: a non-zero exit code is logged as an error but does not
# abort activation. a per-project timeout (activation_command_timeout, default 180s) is the safety
# backstop for non-terminating commands; on expiry the process is killed and activation continues.
# example: activation_command: "npx nx run-many -t build"
activation_command:
# maximum time in seconds to wait for activation_command to complete before killing it (default 180s).
# must be a positive number.
activation_command_timeout: 180.0
# line ending convention to use when writing source files.
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
line_ending:
# The language backend to use for this project.
# If not set, the global setting from serena_config.yml is used.
# Valid values: LSP, JetBrains
# Note: the backend is fixed at startup. If a project with a different backend
# is activated post-init, an error will be returned.
language_backend:
# The interface through which the agent (LLM) accesses Serena's functionality (overrides the global setting).
# Valid values: tools, REPL (see the global configuration for details); leave empty to use the global setting.
# Note: the interface is fixed at startup. If a project is activated post-init, its setting is not applied.
agent_interface:
# whether to use project's .gitignore files to ignore files
ignore_all_files_in_gitignore: true
# advanced configuration option allowing to configure language server-specific options.
# Maps the language key to the options.
# The settings are considered only if the project is trusted (see global configuration to define trusted projects).
# See https://oraios.github.io/serena/02-usage/050_configuration.html#language-server-specific-settings
ls_specific_settings: {}
# list of workspace folder paths (LSP backend only).
# These folders will be used to build up Serena's symbol index.
# Paths must be within the project root and should thus be relative to the project root.
# Furthermore, the paths should not be filtered by ignore settings.
# Default setting: The entire project root folder (".") is considered.
# In (large) monorepos, this can be used to index only subfolders of the project root, e.g.
# ls_workspace_folders:
# - "./subproject1"
# - "./subproject2"
ls_workspace_folders:
- "."
# list of additional workspace folder paths for cross-package reference support.
# Paths can be absolute or relative to the project root.
# Each folder is registered as an LSP workspace folder, enabling language servers to discover
# symbols and references across package boundaries, but these folders are not indexed by Serena,
# i.e. the respective symbols will not be found using Serena's symbol search tools.
# Example:
# additional_workspace_folders:
# - ../sibling-package
# - ../shared-lib
ls_additional_workspace_folders: []
# list of additional paths to ignore in this project.
# Same syntax as gitignore, so you can use * and **.
# Important: quote patterns that start with `*`, otherwise YAML treats them as aliases.
# Example:
# ignored_paths:
# - "examples/**"
# - ".worktrees/**"
# - "**/bin/**"
# - "**/obj/**"
# Note: global ignored_paths from serena_config.yml are also applied additively.
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names (and tool markers) to exclude.
# This extends the existing exclusions (e.g. from the global configuration)
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
excluded_tools: []
# list of tools (and tool markers) to include that would otherwise be disabled (particularly optional tools
# that are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
included_optional_tools: []
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
fixed_tools: []
# list of APIs (facades or facade methods, e.g. "lsp" or "lsp.find_symbol") to exclude from the REPL.
# Add "marker:editing" to exclude all editing functions.
# This extends the existing exclusions (e.g. from the global configuration).
excluded_apis: []
# list of APIs (facades or facade methods, e.g. "lsp" or "lsp.get_diagnostics_for_symbol") to include in the REPL
# that would otherwise be disabled (particularly optional methods, which are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
included_apis: []
# list of mode names that are to be activated by default, overriding the setting in the global configuration.
# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# If the setting is undefined/empty, the default_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
# Therefore, you can set this to [] if you do not want the default modes defined in the global config to apply
# for this project.
# This setting can, in turn, be overridden by CLI parameters (--mode).
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
default_modes:
# list of mode names to be activated additionally for this project, e.g. ["query-projects"]
# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
added_modes:
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
# time budget (seconds) per tool call for the retrieval of additional symbol information
# such as docstrings or parameter information.
# This overrides the corresponding setting in the global configuration; see the documentation there.
# If null or missing, use the setting from the global configuration.
symbol_info_budget:
# list of regex patterns which, when matched, mark a memory entry as read‑only.
# Extends the list from the global configuration, merging the two lists.
read_only_memory_patterns: []
# list of regex patterns for memories to completely ignore.
# Matching memories will not appear in list_memories or activate_project output
# and cannot be accessed via read_memory or write_memory.
# To access ignored memory files, use the read_file tool on the raw file path.
# Extends the list from the global configuration, merging the two lists.
# Example: ["_archive/.*", "_episodes/.*"]
ignored_memory_patterns: []

View File

@@ -1,6 +1,14 @@
# Changelog # Changelog
## Unreleased (0.1.0 candidate) All notable changes to this project are documented in this file. The format is based on
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.0] - 2026-11-16
First public release.
### Added
- Authentication rebuilt: server-side sessions, emergency operator, OIDC (authorization code + PKCE), digest-only - Authentication rebuilt: server-side sessions, emergency operator, OIDC (authorization code + PKCE), digest-only
Outpost tokens and pairing codes, rate limiting, central access gate with per-orbit grants. Outpost tokens and pairing codes, rate limiting, central access gate with per-orbit grants.
@@ -8,3 +16,15 @@
- Environments, production-to-staging relations and durable refresh runs with re-authorisation before overwrite. - Environments, production-to-staging relations and durable refresh runs with re-authorisation before overwrite.
- Refresh console for QA and a refresh-only access mode. - Refresh console for QA and a refresh-only access mode.
- Managed PostgreSQL/MySQL capture and restore through Outposts, Restic deduplication, GFS retention. - Managed PostgreSQL/MySQL capture and restore through Outposts, Restic deduplication, GFS retention.
### Security
- Security headers on every response, and a CSRF check on cookie-authenticated mutations.
- Audit log hardening: denials are throttled per source and audit records are subject to a retention window.
- Rate limiting per client address, with `X-Forwarded-For` honoured only from `TESSERA_TRUSTED_PROXIES`.
- The published development vault passphrase is refused for new vaults.
### Packaging
- The container image runs as a non-root user.
- A release workflow builds and publishes the release artifacts.

1
Cargo.lock generated
View File

@@ -3083,6 +3083,7 @@ name = "tessera-agent"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait",
"base64 0.22.1", "base64 0.22.1",
"clap", "clap",
"hex", "hex",

View File

@@ -14,7 +14,7 @@ members = [
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
authors = ["Senkensha"] authors = ["The Tessera contributors"]
[workspace.dependencies] [workspace.dependencies]
anyhow = "1.0" anyhow = "1.0"

View File

@@ -1,28 +1,55 @@
FROM node:22-bookworm AS web # syntax=docker/dockerfile:1
# Base images are pinned by multi-arch index digest. To update, run
# `docker buildx imagetools inspect <image:tag>` and replace the digest.
FROM node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb AS web
WORKDIR /build WORKDIR /build
COPY web/package.json web/package-lock.json* ./ COPY web/package.json web/package-lock.json* ./
RUN npm ci RUN npm ci
COPY web/ ./ COPY web/ ./
RUN npm run build RUN npm run build
FROM rust:1.89-bookworm AS rust FROM rust:1.89-bookworm@sha256:948f9b08a66e7fe01b03a98ef1c7568292e07ec2e4fe90d88c07bb14563c84ff AS rust
WORKDIR /build WORKDIR /build
COPY Cargo.toml Cargo.lock* ./ COPY Cargo.toml Cargo.lock* ./
COPY crates ./crates COPY crates ./crates
COPY --from=web /build/dist ./web/dist COPY --from=web /build/dist ./web/dist
RUN cargo build --release -p tessera-hub RUN cargo build --release --locked -p tessera-hub -p tessera-cli
FROM restic/restic:0.19.1 AS restic FROM restic/restic:0.19.1@sha256:136600b6ff6843d61d355f7f71f460a166429f35de6fd11b568fece3c9a4d510 AS restic
FROM mysql:8.4 AS mysql-client FROM mysql:8.4@sha256:a81d043930e51745522bd5c430961cf8286f0a23f0a9a2a6e0108f7ea71b0902 AS mysql-client
FROM debian:bookworm-slim FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates postgresql-client libstdc++6 && rm -rf /var/lib/apt/lists/* # Bookworm ships pg_dump 15, which refuses to dump a newer server. Install a
COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/ # current client from the PostgreSQL project's apt repository (PGDG) instead.
# pg_dump 17 dumps servers 9.2 through 17.
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl gnupg libstdc++6 \
&& install -d /usr/share/keyrings \
&& curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor -o /usr/share/keyrings/pgdg.gpg \
&& echo "deb [signed-by=/usr/share/keyrings/pgdg.gpg] https://apt.postgresql.org/pub/repos/apt bookworm-pgdg main" > /etc/apt/sources.list.d/pgdg.list \
&& apt-get update \
&& apt-get install -y --no-install-recommends postgresql-client-17 \
&& apt-get purge -y --auto-remove curl gnupg \
&& rm -rf /var/lib/apt/lists/*
COPY --from=rust /build/target/release/tessera-hub /build/target/release/tessera /usr/local/bin/
COPY --from=restic /usr/bin/restic /usr/local/bin/restic COPY --from=restic /usr/bin/restic /usr/local/bin/restic
COPY --from=mysql-client /usr/bin/mysqldump /usr/local/bin/mysqldump COPY --from=mysql-client /usr/bin/mysqldump /usr/local/bin/mysqldump
RUN restic version && mysqldump --version COPY --chmod=0755 <<'EOF2' /usr/local/bin/tessera-healthcheck
#!/bin/bash
# Minimal HTTP GET /health using bash's /dev/tcp, so the slim image needs no curl.
port="${TESSERA_LISTEN##*:}"
exec 3<>"/dev/tcp/127.0.0.1/${port:-8787}" || exit 1
printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3
IFS= read -r status <&3
[[ "$status" == HTTP/*" 200 "* ]]
EOF2
RUN restic version && mysqldump --version && pg_dump --version && tessera --help >/dev/null \
&& useradd --uid 10001 --user-group --home-dir /home/tessera --create-home tessera \
&& install -d -o tessera -g tessera /data
ENV TESSERA_LISTEN=0.0.0.0:8787 ENV TESSERA_LISTEN=0.0.0.0:8787
ENV TESSERA_DATA_DIR=/data ENV TESSERA_DATA_DIR=/data
EXPOSE 8787 EXPOSE 8787
VOLUME ["/data"] VOLUME ["/data"]
USER tessera
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD ["/usr/local/bin/tessera-healthcheck"]
ENTRYPOINT ["tessera-hub"] ENTRYPOINT ["tessera-hub"]

View File

@@ -16,10 +16,10 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera-hub ./target/release/tessera-hub
``` ```
The hub listens on **127.0.0.1:8787** unless `TESSERA_LISTEN` is set. Open [http://127.0.0.1:8787](http://127.0.0.1:8787). The OpenAPI document is at `/api-doc/openapi.json`. There is no default passphrase, and new vaults refuse the old published value `dev-vault-key`. Leave `TESSERA_SEED_DEMO` unset; `TESSERA_SEED_DEMO=1` writes demo backup history into the data directory. The hub listens on **127.0.0.1:8787** unless `TESSERA_LISTEN` is set. Open [http://127.0.0.1:8787](http://127.0.0.1:8787). The OpenAPI document is at `/api-doc/openapi.json` for signed-in operators (set `TESSERA_PUBLIC_OPENAPI=true` to publish it). There is no default passphrase, and new vaults refuse the old published value `dev-vault-key`. Leave `TESSERA_SEED_DEMO` unset; `TESSERA_SEED_DEMO=1` writes demo backup history into the data directory.
Authentication is required by default, including on loopback. Configure at least one of: the emergency operator Authentication is required by default, including on loopback. Configure at least one of: the emergency operator
(`TESSERA_OPERATOR_PASSWORD_HASH`), a shared API token (`TESSERA_ADMIN_TOKEN`, optionally with (`TESSERA_OPERATOR_PASSWORD_HASH`), a shared API token (`TESSERA_ADMIN_TOKEN`, at least 32 characters, optionally with
`TESSERA_ADMIN_TOKEN_EXPIRES`), or OIDC single sign-on. The hub refuses to start with none of them. For synthetic local `TESSERA_ADMIN_TOKEN_EXPIRES`), or OIDC single sign-on. The hub refuses to start with none of them. For synthetic local
development only, `TESSERA_LOCAL_DEVELOPMENT=true` allows anonymous loopback access. See development only, `TESSERA_LOCAL_DEVELOPMENT=true` allows anonymous loopback access. See
[docs/DATABASE-CAPTURE.md](docs/DATABASE-CAPTURE.md) for operator sign-in, OIDC, per-orbit access grants, downloads, [docs/DATABASE-CAPTURE.md](docs/DATABASE-CAPTURE.md) for operator sign-in, OIDC, per-orbit access grants, downloads,
@@ -32,7 +32,25 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
docker compose up --build docker compose up --build
``` ```
Compose publishes **127.0.0.1:8787** only. The process inside the container listens on `0.0.0.0:8787` so that published port can reach it. The image includes `pg_dump` via `postgresql-client`. Compose publishes **127.0.0.1:8787** only. The process inside the container listens on `0.0.0.0:8787` so that published port can reach it. Compose also needs operator, token or OIDC credentials (see above); pass them through the environment. `compose.yaml` forwards the `TESSERA_*` settings documented here.
The image runs as the non-root user `tessera` (uid 10001) with a read-only root filesystem, no capabilities and a health check on `/health`. All state lives in the `/data` volume, and database dumps are staged there too (`TMPDIR=/data`), so size that volume for one full dump per concurrent capture. It ships `tessera-hub`, the `tessera` CLI, Restic, `mysqldump` and `pg_dump` 17. Base images are pinned by digest.
Requirements and limits to know before exposing it:
- `TESSERA_ADMIN_TOKEN` must be at least 32 characters (`openssl rand -base64 32`).
- Audit records are kept for `TESSERA_AUDIT_RETENTION_DAYS` days (default 90).
- `TESSERA_TRUSTED_PROXIES` takes a comma-separated list of exact proxy IP addresses, not CIDR ranges. Set it when a reverse proxy terminates TLS in front of the hub, along with `TESSERA_PUBLIC_URL`; otherwise the hub sees the proxy as every client.
- Run decay's space reclamation with `docker compose exec tessera-hub tessera gc`.
- Create the operator hash with `printf '%s\n' "$pw" | docker run --rm -i --entrypoint tessera-hub <image> --hash-operator-password`.
Example reverse proxy (Caddy on the same host, TLS handled by Caddy; set `TESSERA_PUBLIC_URL=https://tessera.example.org` and `TESSERA_TRUSTED_PROXIES=127.0.0.1`):
```
tessera.example.org {
reverse_proxy 127.0.0.1:8787
}
```
### CLI ### CLI
@@ -74,7 +92,7 @@ The API accepts `{"retention":{"keep_daily":7,"keep_weekly":2,"keep_monthly":6,"
The same repository setup is used by new [Outpost backup profiles](docs/DATABASE-CAPTURE.md). The same repository setup is used by new [Outpost backup profiles](docs/DATABASE-CAPTURE.md).
Rest Server's `.htpasswd` must use bcrypt entries (`htpasswd -B`); Apache `apr1` hashes from `openssl passwd -apr1` are rejected with "Invalid htpasswd entry". Restart Rest Server after changing the file (a reload signal was not enough in testing). Rest Server's `.htpasswd` must use bcrypt entries (`htpasswd -B`); Apache `apr1` hashes from `openssl passwd -apr1` are rejected with "Invalid htpasswd entry". Restart Rest Server (do not just signal a reload) after changing the file.
Run [Rest Server](https://github.com/restic/rest-server#usage) with TLS, authentication, `--append-only`, and `--private-repos`. Point its storage at the hub's `vault/outposts` directory. Both processes need filesystem access to that directory. Give Rest Server access only to `outposts`, with a separate location for its TLS and authentication files. Run [Rest Server](https://github.com/restic/rest-server#usage) with TLS, authentication, `--append-only`, and `--private-repos`. Point its storage at the hub's `vault/outposts` directory. Both processes need filesystem access to that directory. Give Rest Server access only to `outposts`, with a separate location for its TLS and authentication files.
@@ -105,7 +123,7 @@ See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tesser
- Set `TESSERA_WORMHOLE_MTLS` to `1` or `true` to open a client-certificate listener. It also needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is up, plain HTTP upload routes answer 403. An agent needs `TESSERA_WORMHOLE_CLIENT_CERT` and `TESSERA_WORMHOLE_CLIENT_KEY` for that listener. Configure `TESSERA_WORMHOLE_CA` when the hub certificate uses a private CA. - Set `TESSERA_WORMHOLE_MTLS` to `1` or `true` to open a client-certificate listener. It also needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is up, plain HTTP upload routes answer 403. An agent needs `TESSERA_WORMHOLE_CLIENT_CERT` and `TESSERA_WORMHOLE_CLIENT_KEY` for that listener. Configure `TESSERA_WORMHOLE_CA` when the hub certificate uses a private CA.
- PostgreSQL captures still run a full `pg_dump` into a private temporary file. Restic can deduplicate matching bytes in the resulting dump. Allow temporary disk space for one full dump per concurrent capture. The Docker image contains only the hub (plus Restic and the database clients): build `tessera-agent` and the `tessera` CLI separately and install them on the hosts that need them. On non-x86 hosts build x86_64 binaries natively or in CI, not under QEMU emulation (`aws-lc-sys` crashes the compiler there). - PostgreSQL captures still run a full `pg_dump` into a private temporary file. Restic can deduplicate matching bytes in the resulting dump. Allow temporary disk space for one full dump per concurrent capture. The Docker image contains only the hub (plus Restic and the database clients): build `tessera-agent` and the `tessera` CLI separately and install them on the hosts that need them. On non-x86 hosts build x86_64 binaries natively or in CI, not under QEMU emulation (`aws-lc-sys` crashes the compiler there).
The release image includes `pg_dump`; a native hub needs it on `PATH`. A native hub needs `pg_dump` and `mysqldump` on `PATH`; the Docker image includes them.
- The command provider is outside this release. Creating a command orbit and running it returns `command provider is outside this release; use filesystem or postgres`. - The command provider is outside this release. Creating a command orbit and running it returns `command provider is outside this release; use filesystem or postgres`.
- OIDC supports a single issuer (authorization code with PKCE). Administrators come only from configuration (`TESSERA_OIDC_ADMIN_SUBJECTS` / `TESSERA_OIDC_ADMIN_GROUPS`); there is no first-user-becomes-admin and no self-registration. Group grants are not re-checked against the IdP during a session. - OIDC supports a single issuer (authorization code with PKCE). Administrators come only from configuration (`TESSERA_OIDC_ADMIN_SUBJECTS` / `TESSERA_OIDC_ADMIN_GROUPS`); there is no first-user-becomes-admin and no self-registration. Group grants are not re-checked against the IdP during a session.

View File

@@ -1,9 +1,30 @@
# Security policy # Security policy
Report vulnerabilities privately to the maintainers (use the repository's private security advisory feature, or the ## Reporting a vulnerability
contact listed on the project page). Do not open a public issue for a vulnerability. Expect an acknowledgement within a
few days.
Supported: the latest release. Tessera holds encrypted backups: keep `TESSERA_VAULT_PASSPHRASE` and the `vault` Please report vulnerabilities privately. Use GitHub private vulnerability reporting: open the repository's **Security**
directory together, serve the hub over HTTPS outside loopback, and set `TESSERA_TRUSTED_PROXIES` only for proxies you tab and choose **Report a vulnerability**. Do not open a public issue or pull request for a vulnerability.
operate. Hardening notes and the auth design are in `docs/DATABASE-CAPTURE.md` and `docs/auth-endpoint-contract.md`.
<!-- Owner: add a security contact email on the next line if you want an alternative to GitHub reporting. -->
Security contact email: not configured yet.
We aim to acknowledge a report within a few days, agree on a fix and disclosure timeline with you, and credit you in the
release notes if you wish. Please give us a reasonable window to ship a fix before you disclose publicly.
## Supported versions
Only the latest 0.1.x release receives security fixes. Upgrade to the newest patch release before reporting an issue
that may already be fixed.
## Deploying safely
Tessera holds encrypted backups. Keep `TESSERA_VAULT_PASSPHRASE` and the `vault` directory together and backed up
separately from the hub's host, and serve the hub over HTTPS outside loopback.
When the hub runs behind a reverse proxy, set `TESSERA_TRUSTED_PROXIES` (comma-separated IPs) to the proxies you
operate and nothing else. The hub rate-limits and audits by client address: `X-Forwarded-For` is only trusted when the
connecting peer is listed there. Left unset, every user shares the proxy's address and its rate-limit budget; listing an
address you do not control lets that peer pick the client address the hub records.
Hardening notes are in `docs/DATABASE-CAPTURE.md`; the authorization design and the per-route matrix are in
`docs/auth-endpoint-contract.md`.

View File

@@ -9,18 +9,54 @@ services:
TESSERA_DATA_DIR: /data TESSERA_DATA_DIR: /data
TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE} TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE}
TESSERA_ADMIN_TOKEN: TESSERA_ADMIN_TOKEN:
TESSERA_ADMIN_TOKEN_EXPIRES:
TESSERA_OPERATOR_PASSWORD_HASH: TESSERA_OPERATOR_PASSWORD_HASH:
TESSERA_OPERATOR_NAME: TESSERA_OPERATOR_NAME:
TESSERA_PUBLIC_URL:
TESSERA_TRUSTED_PROXIES:
TESSERA_OIDC_ISSUER:
TESSERA_OIDC_CLIENT_ID:
TESSERA_OIDC_CLIENT_SECRET:
TESSERA_OIDC_REDIRECT_URL:
TESSERA_OIDC_ADMIN_SUBJECTS:
TESSERA_OIDC_ADMIN_GROUPS:
TESSERA_OIDC_GROUPS_CLAIM:
TESSERA_OIDC_CA_FILE:
TESSERA_WORMHOLE_LISTEN:
TESSERA_WORMHOLE_MTLS:
TESSERA_WORMHOLE_CERT:
TESSERA_WORMHOLE_KEY:
TESSERA_WORMHOLE_CLIENT_CA:
TESSERA_EXPORT_CONCURRENCY:
TESSERA_EXPORT_MIN_FREE_BYTES:
TESSERA_OUTPOST_TOKEN_DAYS:
TESSERA_REFRESH_TTL_MINUTES:
TESSERA_REFRESH_MAX_ACTIVE:
TESSERA_OFFSITE_REPOSITORY: TESSERA_OFFSITE_REPOSITORY:
TESSERA_OFFSITE_PASSWORD_FILE: TESSERA_OFFSITE_PASSWORD_FILE:
AWS_ACCESS_KEY_ID: AWS_ACCESS_KEY_ID:
AWS_SECRET_ACCESS_KEY: AWS_SECRET_ACCESS_KEY:
AWS_SESSION_TOKEN: AWS_SESSION_TOKEN:
AWS_REGION: AWS_REGION:
# Database dumps and exports are staged on the data volume, not in RAM.
TMPDIR: /data
RESTIC_CACHE_DIR: /tmp/restic-cache
RUST_LOG: tessera_hub=info RUST_LOG: tessera_hub=info
volumes: volumes:
- tessera-data:/data - tessera-data:/data
read_only: true
tmpfs:
- /tmp:size=256m,mode=1777
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
restart: unless-stopped restart: unless-stopped
healthcheck:
test: ["CMD", "/usr/local/bin/tessera-healthcheck"]
interval: 30s
timeout: 5s
retries: 3
start_period: 20s
volumes: volumes:
tessera-data: tessera-data:

View File

@@ -13,6 +13,7 @@ path = "src/main.rs"
tessera-core = { path = "../tessera-core" } tessera-core = { path = "../tessera-core" }
tessera-providers = { path = "../tessera-providers" } tessera-providers = { path = "../tessera-providers" }
anyhow.workspace = true anyhow.workspace = true
async-trait.workspace = true
clap.workspace = true clap.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true

View File

@@ -46,8 +46,15 @@ pub(super) enum Source {
Mysql(MysqlSource), Mysql(MysqlSource),
} }
impl Source { /// The local backup source, as far as the restore guard cares: which database it is.
pub(super) async fn identity(&self) -> Result<DatabaseIdentity> { #[async_trait::async_trait]
pub(super) trait BackupSource: Sync {
async fn identity(&self) -> Result<DatabaseIdentity>;
}
#[async_trait::async_trait]
impl BackupSource for Source {
async fn identity(&self) -> Result<DatabaseIdentity> {
match self { match self {
Self::Postgres(source) => source.identity().await, Self::Postgres(source) => source.identity().await,
Self::Mysql(source) => source.identity().await, Self::Mysql(source) => source.identity().await,
@@ -119,6 +126,7 @@ pub async fn run(cli: &Cli, path: &Path) -> Result<()> {
profile.source.as_ref(), profile.source.as_ref(),
&profile.targets, &profile.targets,
profile.timeout_seconds, profile.timeout_seconds,
Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS),
) )
.await?; .await?;
if !restored && (profile.source.is_some() || !profile.paths.is_empty()) { if !restored && (profile.source.is_some() || !profile.paths.is_empty()) {

View File

@@ -1,12 +1,21 @@
use crate::{ use crate::{
http, http,
jobs::{digest_file, Hub, Source}, jobs::{digest_file, BackupSource, Hub},
}; };
use anyhow::{ensure, Context, Result}; use anyhow::{ensure, Context, Result};
use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use std::{collections::HashMap, fs::File, sync::Arc, time::Duration}; use std::{
collections::HashMap,
fs::File,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use tessera_core::{ use tessera_core::{
job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS}, job::CaptureFormat,
restore::{DatabaseIdentity, RestoreLease, RestoreProgress}, restore::{DatabaseIdentity, RestoreLease, RestoreProgress},
}; };
use tessera_providers::{MysqlRestore, PostgresRestore}; use tessera_providers::{MysqlRestore, PostgresRestore};
@@ -19,7 +28,108 @@ pub(super) enum Target {
Mysql(MysqlRestore), Mysql(MysqlRestore),
} }
impl Target { /// The local database a restore is applied to. A seam so the destructive sequence in `run` can be driven
/// by fakes in tests; the real implementation is `Target`.
#[async_trait]
pub(super) trait RestoreTarget: Sync {
async fn identity(&self) -> Result<DatabaseIdentity>;
async fn prepare(&self, input: File, lease: &RestoreLease) -> Result<File>;
async fn safety(&self, stage: File) -> Result<()>;
async fn apply(&self, script: File) -> Result<()>;
}
/// What the restore flow needs from the hub. A seam for tests; the real implementation is `Arc<Hub>`.
#[async_trait]
pub(super) trait RestoreHub: Sync {
async fn send(
&self,
path: String,
body: serde_json::Value,
restore: Option<Uuid>,
) -> Result<String>;
async fn send_with_reason(
&self,
path: String,
body: serde_json::Value,
restore: Uuid,
reason: Option<String>,
) -> Result<String>;
async fn upload_safety(
&self,
lease: &RestoreLease,
stage: File,
timeout: Duration,
) -> Result<()>;
async fn download(&self, lease: &RestoreLease, timeout: Duration) -> Result<File>;
}
#[async_trait]
impl RestoreHub for Arc<Hub> {
async fn send(
&self,
path: String,
body: serde_json::Value,
restore: Option<Uuid>,
) -> Result<String> {
self.post(path, body, restore).await
}
async fn send_with_reason(
&self,
path: String,
body: serde_json::Value,
restore: Uuid,
reason: Option<String>,
) -> Result<String> {
self.post_with_reason(path, body, restore, reason).await
}
async fn upload_safety(
&self,
lease: &RestoreLease,
stage: File,
timeout: Duration,
) -> Result<()> {
self.upload(
format!("restore/{}/safety", lease.job.id),
stage,
timeout,
"x-tessera-restore-token",
lease.token,
None,
)
.await
}
async fn download(&self, lease: &RestoreLease, timeout: Duration) -> Result<File> {
let hub = self.clone();
let id = lease.job.id;
let token = lease.token.to_string();
let digest = lease.artifact.sha256.clone();
tokio::task::spawn_blocking(move || {
let mut file = tempfile::tempfile().context("create private restore staging")?;
let size = http::get_file(
&format!("{}/api/v1/wormhole/restore/{id}/payload", hub.url),
&mut file,
&[
("x-tessera-upload-token", &hub.token),
("x-tessera-restore-token", &token),
],
timeout,
)?;
let (bytes, computed) = digest_file(&mut file)?;
ensure!(
size == bytes && computed == digest,
"restore payload checksum mismatch"
);
Ok(file)
})
.await?
}
}
#[async_trait]
impl RestoreTarget for Target {
async fn identity(&self) -> Result<DatabaseIdentity> { async fn identity(&self) -> Result<DatabaseIdentity> {
match self { match self {
Self::Postgres(target) => target.connection.identity().await, Self::Postgres(target) => target.connection.identity().await,
@@ -59,16 +169,17 @@ impl Target {
} }
} }
pub(super) async fn poll( pub(super) async fn poll<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &Arc<Hub>, hub: &H,
application: Uuid, application: Uuid,
source: Option<&Source>, source: Option<&S>,
targets: &HashMap<Uuid, Target>, targets: &HashMap<Uuid, T>,
timeout_seconds: u64, timeout_seconds: u64,
heartbeat: Duration,
) -> Result<bool> { ) -> Result<bool> {
for (target_id, target) in targets { for (target_id, target) in targets {
let reply = hub let reply = hub
.post( .send(
format!("restore-targets/{target_id}/claim"), format!("restore-targets/{target_id}/claim"),
serde_json::Value::Null, serde_json::Value::Null,
None, None,
@@ -81,20 +192,32 @@ pub(super) async fn poll(
lease.job.target.id == *target_id && lease.job.target.application_id == application, lease.job.target.id == *target_id && lease.job.target.application_id == application,
"hub returned an unexpected restore target" "hub returned an unexpected restore target"
); );
let permit_taken = AtomicBool::new(false);
let work = run( let work = run(
hub, hub,
&lease, &lease,
target, target,
source, source,
Duration::from_secs(timeout_seconds), Duration::from_secs(timeout_seconds),
&permit_taken,
); );
tokio::pin!(work); tokio::pin!(work);
loop { loop {
tokio::select! { tokio::select! {
biased; biased;
result = &mut work => return result.map(|()| true), result = &mut work => return result.map(|()| true),
_ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => { _ = tokio::time::sleep(heartbeat) => {
report(hub, &lease, RestoreProgress::Heartbeat).await?; if let Err(error) = report(hub, &lease, RestoreProgress::Heartbeat).await {
// Once the apply permit is spent, dropping `work` would kill the apply
// half way (its children are `kill_on_drop`) and leave the target
// half-restored with no terminal report. Keep going and let the outcome
// report decide. Before the permit nothing destructive has happened,
// so give up and let the lease expire.
if !permit_taken.load(Ordering::SeqCst) {
return Err(error);
}
tracing::warn!(restore = %lease.job.id, %error, "heartbeat failed during apply; letting the restore finish");
}
} }
} }
} }
@@ -102,16 +225,17 @@ pub(super) async fn poll(
Ok(false) Ok(false)
} }
async fn run( async fn run<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &Arc<Hub>, hub: &H,
lease: &RestoreLease, lease: &RestoreLease,
target: &Target, target: &T,
source: Option<&Source>, source: Option<&S>,
timeout: Duration, timeout: Duration,
permit_taken: &AtomicBool,
) -> Result<()> { ) -> Result<()> {
report(hub, lease, RestoreProgress::Checking).await?; report(hub, lease, RestoreProgress::Checking).await?;
let downloaded = tokio::time::timeout(timeout, async { let downloaded = tokio::time::timeout(timeout, async {
let input = download(hub, lease, timeout).await?; let input = hub.download(lease, timeout).await?;
target.prepare(input, lease).await target.prepare(input, lease).await
}) })
.await; .await;
@@ -159,15 +283,7 @@ async fn run(
target.identity().await? == identity, target.identity().await? == identity,
"target changed during safety capture" "target changed during safety capture"
); );
hub.upload( hub.upload_safety(lease, stage, timeout).await?;
format!("restore/{}/safety", lease.job.id),
stage,
timeout,
"x-tessera-restore-token",
lease.token,
None,
)
.await?;
Ok::<_, anyhow::Error>(()) Ok::<_, anyhow::Error>(())
}) })
.await; .await;
@@ -176,8 +292,10 @@ async fn run(
return Ok(()); return Ok(());
} }
// The permit is single-use. A lost response leaves the target locked for reconciliation. // The permit is single-use. A lost response leaves the target locked for reconciliation. Mark it
hub.post( // taken before asking: from here on the hub may consider the apply started.
permit_taken.store(true, Ordering::SeqCst);
hub.send(
format!("restore/{}/apply", lease.job.id), format!("restore/{}/apply", lease.job.id),
serde_json::Value::Null, serde_json::Value::Null,
Some(lease.token), Some(lease.token),
@@ -198,13 +316,13 @@ fn why<T>(result: Result<Result<T>, tokio::time::error::Elapsed>) -> String {
} }
} }
async fn report_failed( async fn report_failed<H: RestoreHub>(
hub: &Arc<Hub>, hub: &H,
lease: &RestoreLease, lease: &RestoreLease,
progress: RestoreProgress, progress: RestoreProgress,
reason: String, reason: String,
) -> Result<()> { ) -> Result<()> {
hub.post_with_reason( hub.send_with_reason(
format!("restore/{}/report", lease.job.id), format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?, serde_json::to_value(progress)?,
lease.token, lease.token,
@@ -214,8 +332,12 @@ async fn report_failed(
Ok(()) Ok(())
} }
async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> { async fn report<H: RestoreHub>(
hub.post( hub: &H,
lease: &RestoreLease,
progress: RestoreProgress,
) -> Result<()> {
hub.send(
format!("restore/{}/report", lease.job.id), format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?, serde_json::to_value(progress)?,
Some(lease.token), Some(lease.token),
@@ -224,28 +346,5 @@ async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress)
Ok(()) Ok(())
} }
async fn download(hub: &Arc<Hub>, lease: &RestoreLease, timeout: Duration) -> Result<File> { #[cfg(test)]
let hub = hub.clone(); mod tests;
let id = lease.job.id;
let token = lease.token.to_string();
let digest = lease.artifact.sha256.clone();
tokio::task::spawn_blocking(move || {
let mut file = tempfile::tempfile().context("create private restore staging")?;
let size = http::get_file(
&format!("{}/api/v1/wormhole/restore/{id}/payload", hub.url),
&mut file,
&[
("x-tessera-upload-token", &hub.token),
("x-tessera-restore-token", &token),
],
timeout,
)?;
let (bytes, computed) = digest_file(&mut file)?;
ensure!(
size == bytes && computed == digest,
"restore payload checksum mismatch"
);
Ok(file)
})
.await?
}

View File

@@ -0,0 +1,863 @@
//! The restore sequence is destructive, so these tests drive `run` and `poll` with in-process fakes and
//! assert what the agent does (and above all never does) at each step. Every fake appends to one shared
//! event log so tests can assert on ordering and absence.
use super::*;
use std::{
collections::VecDeque,
io::{Read, Write},
sync::Mutex,
};
use tessera_core::restore::{RestoreArtifact, RestoreJob, RestoreTarget as JobTarget};
type Log = Arc<Mutex<Vec<String>>>;
fn identity(instance: &str, database: &str) -> DatabaseIdentity {
DatabaseIdentity {
instance: instance.into(),
database: database.into(),
}
}
fn target_identity() -> DatabaseIdentity {
identity("1", "target")
}
fn source_identity() -> DatabaseIdentity {
identity("2", "source")
}
fn lease_for(target: Uuid, application: Uuid, rollback: bool) -> RestoreLease {
RestoreLease {
job: RestoreJob {
id: Uuid::new_v4(),
snapshot_id: Uuid::new_v4(),
target: JobTarget {
id: target,
application_id: application,
outpost_id: Uuid::new_v4(),
name: "target".into(),
engine: tessera_core::restore::Engine::Postgres,
identity: target_identity(),
},
actor: "admin".into(),
status: "running".into(),
phase: "queued".into(),
safety_snapshot_id: None,
created_at: 0,
updated_at: 0,
failure_reason: None,
},
token: Uuid::new_v4(),
artifact: RestoreArtifact {
format: CaptureFormat::PostgresCustom,
// A normal restore comes from another database; a rollback comes from the target itself.
identity: if rollback {
target_identity()
} else {
source_identity()
},
sha256: "00".into(),
rollback,
},
}
}
fn lease() -> RestoreLease {
lease_for(Uuid::new_v4(), Uuid::new_v4(), false)
}
#[derive(Clone, Copy, PartialEq)]
enum Step {
Ok,
Fail,
Hang,
/// Succeeds after this many milliseconds.
Slow(u64),
}
impl Step {
async fn run(self, what: &str) -> Result<()> {
match self {
Step::Ok => Ok(()),
Step::Fail => anyhow::bail!("{what} exploded"),
Step::Hang => std::future::pending().await,
Step::Slow(ms) => {
tokio::time::sleep(Duration::from_millis(ms)).await;
Ok(())
}
}
}
}
type Answer = Result<DatabaseIdentity, &'static str>;
struct FakeTarget {
log: Log,
/// Answers for successive `identity` calls; the last one repeats.
identities: Mutex<VecDeque<Answer>>,
hang_identity: bool,
prepare: Step,
safety: Step,
apply: Step,
}
impl FakeTarget {
fn new(log: &Log) -> Self {
Self {
log: log.clone(),
identities: Mutex::new(VecDeque::from([Ok(target_identity())])),
hang_identity: false,
prepare: Step::Ok,
safety: Step::Ok,
apply: Step::Ok,
}
}
fn identities(self, answers: Vec<Answer>) -> Self {
*self.identities.lock().unwrap() = answers.into();
self
}
}
#[async_trait]
impl RestoreTarget for FakeTarget {
async fn identity(&self) -> Result<DatabaseIdentity> {
self.log.lock().unwrap().push("target.identity".into());
if self.hang_identity {
std::future::pending::<()>().await;
}
let answer = {
let mut answers = self.identities.lock().unwrap();
if answers.len() > 1 {
answers.pop_front().unwrap()
} else {
answers.front().cloned().unwrap()
}
};
answer.map_err(|why| anyhow::anyhow!(why))
}
async fn prepare(&self, mut input: File, _: &RestoreLease) -> Result<File> {
self.log.lock().unwrap().push("target.prepare".into());
self.prepare.run("prepare").await?;
let mut script = tempfile::tempfile()?;
let mut body = Vec::new();
input.read_to_end(&mut body)?;
script.write_all(&body)?;
Ok(script)
}
async fn safety(&self, _: File) -> Result<()> {
self.log.lock().unwrap().push("target.safety".into());
self.safety.run("safety dump").await
}
async fn apply(&self, _: File) -> Result<()> {
self.log.lock().unwrap().push("target.apply".into());
self.apply.run("apply").await
}
}
struct FakeSource(Answer);
#[async_trait]
impl BackupSource for FakeSource {
async fn identity(&self) -> Result<DatabaseIdentity> {
self.0.clone().map_err(|why| anyhow::anyhow!(why))
}
}
struct FakeHub {
log: Log,
/// Queue of claim replies; empty means "nothing to restore".
claims: Mutex<VecDeque<String>>,
download: Step,
upload: Step,
/// A request whose path ends with this fails (the response is "lost").
fail_path: Option<&'static str>,
/// Reports with this progress fail (used to break heartbeats).
fail_progress: Option<&'static str>,
}
impl FakeHub {
fn new(log: &Log) -> Self {
Self {
log: log.clone(),
claims: Mutex::default(),
download: Step::Ok,
upload: Step::Ok,
fail_path: None,
fail_progress: None,
}
}
}
#[async_trait]
impl RestoreHub for FakeHub {
async fn send(
&self,
path: String,
body: serde_json::Value,
restore: Option<Uuid>,
) -> Result<String> {
if path.ends_with("/claim") {
return Ok(self
.claims
.lock()
.unwrap()
.pop_front()
.unwrap_or_else(|| "null".into()));
}
if path.ends_with("/apply") {
assert!(restore.is_some(), "the apply permit needs the lease token");
self.log.lock().unwrap().push("hub.apply-permit".into());
} else {
let progress = body.as_str().unwrap_or("?").to_owned();
self.log.lock().unwrap().push(format!("report:{progress}"));
if self.fail_progress == Some(progress.as_str()) {
anyhow::bail!("hub unreachable");
}
}
if self.fail_path.is_some_and(|suffix| path.ends_with(suffix)) {
anyhow::bail!("response lost");
}
Ok(String::new())
}
async fn send_with_reason(
&self,
_: String,
body: serde_json::Value,
_: Uuid,
reason: Option<String>,
) -> Result<String> {
self.log.lock().unwrap().push(format!(
"failed:{}:{}",
body.as_str().unwrap_or("?"),
reason.unwrap_or_default()
));
Ok(String::new())
}
async fn upload_safety(&self, _: &RestoreLease, _: File, _: Duration) -> Result<()> {
self.log.lock().unwrap().push("hub.safety-upload".into());
self.upload.run("upload").await
}
async fn download(&self, _: &RestoreLease, _: Duration) -> Result<File> {
self.log.lock().unwrap().push("hub.download".into());
self.download.run("download").await?;
Ok(tempfile::tempfile()?)
}
}
const SHORT: Duration = Duration::from_millis(60);
struct Outcome {
result: Result<()>,
log: Vec<String>,
}
impl Outcome {
fn did(&self, event: &str) -> bool {
self.log.iter().any(|entry| entry == event)
}
fn failed(&self, progress: &str) -> Option<&str> {
self.log
.iter()
.find_map(|entry| entry.strip_prefix(&format!("failed:{progress}:")))
}
/// The agent never reached the destructive step.
fn never_applied(&self) -> bool {
!self.did("hub.apply-permit") && !self.did("target.apply")
}
}
async fn drive(
lease: &RestoreLease,
log: &Log,
hub: FakeHub,
target: FakeTarget,
source: Option<FakeSource>,
) -> Outcome {
let result = run(
&hub,
lease,
&target,
source.as_ref(),
SHORT,
&AtomicBool::new(false),
)
.await;
let log = log.lock().unwrap().clone();
Outcome { result, log }
}
fn log() -> Log {
Log::default()
}
#[tokio::test]
async fn full_restore_runs_in_order_and_reports_applied() {
let log = log();
let out = drive(
&lease(),
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
None,
)
.await;
out.result.as_ref().unwrap();
let steps: Vec<&str> = out
.log
.iter()
.map(String::as_str)
.filter(|entry| *entry != "target.identity")
.collect();
assert_eq!(
steps,
[
"report:checking",
"hub.download",
"target.prepare",
"report:safety",
"target.safety",
"hub.safety-upload",
"hub.apply-permit",
"target.apply",
"report:applied",
]
);
}
// ---- safety capture: nothing destructive may happen unless the safety copy is stored ----
#[tokio::test]
async fn safety_dump_failure_never_applies() {
let log = log();
let mut target = FakeTarget::new(&log);
target.safety = Step::Fail;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out.never_applied());
assert!(out
.failed("safety_failed")
.unwrap()
.contains("safety dump exploded"));
assert!(!out.did("hub.safety-upload"));
}
#[tokio::test]
async fn safety_upload_failure_never_applies() {
let log = log();
let mut hub = FakeHub::new(&log);
hub.upload = Step::Fail;
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
out.result.as_ref().unwrap();
assert!(out.never_applied());
assert!(out
.failed("safety_failed")
.unwrap()
.contains("upload exploded"));
}
#[tokio::test]
async fn target_changed_during_safety_capture_never_applies() {
let log = log();
// Verified as the expected target, then a different database answers after the dump.
let target =
FakeTarget::new(&log).identities(vec![Ok(target_identity()), Ok(source_identity())]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out.never_applied());
assert!(out
.failed("safety_failed")
.unwrap()
.contains("target changed during safety capture"));
assert!(
!out.did("hub.safety-upload"),
"a dump of the wrong database must not be stored"
);
}
#[tokio::test]
async fn target_unreachable_after_safety_capture_never_applies() {
let log = log();
let target = FakeTarget::new(&log).identities(vec![Ok(target_identity()), Err("gone")]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out.never_applied());
assert!(out.failed("safety_failed").is_some());
}
// ---- identity checks ----
#[tokio::test]
async fn identity_mismatch_refuses_before_any_dump() {
let log = log();
let target = FakeTarget::new(&log).identities(vec![Ok(identity("1", "other"))]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out
.failed("wrong_target")
.unwrap()
.contains("identity does not match"));
assert!(out.never_applied());
assert!(
!out.did("target.safety"),
"must refuse before touching the target"
);
assert!(!out.did("report:safety"));
}
#[tokio::test]
async fn identity_probe_error_is_a_wrong_target() {
let log = log();
let target = FakeTarget::new(&log).identities(vec![Err("connection refused")]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out
.failed("wrong_target")
.unwrap()
.contains("connection refused"));
assert!(out.never_applied());
}
#[tokio::test]
async fn restoring_a_backup_onto_its_own_source_database_is_refused() {
let log = log();
let mut lease = lease();
lease.artifact.identity = target_identity(); // artifact was taken from the target itself
let out = drive(
&lease,
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
None,
)
.await;
out.result.as_ref().unwrap();
assert!(out.failed("wrong_target").is_some());
assert!(out.never_applied());
}
#[tokio::test]
async fn rollback_may_restore_onto_the_database_the_copy_came_from() {
let log = log();
let lease = lease_for(Uuid::new_v4(), Uuid::new_v4(), true);
assert_eq!(lease.artifact.identity, lease.job.target.identity);
let out = drive(
&lease,
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
None,
)
.await;
out.result.as_ref().unwrap();
assert!(out.did("report:applied"));
}
#[tokio::test]
async fn rollback_still_requires_the_target_identity_to_match() {
let log = log();
let lease = lease_for(Uuid::new_v4(), Uuid::new_v4(), true);
let target = FakeTarget::new(&log).identities(vec![Ok(identity("1", "impostor"))]);
let out = drive(&lease, &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out.failed("wrong_target").is_some());
assert!(out.never_applied());
}
#[tokio::test]
async fn target_that_is_the_local_backup_source_is_refused() {
let log = log();
let source = FakeSource(Ok(target_identity()));
let out = drive(
&lease(),
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
Some(source),
)
.await;
out.result.as_ref().unwrap();
assert!(out
.failed("wrong_target")
.unwrap()
.contains("target resolves to the local backup source"));
assert!(out.never_applied());
}
#[tokio::test]
async fn a_different_local_source_does_not_block_a_restore() {
let log = log();
let source = FakeSource(Ok(source_identity()));
let out = drive(
&lease(),
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
Some(source),
)
.await;
out.result.as_ref().unwrap();
assert!(out.did("report:applied"));
}
/// Documented as designed: the source guard is best effort. If the local source cannot be identified (its
/// probe errors), the restore proceeds on the strength of the target identity checks alone.
#[tokio::test]
async fn unidentifiable_local_source_does_not_block_a_restore() {
let log = log();
let source = FakeSource(Err("source down"));
let out = drive(
&lease(),
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
Some(source),
)
.await;
out.result.as_ref().unwrap();
assert!(out.did("report:applied"));
}
// ---- per-step timeouts map to their own failure state, and never reach apply ----
#[tokio::test]
async fn download_timeout_is_invalid_payload() {
let log = log();
let mut hub = FakeHub::new(&log);
hub.download = Step::Hang;
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("invalid_payload"), Some("timed out"));
assert!(out.never_applied());
assert!(!out.did("target.safety"));
}
#[tokio::test]
async fn prepare_timeout_is_invalid_payload() {
let log = log();
let mut target = FakeTarget::new(&log);
target.prepare = Step::Hang;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("invalid_payload"), Some("timed out"));
assert!(out.never_applied());
}
#[tokio::test]
async fn prepare_error_is_invalid_payload_with_its_reason() {
let log = log();
let mut target = FakeTarget::new(&log);
target.prepare = Step::Fail;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out
.failed("invalid_payload")
.unwrap()
.contains("prepare exploded"));
assert!(out.never_applied());
}
#[tokio::test]
async fn identity_check_timeout_is_wrong_target() {
let log = log();
let mut target = FakeTarget::new(&log);
target.hang_identity = true;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("wrong_target"), Some("timed out"));
assert!(out.never_applied());
}
#[tokio::test]
async fn safety_dump_timeout_is_safety_failed() {
let log = log();
let mut target = FakeTarget::new(&log);
target.safety = Step::Hang;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("safety_failed"), Some("timed out"));
assert!(out.never_applied());
}
#[tokio::test]
async fn safety_upload_timeout_is_safety_failed() {
let log = log();
let mut hub = FakeHub::new(&log);
hub.upload = Step::Hang;
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("safety_failed"), Some("timed out"));
assert!(out.never_applied());
}
#[tokio::test]
async fn apply_timeout_is_apply_failed_after_the_permit() {
let log = log();
let mut target = FakeTarget::new(&log);
target.apply = Step::Hang;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("apply_failed"), Some("timed out"));
assert!(out.did("hub.apply-permit") && out.did("target.apply"));
assert!(!out.did("report:applied"));
}
#[tokio::test]
async fn apply_error_is_apply_failed_with_its_reason() {
let log = log();
let mut target = FakeTarget::new(&log);
target.apply = Step::Fail;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out
.failed("apply_failed")
.unwrap()
.contains("apply exploded"));
assert!(!out.did("report:applied"));
}
// ---- the permit ----
/// The permit is single-use and the agent does not retry it. If the response is lost (or the hub refuses),
/// `run` returns the error WITHOUT applying and without reporting anything further: the hub has consumed
/// (or may have consumed) the permit, so the target stays locked until the hub reconciles the lease.
#[tokio::test]
async fn lost_apply_permit_response_does_not_apply_and_leaves_the_lease_for_reconciliation() {
let log = log();
let mut hub = FakeHub::new(&log);
hub.fail_path = Some("/apply");
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
assert!(out
.result
.as_ref()
.unwrap_err()
.to_string()
.contains("response lost"));
assert!(out.did("hub.apply-permit"));
assert!(
!out.did("target.apply"),
"no permit response, no destructive step"
);
assert_eq!(out.log.last().map(String::as_str), Some("hub.apply-permit"));
assert!(out
.log
.iter()
.all(|e| !e.starts_with("failed:") && e != "report:applied"));
}
/// Agent dies (or is cancelled) after the permit but before the restore finishes. The hub has seen the
/// permit but never a terminal report, so the lease is left mid-flight for the hub to expire.
#[tokio::test]
async fn crash_between_permit_and_apply_leaves_no_terminal_report() {
let log = log();
let hub = FakeHub::new(&log);
let mut target = FakeTarget::new(&log);
target.apply = Step::Hang;
let lease = lease();
let crashed = tokio::time::timeout(
Duration::from_millis(200),
run(
&hub,
&lease,
&target,
None::<&FakeSource>,
Duration::from_secs(30),
&AtomicBool::new(false),
),
)
.await;
assert!(crashed.is_err(), "the run was dropped mid-apply");
let log = log.lock().unwrap().clone();
assert!(log.contains(&"hub.apply-permit".to_owned()));
assert!(log.contains(&"target.apply".to_owned()));
assert!(log
.iter()
.all(|e| e != "report:applied" && !e.starts_with("failed:")));
}
#[tokio::test]
async fn failure_reasons_are_cleaned_before_they_are_reported() {
let log = log();
let target = FakeTarget::new(&log).identities(vec![Err("line one\nline\ttwo \u{1F4A5}")]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("wrong_target"), Some("line one line two ?"));
}
// ---- poll ----
fn poll_fixture(
log: &Log,
lease: &RestoreLease,
target_id: Uuid,
) -> (FakeHub, HashMap<Uuid, FakeTarget>) {
let hub = FakeHub::new(log);
hub.claims
.lock()
.unwrap()
.push_back(serde_json::to_string(lease).unwrap());
let targets = HashMap::from([(target_id, FakeTarget::new(log))]);
(hub, targets)
}
#[tokio::test]
async fn poll_with_nothing_to_claim_does_nothing() {
let log = log();
let hub = FakeHub::new(&log);
let targets = HashMap::from([(Uuid::new_v4(), FakeTarget::new(&log))]);
let did = poll(
&hub,
Uuid::new_v4(),
None::<&FakeSource>,
&targets,
1,
SHORT,
)
.await
.unwrap();
assert!(!did);
assert!(log.lock().unwrap().is_empty());
}
#[tokio::test]
async fn poll_refuses_a_lease_for_another_target_or_application() {
for swap_target in [true, false] {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = if swap_target {
lease_for(Uuid::new_v4(), application, false)
} else {
lease_for(target_id, Uuid::new_v4(), false)
};
let (hub, targets) = poll_fixture(&log, &lease, target_id);
let err = poll(&hub, application, None::<&FakeSource>, &targets, 1, SHORT)
.await
.unwrap_err();
assert!(err.to_string().contains("unexpected restore target"));
assert!(
log.lock().unwrap().is_empty(),
"nothing may run for a mismatched lease"
);
}
}
#[tokio::test]
async fn poll_runs_a_matching_lease() {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = lease_for(target_id, application, false);
let (hub, targets) = poll_fixture(&log, &lease, target_id);
let did = poll(
&hub,
application,
None::<&FakeSource>,
&targets,
5,
Duration::from_secs(60),
)
.await
.unwrap();
assert!(did);
assert!(log.lock().unwrap().contains(&"report:applied".to_owned()));
}
/// Before the apply permit nothing destructive has happened, so a failed heartbeat gives up on the lease
/// (the hub will expire it) rather than carrying on unobserved.
#[tokio::test]
async fn failed_heartbeat_before_the_permit_abandons_the_restore() {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = lease_for(target_id, application, false);
let (mut hub, targets) = poll_fixture(&log, &lease, target_id);
hub.fail_progress = Some("heartbeat");
hub.download = Step::Hang;
let err = tokio::time::timeout(
Duration::from_secs(5),
poll(
&hub,
application,
None::<&FakeSource>,
&targets,
30,
Duration::from_millis(50),
),
)
.await
.expect("poll returns once the heartbeat fails")
.unwrap_err();
assert!(err.to_string().contains("hub unreachable"));
let log = log.lock().unwrap().clone();
assert!(log.contains(&"hub.download".to_owned()));
assert!(log.iter().all(|e| e != "hub.apply-permit"
&& e != "target.apply"
&& e != "report:applied"
&& !e.starts_with("failed:")));
}
/// After the permit is spent, dropping the restore would kill the apply half way (its children are
/// `kill_on_drop`). A failed heartbeat is only logged and the apply runs to its terminal report.
#[tokio::test]
async fn failed_heartbeat_after_the_permit_lets_the_apply_finish() {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = lease_for(target_id, application, false);
let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id);
hub.fail_progress = Some("heartbeat");
targets.get_mut(&target_id).unwrap().apply = Step::Slow(300);
let did = tokio::time::timeout(
Duration::from_secs(5),
poll(
&hub,
application,
None::<&FakeSource>,
&targets,
30,
Duration::from_millis(50),
),
)
.await
.expect("poll finishes")
.unwrap();
assert!(did);
let log = log.lock().unwrap().clone();
let beats = log.iter().filter(|e| *e == "report:heartbeat").count();
assert!(beats >= 2, "heartbeats kept being attempted: {beats}");
assert_eq!(log.last().map(String::as_str), Some("report:applied"));
}
/// If the apply itself fails while heartbeats are failing, the failure is still reported.
#[tokio::test]
async fn failed_apply_is_still_reported_when_heartbeats_fail() {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = lease_for(target_id, application, false);
let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id);
hub.fail_progress = Some("heartbeat");
targets.get_mut(&target_id).unwrap().apply = Step::Hang;
let err = tokio::time::timeout(
Duration::from_secs(5),
poll(
&hub,
application,
None::<&FakeSource>,
&targets,
1,
Duration::from_millis(50),
),
)
.await
.expect("apply timeout ends the poll")
.unwrap();
assert!(err);
let log = log.lock().unwrap().clone();
assert!(log.iter().any(|e| e.starts_with("failed:apply_failed:")));
}

View File

@@ -33,6 +33,9 @@ pub struct ImportArgs {
/// Reconcile counts, times and sizes without downloading or writing snapshots. /// Reconcile counts, times and sizes without downloading or writing snapshots.
#[arg(long)] #[arg(long)]
inventory_only: bool, inventory_only: bool,
/// The AWS CLI to run; a field only so tests can substitute a fake one.
#[arg(skip = PathBuf::from("aws"))]
program: PathBuf,
} }
#[derive(Clone, Copy, ValueEnum)] #[derive(Clone, Copy, ValueEnum)]
@@ -96,6 +99,12 @@ struct Report {
} }
pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> { pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
let report = reconcile(vault, args)?;
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
}
fn reconcile(vault: &Vault, args: ImportArgs) -> Result<Report> {
ensure!( ensure!(
!args.prefix.is_empty() && args.prefix.ends_with('/'), !args.prefix.is_empty() && args.prefix.ends_with('/'),
"provide a per-application prefix ending in '/'" "provide a per-application prefix ending in '/'"
@@ -173,7 +182,7 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
.map(|path| import_history(vault, path)) .map(|path| import_history(vault, path))
.transpose()? .transpose()?
}; };
let report = Report { Ok(Report {
application: args.application, application: args.application,
bucket: args.bucket, bucket: args.bucket,
prefix: args.prefix, prefix: args.prefix,
@@ -181,13 +190,11 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
bytes, bytes,
history_snapshot_id, history_snapshot_id,
objects, objects,
}; })
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
} }
fn aws(args: &ImportArgs, operation: &str) -> Command { fn aws(args: &ImportArgs, operation: &str) -> Command {
let mut cmd = Command::new("aws"); let mut cmd = Command::new(&args.program);
cmd.args([ cmd.args([
"--no-cli-pager", "--no-cli-pager",
"--no-cli-auto-prompt", "--no-cli-auto-prompt",
@@ -285,3 +292,496 @@ fn import_history(vault: &Vault, path: &std::path::Path) -> Result<Uuid> {
vault.import_legacy_payload(manifest, staged, taken_at)?; vault.import_legacy_payload(manifest, staged, taken_at)?;
Ok(id) Ok(id)
} }
/// These drive `reconcile` against a stand-in `aws` (a shell script that serves a local directory), so the
/// listing, conditional download, receipts and history paths all run for real; only S3 is faked.
#[cfg(all(test, unix))]
mod tests {
use super::*;
use serde_json::{json, Value};
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
const ETAG: &str = "\"9b2cf535f27731c974343645a3985328\"";
const WHEN: &str = "2026-01-02T03:04:05+00:00";
struct Fixture {
dir: tempfile::TempDir,
vault: Vault,
listing: Vec<Value>,
}
impl Fixture {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
let vault = Vault::init(dir.path().join("vault"), "synthetic-passphrase").unwrap();
let fake = dir.path().join("fake");
fs::create_dir_all(fake.join("obj")).unwrap();
fs::create_dir_all(fake.join("meta")).unwrap();
let script = format!(
r#"#!/bin/sh
D='{}'
op="$6"
echo "$op" >> "$D/calls"
case "$op" in
list-objects-v2)
[ -f "$D/list.fail" ] && exit 1
cat "$D/list.json" ;;
get-object)
for a in "$@"; do
last="$a"
case "$a" in --key=*) key="${{a#--key=}}" ;; esac
done
name=$(basename "$key")
[ -f "$D/get.fail.$name" ] && exit 1
cp "$D/obj/$name" "$last"
cat "$D/meta/$name.json" ;;
esac
"#,
fake.display()
);
let program = dir.path().join("aws");
fs::write(&program, script).unwrap();
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
let fixture = Self {
dir,
vault,
listing: vec![],
};
fixture.publish();
fixture
}
fn fake(&self) -> std::path::PathBuf {
self.dir.path().join("fake")
}
fn publish(&self) {
fs::write(
self.fake().join("list.json"),
json!({ "Contents": self.listing }).to_string(),
)
.unwrap();
}
/// Put an object in the listing and on the fake bucket, with matching download metadata.
fn add(&mut self, key: &str, body: &[u8]) {
self.add_listed(key, body, body.len() as u64, ETAG);
let name = key.rsplit('/').next().unwrap();
fs::write(self.fake().join("obj").join(name), body).unwrap();
self.meta(key, ETAG, body.len() as u64, WHEN);
}
/// Only the listing entry, for metadata the object itself would not match.
fn add_listed(&mut self, key: &str, _body: &[u8], size: u64, etag: &str) {
self.listing.push(json!({
"Key": key, "ETag": etag, "Size": size, "LastModified": WHEN
}));
self.publish();
}
fn meta(&self, key: &str, etag: &str, length: u64, modified: &str) {
let name = key.rsplit('/').next().unwrap();
fs::write(
self.fake().join("meta").join(format!("{name}.json")),
json!({"ETag": etag, "ContentLength": length, "LastModified": modified})
.to_string(),
)
.unwrap();
}
fn calls(&self) -> Vec<String> {
fs::read_to_string(self.fake().join("calls"))
.unwrap_or_default()
.lines()
.map(str::to_owned)
.collect()
}
fn args(&self) -> ImportArgs {
ImportArgs {
bucket: "legacy-bucket".into(),
prefix: "backups/shop/".into(),
endpoint: None,
orbit_id: Uuid::from_u128(7),
application: "shop".into(),
engine: Engine::Postgres,
history: None,
inventory_only: false,
program: self.dir.path().join("aws"),
}
}
fn run(&self, args: ImportArgs) -> Result<Report> {
reconcile(&self.vault, args)
}
fn snapshots(&self) -> usize {
self.vault.list_snapshots().unwrap().len()
}
fn receipts(&self) -> usize {
fs::read_dir(self.vault.root().join("keys/legacy-imports"))
.map(|entries| entries.count())
.unwrap_or(0)
}
}
fn gzip_header(rest: &[u8]) -> Vec<u8> {
[&[0x1f, 0x8b][..], rest].concat()
}
fn statuses(report: &Report) -> Vec<&'static str> {
report.objects.iter().map(|o| o.status).collect()
}
// ---- arguments are validated before anything is listed ----
#[test]
fn bad_arguments_are_refused_before_aws_is_run() {
let fx = Fixture::new();
type Tweak = fn(&mut ImportArgs);
let cases: [(&str, Tweak); 11] = [
("empty prefix", |a| a.prefix = String::new()),
("prefix without a trailing slash", |a| {
a.prefix = "backups/shop".into()
}),
("blank application", |a| a.application = " ".into()),
("long application", |a| a.application = "a".repeat(129)),
("control in application", |a| {
a.application = "sh\nop".into()
}),
("plain http endpoint", |a| {
a.endpoint = Some("http://s3.example.com".into())
}),
("http on another loopback port form", |a| {
a.endpoint = Some("http://localhost:9000".into())
}),
("credentials in the endpoint", |a| {
a.endpoint = Some("https://user:pw@s3.example.com".into())
}),
("query in the endpoint", |a| {
a.endpoint = Some("https://s3.example.com/?x=1".into())
}),
("fragment in the endpoint", |a| {
a.endpoint = Some("https://s3.example.com/#x".into())
}),
("newline in the endpoint", |a| {
a.endpoint = Some("https://s3.example.com/\nx".into())
}),
];
for (what, tweak) in cases {
let mut args = fx.args();
tweak(&mut args);
assert!(fx.run(args).is_err(), "{what} must be refused");
}
assert!(fx.calls().is_empty(), "aws was never run");
let mut ok = fx.args();
ok.endpoint = Some("http://127.0.0.1:9000".into());
assert!(fx.run(ok).is_ok(), "a local test endpoint is allowed");
let mut ok = fx.args();
ok.endpoint = Some("https://s3.example.com".into());
assert!(fx.run(ok).is_ok());
}
// ---- inventory ----
#[test]
fn inventory_counts_only_sql_archives_under_the_prefix_and_writes_nothing() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"select 1;");
fx.add("backups/shop/b.sql.gz", &gzip_header(b"zz"));
fx.add("backups/shop/readme.txt", b"not a dump");
fx.add("backups/shop/nested/c.sql", b"select 3;");
fx.add("backups/shop/d.sql.bak", b"select 4;");
fx.add("backups/other/e.sql", b"another application");
fx.add("backups/shopping/f.sql", b"prefix lookalike");
let mut args = fx.args();
args.inventory_only = true;
let report = fx.run(args).unwrap();
assert_eq!(report.count, 3, "a, b and nested/c");
assert_eq!(report.bytes, 9 + 4 + 9);
assert_eq!(statuses(&report), ["inventoried"; 3]);
assert!(report.history_snapshot_id.is_none());
assert_eq!(fx.snapshots(), 0);
assert_eq!(fx.receipts(), 0);
assert_eq!(fx.calls(), ["list-objects-v2"], "no object was downloaded");
}
#[test]
fn inventory_only_ignores_a_history_export() {
let fx = Fixture::new();
let history = fx.dir.path().join("history.sqlite");
fs::write(&history, b"SQLite format 3\0 rows").unwrap();
let mut args = fx.args();
args.inventory_only = true;
args.history = Some(history);
let report = fx.run(args).unwrap();
assert!(report.history_snapshot_id.is_none());
assert_eq!(fx.snapshots(), 0);
}
#[test]
fn an_empty_or_missing_listing_is_a_clean_zero() {
let fx = Fixture::new();
let report = fx.run(fx.args()).unwrap();
assert_eq!((report.count, report.bytes), (0, 0));
fs::write(fx.fake().join("list.json"), "{}").unwrap();
assert_eq!(fx.run(fx.args()).unwrap().count, 0);
}
#[test]
fn listing_failures_stop_the_run() {
let fx = Fixture::new();
fs::write(fx.fake().join("list.fail"), "").unwrap();
let err = fx.run(fx.args()).err().unwrap();
assert!(format!("{err:#}").contains("could not list"), "{err:#}");
fs::remove_file(fx.fake().join("list.fail")).unwrap();
for broken in [
"",
"not json",
r#"{"Contents":[{"Key":"x"}]}"#,
r#"{"Contents":"x"}"#,
] {
fs::write(fx.fake().join("list.json"), broken).unwrap();
assert!(fx.run(fx.args()).is_err(), "listing {broken:?}");
}
let missing = ImportArgs {
program: fx.dir.path().join("no-such-aws"),
..fx.args()
};
assert!(fx.run(missing).is_err(), "no aws binary is an error");
assert_eq!(fx.snapshots(), 0);
}
#[test]
fn untrustworthy_inventory_metadata_is_refused() {
for (size, etag) in [(0, ETAG), (5, ""), (5, "*")] {
let mut fx = Fixture::new();
fx.add_listed("backups/shop/a.sql", b"", size, etag);
let err = fx.run(fx.args()).err().unwrap();
assert!(
format!("{err:#}").contains("invalid legacy archive metadata"),
"size {size} etag {etag:?}: {err:#}"
);
assert_eq!(fx.snapshots(), 0);
}
}
#[test]
fn an_inventory_whose_sizes_overflow_is_refused() {
let mut fx = Fixture::new();
fx.add_listed("backups/shop/a.sql", b"", u64::MAX, ETAG);
fx.add_listed("backups/shop/b.sql", b"", 2, "\"other\"");
let mut args = fx.args();
args.inventory_only = true;
let err = fx.run(args).err().unwrap();
assert!(format!("{err:#}").contains("overflow"), "{err:#}");
}
// ---- import ----
#[test]
fn importing_stores_each_archive_once_and_a_rerun_changes_nothing() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
fx.add("backups/shop/b.sql.gz", &gzip_header(b"compressed"));
let first = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&first), ["imported", "imported"]);
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
let stored = fx
.vault
.get_snapshot(first.objects[0].snapshot_id)
.unwrap()
.expect("stored under the reported id");
assert_eq!(stored.manifest.orbit_id, Uuid::from_u128(7));
assert_eq!(stored.manifest.orbit_name, "shop");
assert_eq!(stored.manifest.provider, "postgres");
assert_eq!(stored.manifest.labels, ["legacy-import"]);
assert_eq!(stored.manifest.restore_hints["format"], "plain");
assert_eq!(stored.manifest.restore_hints["legacy"]["etag"], ETAG);
let gz = fx
.vault
.get_snapshot(first.objects[1].snapshot_id)
.unwrap()
.unwrap();
assert_eq!(gz.manifest.restore_hints["format"], "sql_gzip");
assert_eq!(
stored.taken_at,
"2026-01-02T03:04:05Z".parse::<DateTime<Utc>>().unwrap(),
"the snapshot keeps the original time, not the import time"
);
let calls_before = fx.calls().len();
let second = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&second), ["already_imported", "already_imported"]);
assert_eq!(
fx.calls().len(),
calls_before + 1,
"the rerun listed but downloaded nothing"
);
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
assert_eq!(
first.objects[0].snapshot_id, second.objects[0].snapshot_id,
"ids are derived, so a rerun finds its own work"
);
}
#[test]
fn the_engine_orbit_and_endpoint_decide_the_mysql_manifest_and_the_snapshot_id() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
let mut mysql = fx.args();
mysql.engine = Engine::Mysql;
let first = fx.run(mysql).unwrap();
let stored = fx
.vault
.get_snapshot(first.objects[0].snapshot_id)
.unwrap()
.unwrap();
assert_eq!(stored.manifest.provider, "mysql");
// another orbit is a different import of the same bytes, not a duplicate
let mut other = fx.args();
other.orbit_id = Uuid::from_u128(8);
let second = fx.run(other).unwrap();
assert_ne!(first.objects[0].snapshot_id, second.objects[0].snapshot_id);
assert_eq!(statuses(&second), ["imported"]);
// so is another endpoint
let mut elsewhere = fx.args();
elsewhere.endpoint = Some("https://s3.example.com".into());
let third = fx.run(elsewhere).unwrap();
assert_ne!(first.objects[0].snapshot_id, third.objects[0].snapshot_id);
assert_eq!(fx.snapshots(), 3);
}
#[test]
fn an_object_that_changed_since_the_inventory_is_not_imported() {
for (what, etag, length, modified) in [
("etag", "\"changed\"", 17, WHEN),
("length", ETAG, 18, WHEN),
("time", ETAG, 17, "2026-01-02T03:04:06+00:00"),
] {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
fx.meta("backups/shop/a.sql", etag, length, modified);
let err = fx.run(fx.args()).err().unwrap();
assert!(
format!("{err:#}").contains("changed since inventory"),
"{what}: {err:#}"
);
assert_eq!((fx.snapshots(), fx.receipts()), (0, 0), "{what}");
}
}
#[test]
fn a_downloaded_file_of_the_wrong_size_is_not_imported() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
// the metadata agrees with the listing but fewer bytes arrived
fs::write(fx.fake().join("obj/a.sql"), b"create").unwrap();
let err = fx.run(fx.args()).err().unwrap();
assert!(format!("{err:#}").contains("changed since inventory"));
assert_eq!(fx.snapshots(), 0);
}
#[test]
fn a_gzip_named_archive_must_start_with_the_gzip_signature() {
let mut fx = Fixture::new();
fx.add("backups/shop/b.sql.gz", b"plainly not gzip");
let err = fx.run(fx.args()).err().unwrap();
assert!(format!("{err:#}").contains("gzip header"), "{err:#}");
assert_eq!((fx.snapshots(), fx.receipts()), (0, 0));
// a one-byte file cannot even hold the signature
let mut tiny = Fixture::new();
tiny.add("backups/shop/t.sql.gz", &[0x1f]);
assert!(tiny.run(tiny.args()).is_err());
assert_eq!(tiny.snapshots(), 0);
}
#[test]
fn a_plain_sql_archive_is_not_inspected_for_a_signature() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", &gzip_header(b"gz bytes in a .sql"));
let report = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&report), ["imported"]);
}
#[test]
fn a_failed_download_stops_the_run_and_a_retry_resumes_where_it_left_off() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
fx.add("backups/shop/b.sql", b"create table b();");
fs::write(fx.fake().join("get.fail.b.sql"), "").unwrap();
let err = fx.run(fx.args()).err().unwrap();
assert!(format!("{err:#}").contains("download failed"), "{err:#}");
assert_eq!((fx.snapshots(), fx.receipts()), (1, 1), "a was kept");
fs::remove_file(fx.fake().join("get.fail.b.sql")).unwrap();
let retry = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&retry), ["already_imported", "imported"]);
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
}
#[test]
fn a_receipt_keeps_an_archive_from_returning_after_its_snapshot_is_forgotten() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
let first = fx.run(fx.args()).unwrap();
let id = first.objects[0].snapshot_id;
assert!(fx.vault.legacy_import_exists(id).unwrap());
fx.vault.forget(&[id]).unwrap();
assert_eq!(fx.snapshots(), 0);
let again = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&again), ["already_imported"]);
assert_eq!(fx.snapshots(), 0, "retention's decision is not undone");
}
// ---- the operator-history export ----
#[test]
fn a_history_export_must_be_a_sqlite_file() {
let fx = Fixture::new();
let write = |name: &str, bytes: &[u8]| {
let path = fx.dir.path().join(name);
fs::write(&path, bytes).unwrap();
path
};
for (name, bytes) in [
("empty", &b""[..]),
("short", b"SQLite"),
("text", b"just a text file, long enough to read"),
("near", b"SQLite format 3 not-nul-terminated"),
("wal", b"SQLite format 4\0 later version"),
] {
let mut args = fx.args();
args.history = Some(write(name, bytes));
assert!(fx.run(args).is_err(), "{name} must be refused");
}
let mut missing = fx.args();
missing.history = Some(Path::new("/definitely/not/here.sqlite").into());
assert!(fx.run(missing).is_err());
assert_eq!(fx.snapshots(), 0);
}
#[test]
fn a_history_export_is_stored_once_and_identified_by_its_content() {
let fx = Fixture::new();
let path = fx.dir.path().join("history.sqlite");
fs::write(&path, b"SQLite format 3\0 first export").unwrap();
let mut args = fx.args();
args.history = Some(path.clone());
let first = fx.run(args.clone()).unwrap();
let id = first.history_snapshot_id.expect("history imported");
assert_eq!(fx.snapshots(), 1);
let stored = fx.vault.get_snapshot(id).unwrap().unwrap();
assert_eq!(stored.manifest.provider, "legacy-history");
assert_eq!(stored.manifest.orbit_id, Uuid::nil());
assert_eq!(stored.manifest.restore_hints["format"], "sqlite");
// same bytes: same snapshot, nothing new stored
let second = fx.run(args.clone()).unwrap();
assert_eq!(second.history_snapshot_id, Some(id));
assert_eq!(fx.snapshots(), 1);
// different bytes: a different snapshot
fs::write(&path, b"SQLite format 3\0 second export").unwrap();
let third = fx.run(args).unwrap();
assert_ne!(third.history_snapshot_id, Some(id));
assert_eq!(fx.snapshots(), 2);
}
}

View File

@@ -441,4 +441,398 @@ mod tests {
assert!(manifest.is_restore_safety()); assert!(manifest.is_restore_safety());
assert_eq!(manifest.safety_target().as_deref(), Some("t")); assert_eq!(manifest.safety_target().as_deref(), Some("t"));
} }
// ---- boundaries ----
fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32, sec: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(y, mo, d, h, mi, sec).unwrap()
}
fn snap(taken_at: DateTime<Utc>) -> SnapshotRef {
SnapshotRef {
id: Uuid::new_v4(),
taken_at,
}
}
#[test]
fn capture_age_boundary_is_a_whole_number_of_days() {
let now = at(2026, 11, 20, 12, 0, 0);
let newest = snap(now);
let exactly = snap(now - Duration::days(14));
let just_under = snap(now - Duration::days(14) + Duration::seconds(1));
let policy = CaptureRetention::Age { days: 14 };
let forgotten = evaluate_capture_retention(
policy,
vec![just_under.clone(), exactly.clone(), newest.clone()],
now,
);
assert_eq!(forgotten, [exactly.id], "14 days old to the second goes");
}
#[test]
fn capture_retention_never_forgets_the_newest_even_when_ancient_or_in_the_future() {
let now = at(2026, 11, 20, 12, 0, 0);
for policy in [
CaptureRetention::Age { days: 1 },
CaptureRetention::Count { keep: 1 },
] {
let only = snap(now - Duration::days(4000));
assert!(evaluate_capture_retention(policy, vec![only], now).is_empty());
// a snapshot stamped in the future (clock skew) has negative age and is never expired
let future = snap(now + Duration::days(3));
let old = snap(now - Duration::days(30));
assert_eq!(
evaluate_capture_retention(policy, vec![old.clone(), future], now),
[old.id]
);
}
assert!(evaluate_capture_retention(CaptureRetention::default(), vec![], now).is_empty());
}
#[test]
fn capture_count_boundaries() {
let now = at(2026, 11, 20, 12, 0, 0);
let snaps: Vec<_> = (0..4).map(|i| snap(now - Duration::hours(i))).collect();
let count = |keep| {
evaluate_capture_retention(CaptureRetention::Count { keep }, snaps.clone(), now).len()
};
assert_eq!(count(1), 3);
assert_eq!(count(3), 1);
assert_eq!(count(4), 0, "keeping exactly as many as exist forgets none");
assert_eq!(count(u16::MAX), 0);
// keep 0 is rejected by validation, but must still not forget the newest if it slips through
assert!(!CaptureRetention::Count { keep: 0 }.is_valid());
assert!(!CaptureRetention::Age { days: 0 }.is_valid());
let forgotten =
evaluate_capture_retention(CaptureRetention::Count { keep: 0 }, snaps.clone(), now);
assert!(!forgotten.contains(&snaps[0].id));
}
#[test]
fn equal_timestamps_are_ordered_by_id_so_the_outcome_is_deterministic() {
let now = at(2026, 11, 20, 12, 0, 0);
let mut twins = vec![snap(now), snap(now), snap(now)];
let keep_one = CaptureRetention::Count { keep: 1 };
let first = evaluate_capture_retention(keep_one, twins.clone(), now);
twins.reverse();
let second = evaluate_capture_retention(keep_one, twins, now);
assert_eq!(set(&first), set(&second));
assert_eq!(first.len(), 2);
}
#[test]
fn safety_age_boundary_is_seven_whole_days() {
let now = at(2026, 11, 30, 12, 0, 0);
let copy = |age: Duration| SafetyRef {
id: Uuid::new_v4(),
taken_at: now - age,
target: "t".into(),
};
// three fresh copies fill the per-target quota, so age alone decides for the next two
let pad: Vec<_> = (1..=3).map(|i| copy(Duration::hours(i))).collect();
let exactly_seven = copy(Duration::days(7));
let just_under = copy(Duration::days(7) - Duration::seconds(1));
let forgotten = evaluate_safety_retention(
pad.into_iter()
.chain([exactly_seven.clone(), just_under.clone()])
.collect(),
now,
);
assert_eq!(
forgotten,
[exactly_seven.id],
"exactly 7 days old is no longer recent; one second less still is"
);
}
#[test]
fn safety_retention_handles_empty_and_a_lone_ancient_copy() {
let now = at(2030, 1, 1, 0, 0, 0);
assert!(evaluate_safety_retention(vec![], now).is_empty());
assert!(evaluate_safety_retention(vec![safety(1, "only")], now).is_empty());
}
#[test]
fn gfs_period_boundaries_are_utc_midnight_iso_weeks_and_calendar_years() {
let daily = RetentionPolicy {
keep_daily: 2,
..Default::default()
};
let last_second = snap(at(2025, 12, 31, 23, 59, 59));
let first_second = snap(at(2026, 1, 1, 0, 0, 0));
let earlier = snap(at(2025, 12, 31, 0, 0, 0));
// 23:59:59 and 00:00:00 straddle a day, so both days count and each keeps its newest
assert_eq!(
evaluate_gfs(
&daily,
vec![earlier.clone(), last_second.clone(), first_second.clone()]
),
[earlier.id]
);
// ISO weeks: Sun 2024-12-29 is week 52; Mon 2024-12-30 and Wed 2025-01-01 are week 1 of 2025
let weekly = RetentionPolicy {
keep_weekly: 2,
..Default::default()
};
let sunday = snap(at(2024, 12, 29, 12, 0, 0));
let monday = snap(at(2024, 12, 30, 0, 0, 0));
let wednesday = snap(at(2025, 1, 1, 12, 0, 0));
assert_eq!(
evaluate_gfs(&weekly, vec![sunday, monday.clone(), wednesday]),
[monday.id]
);
// ISO week 53 of 2020 spans the new year
let a = snap(at(2020, 12, 31, 1, 0, 0));
let b = snap(at(2021, 1, 1, 1, 0, 0));
let one_week = RetentionPolicy {
keep_weekly: 1,
..Default::default()
};
assert_eq!(evaluate_gfs(&one_week, vec![a.clone(), b]), [a.id]);
let yearly = RetentionPolicy {
keep_yearly: 1,
..Default::default()
};
assert_eq!(
evaluate_gfs(&yearly, vec![first_second.clone(), last_second.clone()]),
[last_second.id]
);
// the same month number in another year is a different month
let monthly = RetentionPolicy {
keep_monthly: 2,
..Default::default()
};
let jan25 = snap(at(2025, 1, 15, 0, 0, 0));
let jan26 = snap(at(2026, 1, 15, 0, 0, 0));
let jan26_early = snap(at(2026, 1, 2, 0, 0, 0));
assert_eq!(
evaluate_gfs(&monthly, vec![jan25, jan26, jan26_early.clone()]),
[jan26_early.id]
);
}
#[test]
fn gfs_edge_inputs() {
let all_tiers = RetentionPolicy {
keep_daily: 3,
keep_weekly: 3,
keep_monthly: 3,
keep_yearly: 3,
};
assert!(evaluate_gfs(&all_tiers, vec![]).is_empty());
assert!(evaluate_gfs(&all_tiers, vec![snap(at(2020, 2, 29, 0, 0, 0))]).is_empty());
// all tiers zero means no policy, which keeps everything rather than forgetting everything
let many: Vec<_> = (1..=5).map(|d| snap(at(2026, 1, d, 0, 0, 0))).collect();
assert!(evaluate_gfs(&RetentionPolicy::default(), many.clone()).is_empty());
let huge = RetentionPolicy {
keep_daily: u32::MAX,
keep_weekly: u32::MAX,
keep_monthly: u32::MAX,
keep_yearly: u32::MAX,
};
assert!(evaluate_gfs(&huge, many).is_empty());
}
// ---- properties, over seeded pseudo-random histories (no extra dependency) ----
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
}
fn history(rng: &mut Rng, now: DateTime<Utc>) -> Vec<SnapshotRef> {
let n = rng.below(60);
(0..n)
.map(|_| {
// about three years at second resolution, with some collisions on whole hours
let secs = rng.below(3 * 365 * 86_400) as i64;
let secs = if rng.below(4) == 0 {
secs - secs % 3600
} else {
secs
};
snap(now - Duration::seconds(secs))
})
.collect()
}
fn random_policy(rng: &mut Rng) -> RetentionPolicy {
RetentionPolicy {
keep_daily: rng.below(10) as u32,
keep_weekly: rng.below(10) as u32,
keep_monthly: rng.below(14) as u32,
keep_yearly: rng.below(5) as u32,
}
}
fn survivors(all: &[SnapshotRef], forgotten: &[Uuid]) -> Vec<SnapshotRef> {
all.iter()
.filter(|s| !forgotten.contains(&s.id))
.cloned()
.collect()
}
fn shuffled(rng: &mut Rng, mut v: Vec<SnapshotRef>) -> Vec<SnapshotRef> {
for i in (1..v.len()).rev() {
v.swap(i, rng.below(i as u64 + 1) as usize);
}
v
}
fn set(ids: &[Uuid]) -> HashSet<Uuid> {
ids.iter().copied().collect()
}
fn newest(all: &[SnapshotRef]) -> Option<&SnapshotRef> {
all.iter().max_by_key(|s| (s.taken_at, s.id))
}
#[test]
fn gfs_properties_hold_for_random_histories() {
let now = at(2026, 11, 20, 12, 0, 0);
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
for _ in 0..400 {
let all = history(&mut rng, now);
let policy = random_policy(&mut rng);
let forgotten = evaluate_gfs(&policy, all.clone());
let ids: Vec<_> = all.iter().map(|s| s.id).collect();
// only names snapshots it was given, each at most once
assert!(set(&forgotten).is_subset(&set(&ids)));
assert_eq!(set(&forgotten).len(), forgotten.len());
// the newest survives whenever any tier is switched on
if policy.has_tiers() {
if let Some(newest) = newest(&all) {
assert!(!forgotten.contains(&newest.id), "{policy:?}");
}
} else {
assert!(forgotten.is_empty());
}
// input order is irrelevant
let again = evaluate_gfs(&policy, shuffled(&mut rng, all.clone()));
assert_eq!(set(&forgotten), set(&again));
// applying the policy to what is left forgets nothing more
let left = survivors(&all, &forgotten);
assert!(evaluate_gfs(&policy, left).is_empty(), "{policy:?}");
// keeping more of any tier never forgets more
let wider = RetentionPolicy {
keep_daily: policy.keep_daily + rng.below(3) as u32,
keep_weekly: policy.keep_weekly + rng.below(3) as u32,
keep_monthly: policy.keep_monthly + rng.below(3) as u32,
keep_yearly: policy.keep_yearly + rng.below(3) as u32,
};
assert!(set(&evaluate_gfs(&wider, all)).is_subset(&set(&forgotten)));
}
}
#[test]
fn capture_retention_properties_hold_for_random_histories() {
let now = at(2026, 11, 20, 12, 0, 0);
let mut rng = Rng(0xD1B5_4A32_D192_ED03);
for _ in 0..400 {
let all = history(&mut rng, now);
let policy = if rng.below(2) == 0 {
CaptureRetention::Age {
days: 1 + rng.below(400) as u16,
}
} else {
CaptureRetention::Count {
keep: 1 + rng.below(20) as u16,
}
};
let forgotten = evaluate_capture_retention(policy, all.clone(), now);
assert_eq!(set(&forgotten).len(), forgotten.len());
if let Some(newest) = newest(&all) {
assert!(!forgotten.contains(&newest.id));
}
let left = survivors(&all, &forgotten);
assert!(evaluate_capture_retention(policy, left, now).is_empty());
let again = evaluate_capture_retention(policy, shuffled(&mut rng, all.clone()), now);
assert_eq!(set(&forgotten), set(&again));
if let CaptureRetention::Count { keep } = policy {
assert_eq!(
all.len() - forgotten.len(),
all.len().min(usize::from(keep))
);
}
}
}
#[test]
fn safety_retention_properties_hold_for_random_histories() {
let now = at(2026, 11, 30, 12, 0, 0);
let mut rng = Rng(0x2545_F491_4F6C_DD1D);
for _ in 0..400 {
let all: Vec<SafetyRef> = (0..rng.below(30))
.map(|_| SafetyRef {
id: Uuid::new_v4(),
taken_at: now - Duration::seconds(rng.below(60 * 86_400) as i64),
target: format!("t{}", rng.below(3)),
})
.collect();
let forgotten = evaluate_safety_retention(all.clone(), now);
assert_eq!(set(&forgotten).len(), forgotten.len());
for copy in all.iter().filter(|c| forgotten.contains(&c.id)) {
// forgotten means old AND outside its target's newest three
assert!(now.signed_duration_since(copy.taken_at).num_days() >= SAFETY_KEEP_DAYS);
let newer = all
.iter()
.filter(|o| {
o.target == copy.target && (o.taken_at, o.id) > (copy.taken_at, copy.id)
})
.count();
assert!(newer >= SAFETY_KEEP_PER_TARGET);
}
for target in ["t0", "t1", "t2"] {
let newest = all
.iter()
.filter(|c| c.target == target)
.max_by_key(|c| (c.taken_at, c.id));
if let Some(newest) = newest {
assert!(!forgotten.contains(&newest.id));
}
}
let left: Vec<_> = all
.iter()
.filter(|c| !forgotten.contains(&c.id))
.cloned()
.collect();
assert!(evaluate_safety_retention(left, now).is_empty());
}
}
#[test]
fn legacy_decay_properties_hold_for_random_histories() {
let now = at(2026, 11, 20, 12, 0, 0);
let mut rng = Rng(0xA076_1D64_78BD_642F);
for _ in 0..400 {
let all = history(&mut rng, now);
let policy = DecayPolicy {
keep_daily: rng.below(10) as usize,
keep_weekly: rng.below(8) as usize,
keep_monthly: rng.below(14) as usize,
};
let forgotten = evaluate_decay(&policy, all.clone());
assert_eq!(set(&forgotten).len(), forgotten.len());
let ids: Vec<_> = all.iter().map(|s| s.id).collect();
assert!(set(&forgotten).is_subset(&set(&ids)));
if policy.keep_daily + policy.keep_weekly + policy.keep_monthly > 0 {
if let Some(newest) = newest(&all) {
assert!(!forgotten.contains(&newest.id));
}
}
let left = survivors(&all, &forgotten);
assert!(evaluate_decay(&policy, left).is_empty());
}
}
} }

View File

@@ -16,6 +16,9 @@ impl AdminGate {
.ok() .ok()
.map(|value| value.trim().to_string()) .map(|value| value.trim().to_string())
.filter(|value| !value.is_empty()); .filter(|value| !value.is_empty());
if let Some(token) = &token {
check_token_strength(token)?;
}
let local_development = match std::env::var("TESSERA_LOCAL_DEVELOPMENT").as_deref() { let local_development = match std::env::var("TESSERA_LOCAL_DEVELOPMENT").as_deref() {
Ok("1" | "true") => true, Ok("1" | "true") => true,
Ok("0" | "false" | "") | Err(std::env::VarError::NotPresent) => false, Ok("0" | "false" | "") | Err(std::env::VarError::NotPresent) => false,
@@ -99,6 +102,22 @@ impl AdminGate {
} }
} }
/// Shortest shared admin token the hub will start with.
pub const MIN_ADMIN_TOKEN_LEN: usize = 32;
fn check_token_strength(token: &str) -> anyhow::Result<()> {
anyhow::ensure!(
token.chars().count() >= MIN_ADMIN_TOKEN_LEN,
"TESSERA_ADMIN_TOKEN must be at least {MIN_ADMIN_TOKEN_LEN} characters (for example `openssl rand -hex 32`)"
);
Ok(())
}
/// True when the request carries an admin token (in either header).
pub(crate) fn presents_token(headers: &HeaderMap) -> bool {
presented_token(headers).is_some()
}
fn presented_token(headers: &HeaderMap) -> Option<&str> { fn presented_token(headers: &HeaderMap) -> Option<&str> {
if let Some(value) = headers if let Some(value) = headers
.get("x-tessera-admin-token") .get("x-tessera-admin-token")
@@ -152,6 +171,13 @@ mod tests {
SocketAddr::new(ip, 9) SocketAddr::new(ip, 9)
} }
#[test]
fn short_admin_tokens_are_refused() {
assert!(check_token_strength("short").is_err());
assert!(check_token_strength(&"x".repeat(31)).is_err());
assert!(check_token_strength(&"x".repeat(32)).is_ok());
}
#[test] #[test]
fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() { fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() {
let gate = AdminGate { let gate = AdminGate {
@@ -266,8 +292,6 @@ pub struct BrowserSession {
pub id: uuid::Uuid, pub id: uuid::Uuid,
pub csrf: String, pub csrf: String,
pub actor: String, pub actor: String,
/// Read by per-user revoke and the OIDC login path (M3/M5).
#[allow(dead_code)]
pub user_id: String, pub user_id: String,
pub auth_method: String, pub auth_method: String,
/// May use the management API. A signed-in user without a grant is `false`. /// May use the management API. A signed-in user without a grant is `false`.

View File

@@ -148,7 +148,7 @@ async fn world() -> World {
async fn world_with(exports: Option<crate::exports::ExportGate>) -> World { async fn world_with(exports: Option<crate::exports::ExportGate>) -> World {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
if let Some(gate) = exports { if let Some(gate) = exports {

View File

@@ -33,8 +33,10 @@ fn every_registered_path_has_an_authorization_contract() {
#[tokio::test] #[tokio::test]
async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() { async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = let mut state = crate::state::HubState::bootstrap(
crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") dir.path().to_str().unwrap(),
"synthetic-vault-passphrase",
)
.await .await
.unwrap(); .unwrap();
state.sessions = crate::admin::SessionGate::fixture(state.db.clone()); state.sessions = crate::admin::SessionGate::fixture(state.db.clone());
@@ -44,6 +46,8 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
.db .db
.insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture"); .insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture");
let app = router(state); let app = router(state);
// each request comes from its own source so the wrong-token throttle does not mask the 401s
let mut source = 0u32;
for row in CONTRACT.lines().filter(|line| line.starts_with("| /")) { for row in CONTRACT.lines().filter(|line| line.starts_with("| /")) {
let fields: Vec<_> = row.split('|').map(str::trim).collect(); let fields: Vec<_> = row.split('|').map(str::trim).collect();
if fields[3] != "human" || !fields[2].split(',').any(|method| method == "GET") { if fields[3] != "human" || !fields[2].split(',').any(|method| method == "GET") {
@@ -51,9 +55,14 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
} }
let path = fields[1].replace(":id", "00000000-0000-0000-0000-000000000001"); let path = fields[1].replace(":id", "00000000-0000-0000-0000-000000000001");
for token in [None, Some("synthetic-outpost")] { for token in [None, Some("synthetic-outpost")] {
let mut request = Request::builder() source += 1;
let mut request =
Request::builder()
.uri(&path) .uri(&path)
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap())); .extension(ConnectInfo(SocketAddr::from((
[10, 0, (source >> 8) as u8, source as u8],
9000,
))));
if let Some(token) = token { if let Some(token) = token {
request = request request = request
.header(header::AUTHORIZATION, format!("Bearer {token}")) .header(header::AUTHORIZATION, format!("Bearer {token}"))
@@ -76,8 +85,10 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
#[tokio::test] #[tokio::test]
async fn local_proxy_never_enables_auth_when_credentials_are_absent() { async fn local_proxy_never_enables_auth_when_credentials_are_absent() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = let mut state = crate::state::HubState::bootstrap(
crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") dir.path().to_str().unwrap(),
"synthetic-vault-passphrase",
)
.await .await
.unwrap(); .unwrap();
state.admin = crate::admin::AdminGate { state.admin = crate::admin::AdminGate {

View File

@@ -22,7 +22,7 @@ struct Harness {
async fn harness_with(configure: impl FnOnce(&mut HubState)) -> Harness { async fn harness_with(configure: impl FnOnce(&mut HubState)) -> Harness {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some(ADMIN.into()); state.admin.token = Some(ADMIN.into());
@@ -582,3 +582,275 @@ async fn sso_endpoints_are_rate_limited_per_source() {
); );
assert!(h.state.limits.oidc_login_allowed(other)); assert!(h.state.limits.oidc_login_allowed(other));
} }
// ---- pairing, the ways it must say no ----
const START: &str = "/api/v1/wormhole/pairing";
const CLAIM: &str = "/api/v1/wormhole/claim";
/// A different source address each time, so the per-source claim limit does not interfere.
fn fresh_peer() -> String {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
format!("192.0.{}.{}", (n >> 8) & 255, n & 255)
}
impl Harness {
async fn start_code(&self) -> String {
let start = self
.call(request("POST", START, "127.0.0.1", Some(ADMIN), None))
.await;
assert_eq!(start.status(), StatusCode::OK);
json_of(start).await["code"].as_str().unwrap().to_string()
}
async fn claim(&self, _peer: &str, body: Value) -> Response<Body> {
self.call(request("POST", CLAIM, &fresh_peer(), None, Some(body)))
.await
}
fn outposts(&self) -> i64 {
self.scalar("SELECT COUNT(*) FROM outposts")
}
fn credentials(&self) -> i64 {
self.scalar("SELECT COUNT(*) FROM outpost_credentials")
}
}
#[tokio::test]
async fn only_an_admin_can_start_a_pairing() {
let h = harness().await;
for auth in [None, Some("wrong-token"), Some("")] {
let status = h
.status(request("POST", START, "127.0.0.1", auth, None))
.await;
assert!(
status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN,
"{auth:?} must not start a pairing, got {status}"
);
}
// a paired agent's upload token is not an operator credential either
let (_, token) = h.pair("agent").await;
let status = h
.status(as_outpost(
request("POST", START, "198.51.100.20", None, None),
&token,
))
.await;
assert!(
status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN,
"an outpost token must not start a pairing, got {status}"
);
let codes: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes WHERE consumed_at IS NULL");
assert_eq!(codes, 0, "a refused request leaves no code behind");
}
#[tokio::test]
async fn a_started_code_is_twelve_unambiguous_characters_valid_for_about_ten_minutes() {
let h = harness().await;
let start = h
.call(request("POST", START, "127.0.0.1", Some(ADMIN), None))
.await;
let body = json_of(start).await;
let code = body["code"].as_str().unwrap();
assert_eq!(code.len(), 12);
assert!(
code.chars()
.all(|c| "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".contains(c)),
"no 0/O/1/I lookalikes: {code}"
);
let expires = chrono::DateTime::parse_from_rfc3339(body["expires_at"].as_str().unwrap())
.unwrap()
.timestamp();
let in_secs = expires - chrono::Utc::now().timestamp();
assert!((595..=600).contains(&in_secs), "expires in {in_secs}s");
assert_ne!(code, h.start_code().await, "codes are not repeated");
}
#[tokio::test]
async fn a_claim_that_is_refused_creates_no_outpost_and_no_credential() {
let h = harness().await;
let code = h.start_code().await;
let lower = code.to_lowercase();
let spaced = format!(" {code} ");
let truncated = code[..11].to_string();
for wrong in [
lower.as_str(),
spaced.as_str(),
truncated.as_str(),
"",
"AAAAAAAAAAAA",
"'; DROP TABLE pairing_codes;--",
] {
let response = h
.claim("198.51.100.20", json!({"code": wrong, "outpost_name": "x"}))
.await;
assert_eq!(response.status(), StatusCode::GONE, "code {wrong:?}");
}
assert_eq!((h.outposts(), h.credentials()), (0, 0));
let failed: i64 = h.scalar(
"SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'",
);
assert_eq!(failed, 6, "every refusal is audited");
let leaked: i64 = h.scalar(&format!(
"SELECT COUNT(*) FROM audit_events WHERE actor_id||action||coalesce(resource_id,'') LIKE '%{code}%'"
));
assert_eq!(leaked, 0, "the code is never written to the audit log");
// the real code still works afterwards: wrong guesses do not burn it
let ok = h
.claim(
"198.51.100.20",
json!({"code": code, "outpost_name": "real"}),
)
.await;
assert_eq!(ok.status(), StatusCode::OK);
}
#[tokio::test]
async fn a_claim_with_a_bad_name_is_refused_before_the_code_is_spent() {
let h = harness().await;
let code = h.start_code().await;
let too_long = "n".repeat(129);
for name in [
"",
" ",
"\t\n",
"tab\there",
"nul\u{0}byte",
too_long.as_str(),
] {
let response = h
.claim("198.51.100.20", json!({"code": code, "outpost_name": name}))
.await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "name {name:?}");
}
assert_eq!(h.outposts(), 0);
let longest = "n".repeat(128);
let ok = h
.claim(
"198.51.100.20",
json!({"code": code, "outpost_name": longest}),
)
.await;
assert_eq!(ok.status(), StatusCode::OK, "128 characters is allowed");
assert_eq!(h.outposts(), 1);
}
#[tokio::test]
async fn malformed_claims_are_client_errors_and_never_touch_a_code() {
let h = harness().await;
let code = h.start_code().await;
for body in [
json!({}),
json!({"code": code}),
json!({"outpost_name": "x"}),
json!({"code": 12345, "outpost_name": "x"}),
json!({"code": null, "outpost_name": "x"}),
json!({"code": ["a"], "outpost_name": "x"}),
] {
let status = h.claim("198.51.100.20", body.clone()).await.status();
assert!(
status.is_client_error() && status != StatusCode::GONE,
"{body} gave {status}"
);
}
let good = format!(r#"{{"code":"{code}","outpost_name":"x"}}"#);
let raw = |content_type: Option<&str>, body: &str| {
let mut builder = Request::builder()
.method("POST")
.uri(CLAIM)
.extension(ConnectInfo(
format!("{}:4000", fresh_peer())
.parse::<SocketAddr>()
.unwrap(),
));
if let Some(content_type) = content_type {
builder = builder.header(header::CONTENT_TYPE, content_type);
}
builder.body(Body::from(body.to_string())).unwrap()
};
for request in [
raw(Some("application/json"), "{not json"),
raw(None, &good),
raw(Some("text/plain"), &good),
] {
let status = h.status(request).await;
assert!(status.is_client_error(), "got {status}");
}
assert_eq!((h.outposts(), h.credentials()), (0, 0));
let ok = h
.claim("198.51.100.20", json!({"code": code, "outpost_name": "x"}))
.await;
assert_eq!(
ok.status(),
StatusCode::OK,
"the code survived every bad request"
);
}
#[tokio::test]
async fn an_enormous_code_is_refused_without_trouble() {
let h = harness().await;
let huge = "A".repeat(1 << 20);
let status = h
.claim("198.51.100.20", json!({"code": huge, "outpost_name": "x"}))
.await
.status();
assert!(
status == StatusCode::GONE || status == StatusCode::PAYLOAD_TOO_LARGE,
"got {status}"
);
assert_eq!((h.outposts(), h.credentials()), (0, 0));
}
#[tokio::test]
async fn a_claimed_code_cannot_be_replayed_and_the_replay_is_audited() {
let h = harness().await;
let code = h.start_code().await;
let first = h
.claim(
"198.51.100.20",
json!({"code": code, "outpost_name": "first"}),
)
.await;
assert_eq!(first.status(), StatusCode::OK);
let second = h
.claim(
"198.51.100.21",
json!({"code": code, "outpost_name": "second"}),
)
.await;
assert_eq!(second.status(), StatusCode::GONE);
assert_eq!((h.outposts(), h.credentials()), (1, 1), "no second outpost");
let failed: i64 = h.scalar(
"SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'",
);
assert_eq!(failed, 1);
}
#[tokio::test]
async fn an_expired_code_is_refused_and_old_ones_are_swept_by_the_next_pairing() {
let h = harness().await;
let now = chrono::Utc::now().timestamp();
h.state
.db
.insert_pairing("old-outpost", "STALECODE234", now - 1)
.unwrap();
h.state
.db
.insert_pairing("ancient-outpost", "ANCIENTCODE2", now - 200_000)
.unwrap();
let response = h
.claim(
"198.51.100.20",
json!({"code": "STALECODE234", "outpost_name": "late"}),
)
.await;
assert_eq!(response.status(), StatusCode::GONE);
assert_eq!((h.outposts(), h.credentials()), (0, 0));
h.start_code().await;
// a code that expired a moment ago lingers (the claim still refuses it); one a day old is deleted
let rows: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes");
assert_eq!(rows, 2, "the recent stale code and the fresh one remain");
}

View File

@@ -23,7 +23,7 @@ struct Harness {
async fn harness_with(gate: Option<ExportGate>) -> Harness { async fn harness_with(gate: Option<ExportGate>) -> Harness {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some(ADMIN.into()); state.admin.token = Some(ADMIN.into());

View File

@@ -266,10 +266,11 @@ async fn job(
async fn claim( async fn claim(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(application): Path<Uuid>, Path(application): Path<Uuid>,
) -> Result<Json<Option<CaptureLease>>, StatusCode> { ) -> Result<Json<Option<CaptureLease>>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let mut lease = state let mut lease = state
.db .db
.claim_capture(outpost, application, now()) .claim_capture(outpost, application, now())
@@ -288,11 +289,12 @@ async fn claim(
async fn report( async fn report(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Result<Json<CaptureReport>, JsonRejection>, body: Result<Json<CaptureReport>, JsonRejection>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?; let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
if !state if !state
.db .db
@@ -306,11 +308,12 @@ async fn report(
async fn upload( async fn upload(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Body, body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?) let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?)
.map_err(|_| StatusCode::BAD_REQUEST)?; .map_err(|_| StatusCode::BAD_REQUEST)?;
let job = state let job = state
@@ -401,11 +404,12 @@ async fn upload(
async fn commit_restic( async fn commit_restic(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
Json(commit): Json<ResticCaptureCommit>, Json(commit): Json<ResticCaptureCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let job = state let job = state
.db .db
.capture_upload(outpost, id, commit.lease_id, now()) .capture_upload(outpost, id, commit.lease_id, now())
@@ -549,31 +553,43 @@ pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a
.ok_or(StatusCode::BAD_REQUEST) .ok_or(StatusCode::BAD_REQUEST)
} }
pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> { pub(super) fn outpost(
state: &HubState,
peer: Option<std::net::SocketAddr>,
headers: &HeaderMap,
) -> Result<Uuid, StatusCode> {
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal}; use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
let result = authenticate_outpost(state, headers); let result = authenticate_outpost(state, headers);
let (actor, resource, outcome) = match result { match result {
Ok(id) => ( Ok(id) => {
Principal::Outpost(id),
AuditResource::Outpost(id),
AuditOutcome::Allowed,
),
Err(_) => (
Principal::Anonymous,
AuditResource::Api,
AuditOutcome::Denied,
),
};
state state
.db .db
.audit_event( .audit_event(
&actor, &Principal::Outpost(id),
AuditAction::Authentication, AuditAction::Authentication,
resource, AuditResource::Outpost(id),
outcome, AuditOutcome::Allowed,
Uuid::new_v4(), Uuid::new_v4(),
) )
.map_err(internal)?; .map_err(internal)?;
}
Err(_) => {
// One denial row per source per minute; a failed audit write must not
// change the refusal into a 500.
let source = state.limits.source(peer, headers);
if state.limits.audit_denial(source) {
if let Err(error) = state.db.audit_event(
&Principal::Anonymous,
AuditAction::Authentication,
AuditResource::Api,
AuditOutcome::Denied,
Uuid::new_v4(),
) {
tracing::error!(%error, "could not record a denied outpost authentication");
}
}
}
}
result result
} }

View File

@@ -248,7 +248,7 @@ fn config(idp: &Idp) -> OidcConfig {
async fn harness_with(min_refresh: Duration) -> Harness { async fn harness_with(min_refresh: Duration) -> Harness {
let idp = Idp::start().await; let idp = Idp::start().await;
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
let config = config(&idp); let config = config(&idp);
@@ -788,7 +788,7 @@ async fn an_idp_outage_degrades_to_fixed_errors_and_never_a_session() {
#[tokio::test] #[tokio::test]
async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() { async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
let app = crate::api::router(state); let app = crate::api::router(state);

View File

@@ -71,25 +71,95 @@ struct RunView {
snapshot_id: Option<String>, snapshot_id: Option<String>,
/// This run put a target back from the safety copy of an earlier restore. /// This run put a target back from the safety copy of an earlier restore.
undo: bool, undo: bool,
/// A completed restore that can still be undone: the newest restore of its target, with its safety copy in /// For an undo, the run whose restore it puts back; the Activity log shows the undo under it.
/// the vault. Never says where the copy is. #[serde(skip_serializing_if = "Option::is_none")]
undo_of: Option<String>,
/// The restore job this run queued, which is how the Activity log ties a restore to its run.
#[serde(skip_serializing_if = "Option::is_none")]
restore_job_id: Option<String>,
/// This restore can be put back right now: it is the newest of its target and its safety copy is in the vault.
/// Never says where the copy is.
undo_available: bool, undo_available: bool,
/// Why it can or cannot be put back, for a restore that took a safety copy: `available`, `superseded` (something
/// was restored onto the target after it) or `expired` (retention has forgotten the copy).
#[serde(skip_serializing_if = "Option::is_none")]
undo_state: Option<&'static str>,
/// While it can be undone: when the safety copy is first at risk of being forgotten. Retention keeps a copy a
/// week, and longer while it is one of the target's newest few.
#[serde(skip_serializing_if = "Option::is_none")]
undo_kept_until: Option<i64>,
} }
/// Can this run still be undone: see `Db::undo_candidate`, and the safety copy must still exist. /// What `undo_views` found out about one run.
async fn can_undo(state: &HubState, run: &RefreshRun) -> bool { #[derive(Clone, Copy)]
if run.status != "completed" { struct Undo {
return false; state: &'static str,
} kept_until: Option<i64>,
match state.db.undo_candidate(&run.id, &run.relation_id) {
Ok(Ok(safety)) => snapshot_fits(state, &run.relation_id, safety)
.await
.unwrap_or(false),
_ => false,
}
} }
async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> { /// For every run in the list that took a safety copy, whether it can be put back. The database answers for all of
/// them in one go; the vault is only asked whether a copy still exists (a file lookup), and read only for the one
/// restore per target that could still be undone.
async fn undo_views(
state: &HubState,
runs: &[RefreshRun],
) -> Result<std::collections::HashMap<String, Undo>, StatusCode> {
let infos = state.db.undo_infos(runs).map_err(internal)?;
let mut views = std::collections::HashMap::new();
if infos.is_empty() {
return Ok(views);
}
let vault = state.vault.read().await;
for run in runs {
let Some(info) = infos.get(&run.id) else {
continue;
};
// Safety copies are forgotten by retention: the restore stays in the log, but there is nothing to go back to.
if !vault
.has_published_snapshot(info.safety)
.map_err(internal)?
{
views.insert(
run.id.clone(),
Undo {
state: "expired",
kept_until: None,
},
);
} else if !info.latest {
views.insert(
run.id.clone(),
Undo {
state: "superseded",
kept_until: None,
},
);
} else if let Some(taken) = fitting_snapshot(state, &vault, &run.relation_id, info.safety)?
{
let kept = taken + tessera_core::decay::SAFETY_KEEP_DAYS * 86_400;
views.insert(
run.id.clone(),
Undo {
state: "available",
kept_until: Some(kept),
},
);
}
}
Ok(views)
}
async fn view_one(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
let undo = undo_views(state, std::slice::from_ref(run)).await?;
view(state, run, admin, undo.get(&run.id))
}
fn view(
state: &HubState,
run: &RefreshRun,
admin: bool,
undo: Option<&Undo>,
) -> Result<RunView, StatusCode> {
let Progress { let Progress {
capture_status, capture_status,
capture_phase, capture_phase,
@@ -117,7 +187,11 @@ async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView
requested_by: admin.then(|| run.requester.clone()), requested_by: admin.then(|| run.requester.clone()),
snapshot_id: admin.then(|| run.snapshot_id.clone()).flatten(), snapshot_id: admin.then(|| run.snapshot_id.clone()).flatten(),
undo: run.is_undo(), undo: run.is_undo(),
undo_available: can_undo(state, run).await, undo_of: state.db.undo_parent(run).map_err(internal)?,
restore_job_id: run.restore_job_id.clone(),
undo_available: undo.is_some_and(|undo| undo.state == "available"),
undo_state: undo.map(|undo| undo.state),
undo_kept_until: undo.and_then(|undo| undo.kept_until),
}) })
} }
@@ -168,39 +242,46 @@ fn valid_key(key: &str) -> bool {
} }
/// Is this snapshot one that a relation may restore: a database capture of the relation's own source orbit, /// Is this snapshot one that a relation may restore: a database capture of the relation's own source orbit,
/// never a safety copy of some target, with what a restore needs (format, checksum, source identity)? /// never a safety copy of some target, with what a restore needs (format, checksum, source identity)? When it is,
async fn snapshot_fits( /// when it was taken (seconds since the epoch).
fn fitting_snapshot(
state: &HubState, state: &HubState,
vault: &tessera_store::Vault,
relation: &str, relation: &str,
snapshot: Uuid, snapshot: Uuid,
) -> Result<bool, StatusCode> { ) -> Result<Option<i64>, StatusCode> {
let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else { let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else {
return Ok(false); return Ok(None);
}; };
let manifest = state let Some(stored) = vault.get_snapshot(snapshot).map_err(internal)? else {
.vault return Ok(None);
.read() };
.await let manifest = &stored.manifest;
.get_snapshot(snapshot)
.map_err(internal)?
.map(|s| s.manifest);
let target = match state.db.relation_target(relation).map_err(internal)? { let target = match state.db.relation_target(relation).map_err(internal)? {
Some(id) => Uuid::parse_str(&id) Some(id) => Uuid::parse_str(&id)
.ok() .ok()
.and_then(|id| state.db.restore_target(id).ok().flatten()), .and_then(|id| state.db.restore_target(id).ok().flatten()),
None => None, None => None,
}; };
Ok(manifest.is_some_and(|manifest| { let fits = manifest.orbit_id.to_string() == source
manifest.orbit_id.to_string() == source
&& if manifest.is_restore_safety() { && if manifest.is_restore_safety() {
// a safety copy only ever goes back onto the target it was taken from // a safety copy only ever goes back onto the target it was taken from
target.as_ref().is_some_and(|target| { target
crate::api::rollback_artifact(&manifest, target).is_some() .as_ref()
}) .is_some_and(|target| crate::api::rollback_artifact(manifest, target).is_some())
} else { } else {
crate::api::artifact(&manifest).is_some() crate::api::artifact(manifest).is_some()
};
Ok(fits.then(|| stored.taken_at.timestamp()))
} }
}))
async fn snapshot_fits(
state: &HubState,
relation: &str,
snapshot: Uuid,
) -> Result<bool, StatusCode> {
let vault = state.vault.read().await;
Ok(fitting_snapshot(state, &vault, relation, snapshot)?.is_some())
} }
async fn start( async fn start(
@@ -217,7 +298,7 @@ async fn start(
let relation = body.relation_id.to_string(); let relation = body.relation_id.to_string();
// What to restore: a snapshot the person picked, the safety copy that undoes an earlier restore, or (neither) // What to restore: a snapshot the person picked, the safety copy that undoes an earlier restore, or (neither)
// a fresh capture. // a fresh capture.
let mut chosen: Option<(Uuid, bool)> = None; let mut chosen: Option<(Uuid, Option<String>)> = None;
if let Some(of) = body.undo_of { if let Some(of) = body.undo_of {
if body.snapshot_id.is_some() { if body.snapshot_id.is_some() {
return Err(StatusCode::BAD_REQUEST); return Err(StatusCode::BAD_REQUEST);
@@ -233,7 +314,7 @@ async fn start(
if !snapshot_fits(&state, &relation, safety).await? { if !snapshot_fits(&state, &relation, safety).await? {
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo")); return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
} }
chosen = Some((safety, true)); chosen = Some((safety, Some(of.to_string())));
} else if let Some(snapshot) = body.snapshot_id { } else if let Some(snapshot) = body.snapshot_id {
if !snapshot_fits(&state, &relation, snapshot).await? { if !snapshot_fits(&state, &relation, snapshot).await? {
return Ok(reason( return Ok(reason(
@@ -241,7 +322,7 @@ async fn start(
"snapshot_unusable", "snapshot_unusable",
)); ));
} }
chosen = Some((snapshot, false)); chosen = Some((snapshot, None));
} }
// What authorised this run, recorded so it can be checked again before anything is overwritten. // What authorised this run, recorded so it can be checked again before anything is overwritten.
let authorized_by = if actor.subject.admin { let authorized_by = if actor.subject.admin {
@@ -270,7 +351,9 @@ async fn start(
actor.subject.user_id.as_deref(), actor.subject.user_id.as_deref(),
&authorized_by, &authorized_by,
&body.idempotency_key, &body.idempotency_key,
chosen, chosen
.as_ref()
.map(|(snapshot, of)| (*snapshot, of.as_deref())),
state.refresh.ttl_secs, state.refresh.ttl_secs,
state.refresh.max_active, state.refresh.max_active,
now(), now(),
@@ -293,10 +376,13 @@ async fn start(
Ok(( Ok((
status, status,
no_store(), no_store(),
Json(view(&state, &run, actor.subject.admin).await?), Json(view_one(&state, &run, actor.subject.admin).await?),
) )
.into_response()) .into_response())
} }
Err(StartError::NothingToUndo) => {
Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"))
}
Err(StartError::UnknownRelation) => Err(StatusCode::NOT_FOUND), Err(StartError::UnknownRelation) => Err(StatusCode::NOT_FOUND),
Err(StartError::Unusable(why)) => Ok(( Err(StartError::Unusable(why)) => Ok((
StatusCode::CONFLICT, StatusCode::CONFLICT,
@@ -343,9 +429,10 @@ async fn list(
} }
} }
.map_err(internal)?; .map_err(internal)?;
let undo = undo_views(&state, &runs).await?;
let mut views = Vec::with_capacity(runs.len()); let mut views = Vec::with_capacity(runs.len());
for run in &runs { for run in &runs {
views.push(view(&state, run, actor.subject.admin).await?); views.push(view(&state, run, actor.subject.admin, undo.get(&run.id))?);
} }
Ok((no_store(), Json(views))) Ok((no_store(), Json(views)))
} }
@@ -380,7 +467,7 @@ async fn show(
let run = run.ok_or(StatusCode::NOT_FOUND)?; let run = run.ok_or(StatusCode::NOT_FOUND)?;
Ok(( Ok((
no_store(), no_store(),
Json(view(&state, &run, actor.subject.admin).await?), Json(view_one(&state, &run, actor.subject.admin).await?),
)) ))
} }
@@ -429,7 +516,7 @@ async fn cancel(
crate::refresh::audit_run(&state, &run.id, "cancelled"); crate::refresh::audit_run(&state, &run.id, "cancelled");
Ok(( Ok((
no_store(), no_store(),
Json(view(&state, &run, actor.subject.admin).await?), Json(view_one(&state, &run, actor.subject.admin).await?),
) )
.into_response()) .into_response())
} }

View File

@@ -44,7 +44,7 @@ struct Lab {
async fn lab_with(configure: impl FnOnce(&mut HubState)) -> Lab { async fn lab_with(configure: impl FnOnce(&mut HubState)) -> Lab {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some(ADMIN.into()); state.admin.token = Some(ADMIN.into());
@@ -2257,6 +2257,16 @@ async fn a_completed_restore_can_be_undone_from_its_safety_copy_and_the_undo_can
lab.report_applied(&job, &token).await; lab.report_applied(&job, &token).await;
lab.tick().await; lab.tick().await;
assert_eq!(lab.run(&undo_id).status, "completed"); assert_eq!(lab.run(&undo_id).status, "completed");
// the undo says which restore it puts back, and the restore says which job it queued
let (_, child) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{undo_id}"), None)
.await;
assert_eq!(child["undo_of"], json!(first), "{child}");
assert!(child["restore_job_id"].is_string(), "{child}");
let (_, parent) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
.await;
assert!(parent.get("undo_of").is_none(), "{parent}");
// only the newest restore of a target can be undone: the first one no longer can, the undo can // only the newest restore of a target can be undone: the first one no longer can, the undo can
let (_, old) = lab let (_, old) = lab
@@ -2365,3 +2375,188 @@ async fn only_someone_who_may_use_the_relation_can_undo_through_it() {
); );
assert_eq!(lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"), 1); assert_eq!(lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"), 1);
} }
// ---- why a restore can or cannot be put back, and rolling back a restore that failed ----
impl Lab {
async fn run_view(&self, run: &str) -> Value {
self.send(
&self.admin(),
"GET",
&format!("/api/v1/refresh-runs/{run}"),
None,
)
.await
.1
}
fn safety_of(&self, run: &str) -> Uuid {
Uuid::parse_str(&self.scalar::<String>(&format!(
"SELECT safety_id FROM restore_jobs WHERE id=(SELECT restore_job_id FROM refresh_runs WHERE id='{run}')"
)))
.unwrap()
}
/// A restore that got as far as overwriting the target and then failed, as the agent reports it.
async fn failed_apply(&self, key: &str) -> (String, String) {
let (_, run) = self.start(&self.admin(), key).await;
let run = run["id"].as_str().unwrap().to_string();
self.capture(&Lab::production_identity(), false)
.await
.unwrap();
self.tick().await;
let (job, token) = self
.restore_until_ready()
.await
.expect("a restore job is waiting");
assert_eq!(self.apply(&job, &token).await, StatusCode::NO_CONTENT);
let (status, _) = self
.agent_json(
"POST",
&format!("/api/v1/wormhole/restore/{job}/report"),
&[("x-tessera-restore-token", token)],
json!("apply_failed"),
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
self.tick().await;
assert_eq!(self.run(&run).status, "recovery_required");
(run, job)
}
}
#[tokio::test]
async fn a_restore_says_why_it_can_or_cannot_be_put_back_and_how_long_for() {
let lab = fresh().await;
let first = lab.restored_once("first").await;
let view = lab.run_view(&first).await;
assert_eq!(
(view["undo_available"].clone(), view["undo_state"].clone()),
(json!(true), json!("available")),
"{view}"
);
let until = view["undo_kept_until"]
.as_i64()
.expect("a date while it can be undone");
assert!(
until > chrono::Utc::now().timestamp() + 6 * 86_400,
"a week from when it was taken: {view}"
);
// a later restore of the same target supersedes it; only the newest can be undone
let second = lab.restored_once("second").await;
let (old, new) = (lab.run_view(&first).await, lab.run_view(&second).await);
assert_eq!(
(old["undo_state"].clone(), old["undo_available"].clone()),
(json!("superseded"), json!(false)),
"{old}"
);
assert_eq!(new["undo_state"], "available", "{new}");
// retention forgets the newest copy: it says so, instead of offering something that would be refused
lab.state
.vault
.write()
.await
.forget(&[lab.safety_of(&second)])
.unwrap();
let new = lab.run_view(&second).await;
assert_eq!(
(new["undo_state"].clone(), new["undo_available"].clone()),
(json!("expired"), json!(false)),
"{new}"
);
assert!(new.get("undo_kept_until").is_none(), "{new}");
// expired wins over superseded, so nobody is told to look for a copy that is gone
lab.state
.vault
.write()
.await
.forget(&[lab.safety_of(&first)])
.unwrap();
assert_eq!(lab.run_view(&first).await["undo_state"], "expired");
// the list says the same, for a person who may only use the relation
let (qa, _) = lab.refresher("qa");
let (_, list) = lab.send(&qa, "GET", "/api/v1/refresh-runs", None).await;
let states: Vec<_> = list
.as_array()
.unwrap()
.iter()
.map(|r| r["undo_state"].clone())
.collect();
assert_eq!(states, vec![json!("expired"), json!("expired")], "{list}");
}
#[tokio::test]
async fn a_restore_whose_apply_failed_is_rolled_back_from_its_safety_copy() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa");
let (run, job) = lab.failed_apply("broken").await;
let view = lab.run_view(&run).await;
assert_eq!(
view["undo_available"], true,
"rolling back is offered: {view}"
);
// while the failed apply fences the target nothing else may start, but the rollback may
let (status, other) = lab.start(&qa, "other").await;
assert_eq!(
(status, other["reason"].clone()),
(StatusCode::CONFLICT, json!("run_active")),
"{other}"
);
let (status, undo) = lab.start_undo(&qa, "rollback", &run).await;
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
assert_eq!(undo["undo_of"], json!(run));
assert_eq!(lab.run(&run).status, "reconciled");
assert_eq!(
lab.scalar::<String>(&format!("SELECT phase FROM restore_jobs WHERE id='{job}'")),
"rolled_back"
);
assert!(lab
.audit_log()
.iter()
.any(|(event, _)| event == "restore.rolled_back"));
// it goes through the same engine and puts the copy back
lab.tick().await;
lab.finish_restore().await;
assert_eq!(lab.run(undo["id"].as_str().unwrap()).status, "completed");
assert_eq!(
lab.run_view(&run).await["undo_state"],
"superseded",
"it is not offered twice"
);
}
#[tokio::test]
async fn an_apply_that_lost_its_agent_waits_for_an_administrator_before_it_can_be_rolled_back() {
let lab = fresh().await;
let (run, job) = lab.failed_apply("silent").await;
// the agent did not say it stopped: the apply may still be writing
lab.conn()
.execute(
"UPDATE restore_jobs SET phase='lease_lost' WHERE id=?1",
[&job],
)
.unwrap();
assert_eq!(lab.run_view(&run).await["undo_available"], false);
let (status, body) = lab.start_undo(&lab.admin(), "early", &run).await;
assert_eq!(
(status, body["reason"].clone()),
(StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")),
"{body}"
);
// once an administrator has verified it, the same safety copy can put the target back
assert!(lab
.state
.db
.reconcile_restore(Uuid::parse_str(&job).unwrap(), "admin", now())
.unwrap());
lab.tick().await;
assert_eq!(lab.run(&run).status, "reconciled");
assert_eq!(lab.run_view(&run).await["undo_available"], true);
let (status, undo) = lab.start_undo(&lab.admin(), "after", &run).await;
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
}

View File

@@ -370,10 +370,11 @@ async fn reconcile(
async fn claim( async fn claim(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(target): Path<Uuid>, Path(target): Path<Uuid>,
) -> Result<Json<Option<RestoreLease>>, StatusCode> { ) -> Result<Json<Option<RestoreLease>>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
state state
.db .db
.claim_restore(outpost, target, now()) .claim_restore(outpost, target, now())
@@ -381,8 +382,12 @@ async fn claim(
.map_err(internal) .map_err(internal)
} }
fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCode> { fn auth(
let outpost = outpost(state, headers)?; state: &HubState,
peer: Option<ConnectInfo<SocketAddr>>,
headers: &HeaderMap,
) -> Result<(Uuid, Uuid), StatusCode> {
let outpost = outpost(state, peer.map(|ConnectInfo(addr)| addr), headers)?;
let token = let token =
header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?; header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?;
Ok(( Ok((
@@ -393,10 +398,11 @@ fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCod
async fn payload( async fn payload(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> { ) -> Result<Response, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
let (job, artifact, _) = state let (job, artifact, _) = state
.db .db
.restore_access(outpost, id, token, now()) .restore_access(outpost, id, token, now())
@@ -435,11 +441,12 @@ async fn payload(
async fn report( async fn report(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Result<Json<RestoreProgress>, JsonRejection>, body: Result<Json<RestoreProgress>, JsonRejection>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?; let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
// Why a step failed, in the agent's words. Cleaned again here: the agent is trusted with the job, not // Why a step failed, in the agent's words. Cleaned again here: the agent is trusted with the job, not
// with what ends up in the database and the log. // with what ends up in the database and the log.
@@ -462,11 +469,12 @@ async fn report(
async fn safety( async fn safety(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Body, body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
let (job, _, safety_id) = state let (job, _, safety_id) = state
.db .db
.restore_access(outpost, id, token, now()) .restore_access(outpost, id, token, now())
@@ -538,10 +546,11 @@ async fn safety(
async fn apply( async fn apply(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
if !state if !state
.db .db
.authorize_apply(outpost, id, token, now()) .authorize_apply(outpost, id, token, now())

View File

@@ -251,7 +251,6 @@ struct ReconstituteStartResponse {
pub(super) struct OperatorActor { pub(super) struct OperatorActor {
/// Display only. Never record this as "who did it": an IdP can call a user anything. /// Display only. Never record this as "who did it": an IdP can call a user anything.
pub(super) name: String, pub(super) name: String,
pub(super) browser: bool,
pub(super) principal: Principal, pub(super) principal: Principal,
pub(super) subject: Subject, pub(super) subject: Subject,
pub(super) request_id: Uuid, pub(super) request_id: Uuid,
@@ -289,16 +288,21 @@ pub(super) fn authenticate(
.unwrap_or(Principal::Anonymous); .unwrap_or(Principal::Anonymous);
let result = authenticate_inner(state, peer, headers, mutation, request_id, session); let result = authenticate_inner(state, peer, headers, mutation, request_id, session);
if result.is_err() { if result.is_err() {
state // One denial row per source per minute: an unauthenticated flood must not
.db // grow the audit table, and a failed audit write must not turn the 401/403
.audit_event( // into a 500.
let source = state.limits.source(Some(peer), headers);
if state.limits.audit_denial(source) {
if let Err(error) = state.db.audit_event(
&attempted, &attempted,
AuditAction::Authentication, AuditAction::Authentication,
AuditResource::Api, AuditResource::Api,
AuditOutcome::Denied, AuditOutcome::Denied,
request_id, request_id,
) ) {
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; tracing::error!(%error, "could not record a denied authentication");
}
}
} }
result result
} }
@@ -313,7 +317,6 @@ fn authenticate_inner(
) -> Result<OperatorActor, StatusCode> { ) -> Result<OperatorActor, StatusCode> {
let configured_admin = |name: &str, principal: Principal| OperatorActor { let configured_admin = |name: &str, principal: Principal| OperatorActor {
name: name.into(), name: name.into(),
browser: false,
principal, principal,
subject: Subject { subject: Subject {
user_id: None, user_id: None,
@@ -322,12 +325,22 @@ fn authenticate_inner(
}, },
request_id, request_id,
}; };
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() { if state.admin.token.is_some() {
if state.admin.authorize(peer, headers).is_ok() {
return Ok(configured_admin( return Ok(configured_admin(
"api-token", "api-token",
Principal::Service("legacy-admin-token"), Principal::Service("legacy-admin-token"),
)); ));
} }
// A wrong token counts against the source's budget; past it the answer is 429.
if crate::admin::presents_token(headers)
&& !state
.limits
.admin_token_failure(state.limits.source(Some(peer), headers))
{
return Err(StatusCode::TOO_MANY_REQUESTS);
}
}
if let Some(session) = session { if let Some(session) = session {
if mutation { if mutation {
super::session::require_csrf(headers, &session.csrf.to_string())?; super::session::require_csrf(headers, &session.csrf.to_string())?;
@@ -336,7 +349,6 @@ fn authenticate_inner(
principal: session.principal(), principal: session.principal(),
subject: session.subject(), subject: session.subject(),
name: session.actor, name: session.actor,
browser: true,
request_id, request_id,
}); });
} }
@@ -407,14 +419,73 @@ pub fn router(state: HubState) -> Router {
.merge(super::relations::routes()) .merge(super::relations::routes())
.merge(super::refresh::routes()) .merge(super::refresh::routes())
.merge(super::restore::routes()) .merge(super::restore::routes())
.route("/api-doc/openapi.json", get(openapi_document))
.with_state(state); .with_state(state);
let api = api.route( let hsts = matches!(std::env::var("TESSERA_HSTS").as_deref(), Ok("1" | "true"));
"/api-doc/openapi.json", api.fallback(spa_fallback)
get(|| async { Json(ApiDoc::openapi()) }), .layer(TraceLayer::new_for_http().make_span_with(request_span))
); .layer(axum::middleware::from_fn(move |request, next| {
security_headers(hsts, request, next)
}))
}
api.fallback(spa_fallback).layer(TraceLayer::new_for_http()) /// The log span for a request: method and path only. The query string is left out because it carries
/// OIDC `code` and `state` values (and may carry other secrets).
fn request_span(request: &axum::http::Request<axum::body::Body>) -> tracing::Span {
tracing::info_span!("request", method = %request.method(), path = %request.uri().path())
}
/// Policy for the bundled web app: everything from this origin. The stylesheet pulls the
/// Google Fonts CSS and font files, hence those two allowances.
const CONTENT_SECURITY_POLICY: &str = "default-src 'self'; script-src 'self'; \
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; \
img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
async fn security_headers(
hsts: bool,
request: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
let mut response = next.run(request).await;
let headers = response.headers_mut();
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(CONTENT_SECURITY_POLICY),
);
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
headers.insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
if hsts {
headers.insert(
header::STRICT_TRANSPORT_SECURITY,
HeaderValue::from_static("max-age=31536000; includeSubDomains"),
);
}
response
}
/// The API description needs a signed-in operator or the admin token, unless
/// `TESSERA_PUBLIC_OPENAPI=true` publishes it.
async fn openapi_document(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<utoipa::openapi::OpenApi>, StatusCode> {
let public = matches!(
std::env::var("TESSERA_PUBLIC_OPENAPI").as_deref(),
Ok("1" | "true")
);
if !public {
authenticate(&state, peer, &headers, false)?;
}
Ok(Json(ApiDoc::openapi()))
} }
#[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))] #[utoipa::path(get, path = "/health", responses((status = 200, description = "ok")))]
@@ -750,12 +821,13 @@ async fn start_reconstitute(
headers: HeaderMap, headers: HeaderMap,
Json(req): Json<ReconstituteRequest>, Json(req): Json<ReconstituteRequest>,
) -> Result<Json<ReconstituteStartResponse>, StatusCode> { ) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
let actor = admin_write(&state, peer, &headers)?; admin_write(&state, peer, &headers)?;
let destination = if actor.browser { // Every caller, browser or API token, may only name a file inside the hub's exports directory,
browser_export_path(&state, &req.target_path)? // and never one that already exists.
} else { let destination = browser_export_path(&state, &req.target_path)?;
req.target_path.clone().into() if destination.symlink_metadata().is_ok() {
}; return Err(StatusCode::CONFLICT);
}
let vault = state.vault.read().await; let vault = state.vault.read().await;
if vault if vault
.get_snapshot(req.snapshot_id) .get_snapshot(req.snapshot_id)
@@ -785,6 +857,7 @@ async fn start_reconstitute(
let mut map = state_bg.reconstitute_sessions.write().await; let mut map = state_bg.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&session_id) { if let Some(s) = map.get_mut(&session_id) {
if s.state == ReconstituteState::Aborted { if s.state == ReconstituteState::Aborted {
evict_reconstitute_later(&state_bg, session_id);
return; return;
} }
s.seconds_remaining = remaining; s.seconds_remaining = remaining;
@@ -798,6 +871,7 @@ async fn start_reconstitute(
return; return;
}; };
if s.state == ReconstituteState::Aborted { if s.state == ReconstituteState::Aborted {
evict_reconstitute_later(&state_bg, session_id);
return; return;
} }
s.state = ReconstituteState::Restoring; s.state = ReconstituteState::Restoring;
@@ -816,6 +890,7 @@ async fn start_reconstitute(
.db .db
.audit("reconstitute.done", &format!("session={session_id}")) .audit("reconstitute.done", &format!("session={session_id}"))
.await; .await;
evict_reconstitute_later(&state_bg, session_id);
}); });
Ok(Json(ReconstituteStartResponse { Ok(Json(ReconstituteStartResponse {
@@ -824,6 +899,19 @@ async fn start_reconstitute(
})) }))
} }
/// How long a finished restore session stays readable before its entry is dropped.
const RECONSTITUTE_RETAIN: std::time::Duration = std::time::Duration::from_secs(3600);
/// Drops a finished session from the in-memory map after `RECONSTITUTE_RETAIN`, so the map does
/// not grow for as long as the hub runs.
fn evict_reconstitute_later(state: &HubState, id: Uuid) {
let state = state.clone();
tokio::spawn(async move {
tokio::time::sleep(RECONSTITUTE_RETAIN).await;
state.reconstitute_sessions.write().await.remove(&id);
});
}
fn browser_export_path( fn browser_export_path(
state: &HubState, state: &HubState,
requested: &str, requested: &str,
@@ -1189,10 +1277,11 @@ fn require_legacy_upload_owner(
#[utoipa::path(post, path = "/api/v1/wormhole/upload/init", request_body = UploadInit, responses((status = 200)))] #[utoipa::path(post, path = "/api/v1/wormhole/upload/init", request_body = UploadInit, responses((status = 200)))]
async fn wormhole_upload_init( async fn wormhole_upload_init(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: axum::http::HeaderMap, headers: axum::http::HeaderMap,
Json(body): Json<UploadInit>, Json(body): Json<UploadInit>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = super::jobs::outpost(&state, &headers)?; let outpost = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
require_legacy_upload_owner(&state, body.orbit_id, outpost)?; require_legacy_upload_owner(&state, body.orbit_id, outpost)?;
reject_managed_orbit(&state, body.orbit_id)?; reject_managed_orbit(&state, body.orbit_id)?;
if state if state
@@ -1231,10 +1320,11 @@ async fn wormhole_upload_init(
#[utoipa::path(post, path = "/api/v1/wormhole/upload/chunk", request_body = UploadChunk, responses((status = 204)))] #[utoipa::path(post, path = "/api/v1/wormhole/upload/chunk", request_body = UploadChunk, responses((status = 204)))]
async fn wormhole_upload_chunk( async fn wormhole_upload_chunk(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: axum::http::HeaderMap, headers: axum::http::HeaderMap,
Json(body): Json<UploadChunk>, Json(body): Json<UploadChunk>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let outpost = super::jobs::outpost(&state, &headers)?; let outpost = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let session = state let session = state
.db .db
.upload_session(&body.session_id.to_string()) .upload_session(&body.session_id.to_string())
@@ -1338,10 +1428,11 @@ pub(super) fn upload_token<'a>(
#[utoipa::path(post, path = "/api/v1/wormhole/restic/commit", request_body = ResticCommit, responses((status = 200)))] #[utoipa::path(post, path = "/api/v1/wormhole/restic/commit", request_body = ResticCommit, responses((status = 200)))]
async fn wormhole_restic_commit( async fn wormhole_restic_commit(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Json(body): Json<ResticCommit>, Json(body): Json<ResticCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost_id = super::jobs::outpost(&state, &headers)?; let outpost_id = super::jobs::outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
require_legacy_upload_owner(&state, body.orbit_id, outpost_id)?; require_legacy_upload_owner(&state, body.orbit_id, outpost_id)?;
if body.snapshot_id.len() != 64 || !body.snapshot_id.bytes().all(|b| b.is_ascii_hexdigit()) { if body.snapshot_id.len() != 64 || !body.snapshot_id.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(StatusCode::BAD_REQUEST); return Err(StatusCode::BAD_REQUEST);
@@ -1469,18 +1560,33 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse {
path = "index.html".into(); path = "index.html".into();
} }
if let Some(file) = WEB_DIST.get_file(&path) { if let Some(file) = WEB_DIST.get_file(&path) {
let ct = content_type(&path); // Build output under /assets/ carries a content hash in its name.
let cache = if path.starts_with("assets/") {
"public, max-age=31536000, immutable"
} else {
"no-cache"
};
return ( return (
StatusCode::OK, StatusCode::OK,
[(header::CONTENT_TYPE, ct)], [
(header::CONTENT_TYPE, content_type(&path)),
(header::CACHE_CONTROL, cache),
],
file.contents(), file.contents(),
) )
.into_response(); .into_response();
} }
// A missing asset or API path is a 404, not the app shell.
if path.starts_with("assets/") || path.starts_with("api/") {
return (StatusCode::NOT_FOUND, "not found").into_response();
}
if let Some(index) = WEB_DIST.get_file("index.html") { if let Some(index) = WEB_DIST.get_file("index.html") {
return ( return (
StatusCode::OK, StatusCode::OK,
[(header::CONTENT_TYPE, "text/html")], [
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
(header::CACHE_CONTROL, "no-cache"),
],
index.contents(), index.contents(),
) )
.into_response(); .into_response();
@@ -1489,14 +1595,22 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse {
} }
fn content_type(path: &str) -> &'static str { fn content_type(path: &str) -> &'static str {
if path.ends_with(".js") { let extension = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
"application/javascript" match extension.as_str() {
} else if path.ends_with(".css") { "html" => "text/html; charset=utf-8",
"text/css" "js" | "mjs" => "text/javascript; charset=utf-8",
} else if path.ends_with(".svg") { "css" => "text/css; charset=utf-8",
"image/svg+xml" "svg" => "image/svg+xml",
} else { "png" => "image/png",
"text/html" "jpg" | "jpeg" => "image/jpeg",
"webp" => "image/webp",
"ico" => "image/x-icon",
"woff" => "font/woff",
"woff2" => "font/woff2",
"json" => "application/json",
"map" => "application/json",
"txt" => "text/plain; charset=utf-8",
_ => "application/octet-stream",
} }
} }
@@ -1507,10 +1621,289 @@ mod tests {
use axum::http::Request; use axum::http::Request;
use tower::ServiceExt; use tower::ServiceExt;
async fn denied_authentication_rows(dir: &std::path::Path) -> i64 {
rusqlite::Connection::open(dir.join("tessera.db"))
.unwrap()
.query_row(
"SELECT count(*) FROM audit_events WHERE action='authentication.check' AND outcome='denied'",
[],
|r| r.get(0),
)
.unwrap()
}
#[tokio::test]
async fn unauthenticated_floods_write_one_denial_row_per_source() {
let dir = tempfile::tempdir().unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
let human = |ip: &str| {
Request::get("/api/v1/orbits")
.extension(ConnectInfo(
format!("{ip}:9000").parse::<SocketAddr>().unwrap(),
))
.body(Body::empty())
.unwrap()
};
let outpost = |ip: &str| {
Request::post("/api/v1/wormhole/upload/init")
.extension(ConnectInfo(
format!("{ip}:9000").parse::<SocketAddr>().unwrap(),
))
.header(header::CONTENT_TYPE, "application/json")
.header("x-tessera-upload-token", "wrong")
.body(Body::from(
r#"{"orbit_id":"00000000-0000-0000-0000-000000000000","total_bytes":1}"#,
))
.unwrap()
};
for _ in 0..25 {
let r = app.clone().oneshot(human("203.0.113.5")).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
}
assert_eq!(denied_authentication_rows(dir.path()).await, 1);
for _ in 0..25 {
let r = app.clone().oneshot(outpost("203.0.113.5")).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
}
// the same source shares one budget across both entry points
assert_eq!(denied_authentication_rows(dir.path()).await, 1);
// another source still gets its own row
let r = app.clone().oneshot(outpost("203.0.113.6")).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
assert_eq!(denied_authentication_rows(dir.path()).await, 2);
}
#[tokio::test]
async fn wrong_admin_tokens_are_throttled_per_source() {
let dir = tempfile::tempdir().unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
let req = |ip: &str, token: &str| {
Request::get("/api/v1/orbits")
.extension(ConnectInfo(
format!("{ip}:9000").parse::<SocketAddr>().unwrap(),
))
.header("x-tessera-admin-token", token)
.body(Body::empty())
.unwrap()
};
let mut limited = false;
for _ in 0..20 {
let r = app
.clone()
.oneshot(req("203.0.113.20", "wrong"))
.await
.unwrap();
limited |= r.status() == StatusCode::TOO_MANY_REQUESTS;
}
assert!(limited);
let r = app.oneshot(req("203.0.113.21", "wrong")).await.unwrap();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn reconstitute_targets_stay_inside_the_exports_directory_for_every_caller() {
let dir = tempfile::tempdir().unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
let attempt = |path: &str| {
Request::post("/api/v1/reconstitute")
.extension(ConnectInfo(
"203.0.113.30:9000".parse::<SocketAddr>().unwrap(),
))
.header(
header::AUTHORIZATION,
"Bearer synthetic-admin-token-of-32-chars!",
)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
serde_json::json!({"snapshot_id": Uuid::new_v4(), "target_path": path})
.to_string(),
))
.unwrap()
};
for path in ["/etc/passwd", "../escape", "a/b", "..", ""] {
let r = app.clone().oneshot(attempt(path)).await.unwrap();
assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{path}");
}
// a plain file name passes confinement (the unknown snapshot is what stops it)
let r = app.clone().oneshot(attempt("dump.sql")).await.unwrap();
assert_eq!(r.status(), StatusCode::NOT_FOUND);
std::fs::write(dir.path().join("exports").join("taken.sql"), b"keep").unwrap();
let r = app.oneshot(attempt("taken.sql")).await.unwrap();
assert_eq!(r.status(), StatusCode::CONFLICT);
}
#[test]
fn request_logs_name_the_path_and_never_the_query() {
use std::sync::{Arc, Mutex};
#[derive(Clone, Default)]
struct Sink(Arc<Mutex<Vec<u8>>>);
impl std::io::Write for Sink {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Sink {
type Writer = Sink;
fn make_writer(&'a self) -> Sink {
self.clone()
}
}
let sink = Sink::default();
let subscriber = tracing_subscriber::fmt().with_writer(sink.clone()).finish();
tracing::subscriber::with_default(subscriber, || {
let request =
Request::get("/api/v1/auth/oidc/callback?code=secret-code&state=secret-state")
.body(Body::empty())
.unwrap();
request_span(&request).in_scope(|| tracing::info!("handled"));
});
let logged = String::from_utf8(sink.0.lock().unwrap().clone()).unwrap();
assert!(logged.contains("/api/v1/auth/oidc/callback"), "{logged}");
assert!(
!logged.contains("secret-code") && !logged.contains("secret-state"),
"{logged}"
);
}
#[test]
fn content_types_are_right_and_unknown_is_never_html() {
assert_eq!(content_type("assets/x.png"), "image/png");
assert_eq!(content_type("assets/x.woff2"), "font/woff2");
assert_eq!(content_type("assets/x.woff"), "font/woff");
assert_eq!(content_type("favicon.ico"), "image/x-icon");
assert_eq!(content_type("assets/x.js.map"), "application/json");
assert_eq!(content_type("manifest.json"), "application/json");
assert_eq!(content_type("assets/x.bin"), "application/octet-stream");
assert_eq!(content_type("noextension"), "application/octet-stream");
}
#[tokio::test]
async fn the_api_description_is_not_served_to_anonymous_callers() {
let dir = tempfile::tempdir().unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
let request = |token: Option<&str>| {
let mut r = Request::get("/api-doc/openapi.json").extension(ConnectInfo(
"203.0.113.50:9000".parse::<SocketAddr>().unwrap(),
));
if let Some(token) = token {
r = r.header(header::AUTHORIZATION, format!("Bearer {token}"));
}
r.body(Body::empty()).unwrap()
};
let anonymous = app.clone().oneshot(request(None)).await.unwrap();
assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
let signed_in = app
.oneshot(request(Some("synthetic-admin-token-of-32-chars!")))
.await
.unwrap();
assert_eq!(signed_in.status(), StatusCode::OK);
}
#[tokio::test]
async fn responses_carry_security_headers_and_assets_cache_for_a_year() {
let dir = tempfile::tempdir().unwrap();
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
let app = router(state);
let get = |uri: &str| {
Request::get(uri)
.extension(ConnectInfo(
"203.0.113.40:9000".parse::<SocketAddr>().unwrap(),
))
.body(Body::empty())
.unwrap()
};
for uri in ["/", "/health", "/api/v1/orbits"] {
let r = app.clone().oneshot(get(uri)).await.unwrap();
let h = r.headers();
let csp = h[header::CONTENT_SECURITY_POLICY].to_str().unwrap();
assert!(csp.contains("default-src 'self'") && csp.contains("frame-ancestors 'none'"));
assert_eq!(h[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
assert_eq!(h[header::REFERRER_POLICY], "no-referrer");
assert_eq!(h[header::X_FRAME_OPTIONS], "DENY");
}
let missing = app.clone().oneshot(get("/assets/nope.js")).await.unwrap();
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
if let Some(file) = WEB_DIST.get_dir("assets").and_then(|d| d.files().next()) {
let uri = format!("/{}", file.path().display());
let r = app.oneshot(get(&uri)).await.unwrap();
assert_eq!(r.status(), StatusCode::OK);
assert_eq!(
r.headers()[header::CACHE_CONTROL],
"public, max-age=31536000, immutable"
);
}
}
#[tokio::test]
async fn a_failed_denial_audit_write_still_answers_401() {
let dir = tempfile::tempdir().unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some("synthetic-admin-token-of-32-chars!".into());
let app = router(state);
rusqlite::Connection::open(dir.path().join("tessera.db"))
.unwrap()
.execute_batch("DROP TABLE audit_events")
.unwrap();
let human = Request::get("/api/v1/orbits")
.extension(ConnectInfo(
"203.0.113.9:9000".parse::<SocketAddr>().unwrap(),
))
.body(Body::empty())
.unwrap();
assert_eq!(
app.clone().oneshot(human).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
let outpost = Request::post("/api/v1/wormhole/upload/init")
.extension(ConnectInfo(
"203.0.113.10:9000".parse::<SocketAddr>().unwrap(),
))
.header(header::CONTENT_TYPE, "application/json")
.header("x-tessera-upload-token", "wrong")
.body(Body::from(
r#"{"orbit_id":"00000000-0000-0000-0000-000000000000","total_bytes":1}"#,
))
.unwrap();
assert_eq!(
app.oneshot(outpost).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
}
#[tokio::test] #[tokio::test]
async fn legacy_uploads_are_owned_by_the_assigned_outpost() { async fn legacy_uploads_are_owned_by_the_assigned_outpost() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault") let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.accept_plain_upload = true; state.accept_plain_upload = true;
@@ -1693,6 +2086,7 @@ mod tests {
); );
let mut commit = Box::pin(wormhole_restic_commit( let mut commit = Box::pin(wormhole_restic_commit(
State(state.clone()), State(state.clone()),
None,
owner_headers, owner_headers,
Json(ResticCommit { Json(ResticCommit {
orbit_id: orbit, orbit_id: orbit,
@@ -1721,7 +2115,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn orbit_creation_validates_cron_and_direct_run_preserves_wormhole_status() { async fn orbit_creation_validates_cron_and_direct_run_preserves_wormhole_status() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some("fixture-admin".into()); state.admin.token = Some("fixture-admin".into());
@@ -1787,7 +2181,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn new_orbits_validate_source_access_and_keep_provider_internal() { async fn new_orbits_validate_source_access_and_keep_provider_internal() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some("fixture-admin".into()); state.admin.token = Some("fixture-admin".into());
@@ -1843,7 +2237,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn orbit_responses_and_schema_hide_provider_config() { async fn orbit_responses_and_schema_hide_provider_config() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault") let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.admin.token = Some("fixture-admin".into()); state.admin.token = Some("fixture-admin".into());

View File

@@ -369,7 +369,8 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn operator_session_requires_csrf_and_expires_without_disabling_cli() { async fn operator_session_requires_csrf_and_expires_without_disabling_cli() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault") let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.sessions = SessionGate::fixture(state.db.clone()); state.sessions = SessionGate::fixture(state.db.clone());
@@ -507,7 +508,8 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn me_reports_the_caller_and_rejects_anonymous() { async fn me_reports_the_caller_and_rejects_anonymous() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault") let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase")
.await .await
.unwrap(); .unwrap();
state.sessions = SessionGate::fixture(state.db.clone()); state.sessions = SessionGate::fixture(state.db.clone());

View File

@@ -51,12 +51,56 @@ impl Db {
)?; )?;
Ok(()) Ok(())
} }
/// Deletes structured audit events recorded before `cutoff` (unix seconds);
/// returns how many rows went.
pub fn prune_audit_events(&self, cutoff: i64) -> Result<usize> {
Ok(self
.conn
.lock()
.unwrap()
.execute("DELETE FROM audit_events WHERE at < ?1", params![cutoff])?)
}
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[tokio::test]
async fn pruning_removes_only_events_older_than_the_cutoff() {
let dir = tempfile::tempdir().unwrap();
let db = Db::connect(&dir.path().join("fixture.db")).await.unwrap();
db.migrate().await.unwrap();
for _ in 0..3 {
db.audit_event(
&Principal::Anonymous,
AuditAction::Authentication,
AuditResource::Api,
AuditOutcome::Denied,
Uuid::new_v4(),
)
.unwrap();
}
let now = chrono::Utc::now().timestamp();
db.conn
.lock()
.unwrap()
.execute(
"UPDATE audit_events SET at = ?1 WHERE id <= 2",
params![now - 100 * 86_400],
)
.unwrap();
assert_eq!(db.prune_audit_events(now - 90 * 86_400).unwrap(), 2);
let left: i64 = db
.conn
.lock()
.unwrap()
.query_row("SELECT count(*) FROM audit_events", [], |r| r.get(0))
.unwrap();
assert_eq!(left, 1);
}
#[tokio::test] #[tokio::test]
async fn structured_audit_survives_reopen_and_preserves_legacy_events() { async fn structured_audit_survives_reopen_and_preserves_legacy_events() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();

View File

@@ -79,6 +79,8 @@ pub enum StartError {
KeyReused, KeyReused,
/// Too many refreshes are running at once. /// Too many refreshes are running at once.
TooManyRuns, TooManyRuns,
/// The restore to undo is not one that can be undone (any more).
NothingToUndo,
} }
/// What the confirmation must say: it names exactly what the person saw, including the version. /// What the confirmation must say: it names exactly what the person saw, including the version.
@@ -99,55 +101,125 @@ impl RefreshRun {
} }
} }
/// A relation's source orbit, for checking that a snapshot belongs to it. /// The safety copy a restore took before it overwrote its target, and whether it is still the newest restore there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UndoInfo {
pub safety: Uuid,
/// Nothing was restored onto the target after it. Undoing an older restore would also undo what came later.
pub latest: bool,
}
/// Does this run have a safety copy that puts its target back? A restore that finished, one an administrator
/// has since reconciled, and one whose apply failed (the agent says it stopped, so nothing is still writing) all
/// do: in the last case, rolling back is the recovery. An apply whose agent went silent may still be running, so
/// it waits for an administrator to reconcile it.
fn undo_info(conn: &Connection, run: &RefreshRun) -> Result<Option<UndoInfo>> {
if !matches!(
run.status.as_str(),
"completed" | "reconciled" | "recovery_required"
) {
return Ok(None);
}
let Some(job) = &run.restore_job_id else {
return Ok(None);
};
let row: Option<(String, String, Option<String>)> = conn
.query_row(
"SELECT status, phase, safety_id FROM restore_jobs WHERE id = ?1",
params![job],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?;
let Some((status, phase, Some(safety))) = row else {
return Ok(None);
};
let sound = match status.as_str() {
"completed" | "reconciled" => true,
"recovery_required" => phase == "apply_failed",
_ => false,
};
if !sound {
return Ok(None);
}
// Jobs are numbered in the order they were queued.
let later: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE target_id = ?1
AND rowid > (SELECT rowid FROM restore_jobs WHERE id = ?2)
AND status IN ('queued','running','applying','completed','reconciled','recovery_required'))",
params![run.target_id, job],
|r| r.get(0),
)?;
Ok(Some(UndoInfo {
safety: Uuid::parse_str(&safety)?,
latest: !later,
}))
}
fn undo_check(
conn: &Connection,
run: &str,
relation: &str,
) -> Result<std::result::Result<Uuid, UndoRefusal>> {
let Some(run) = get(conn, run)?.filter(|r| r.relation_id == relation) else {
return Ok(Err(UndoRefusal::NothingToUndo));
};
Ok(match undo_info(conn, &run)? {
None => Err(UndoRefusal::NothingToUndo),
Some(info) if !info.latest => Err(UndoRefusal::NotTheLatest),
Some(info) => Ok(info.safety),
})
}
/// Why a restore cannot be undone. /// Why a restore cannot be undone.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum UndoRefusal { pub enum UndoRefusal {
/// No such run, not of this relation, not completed, or it took no safety copy. /// No such run, not of this relation, not a restore that can be put back, or it took no safety copy.
NothingToUndo, NothingToUndo,
/// Something else was restored onto the target after it. Undoing an older restore would also undo that. /// Something else was restored onto the target after it. Undoing an older restore would also undo that.
NotTheLatest, NotTheLatest,
} }
impl Db { impl Db {
/// The safety copy that undoes `run`, if the run is a completed restore of this relation and the newest /// The safety copy that undoes `run`, if the run is a restore of this relation that can be put back and the
/// restore of its target. Whether the copy still exists in the vault is for the caller to check. /// newest restore of its target. Whether the copy still exists in the vault is for the caller to check.
pub fn undo_candidate( pub fn undo_candidate(
&self, &self,
run: &str, run: &str,
relation: &str, relation: &str,
) -> Result<std::result::Result<Uuid, UndoRefusal>> { ) -> Result<std::result::Result<Uuid, UndoRefusal>> {
undo_check(&self.conn.lock().unwrap(), run, relation)
}
/// What can be done about each run's restore, for a whole list under one lock: only runs that took a safety
/// copy appear. See `UndoInfo`.
pub fn undo_infos(
&self,
runs: &[RefreshRun],
) -> Result<std::collections::HashMap<String, UndoInfo>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
let Some(run) = let mut infos = std::collections::HashMap::new();
get(&conn, run)?.filter(|r| r.relation_id == relation && r.status == "completed") for run in runs {
else { if let Some(info) = undo_info(&conn, run)? {
return Ok(Err(UndoRefusal::NothingToUndo)); infos.insert(run.id.clone(), info);
}
}
Ok(infos)
}
/// The restore this undo puts back: the run whose restore took the safety copy that `run` restores.
pub fn undo_parent(&self, run: &RefreshRun) -> Result<Option<String>> {
let Some(safety) = run.snapshot_id.as_deref().filter(|_| run.is_undo()) else {
return Ok(None);
}; };
let Some(job) = &run.restore_job_id else { let conn = self.conn.lock().unwrap();
return Ok(Err(UndoRefusal::NothingToUndo)); Ok(conn
};
let safety: Option<Option<String>> = conn
.query_row( .query_row(
"SELECT safety_id FROM restore_jobs WHERE id = ?1 AND status = 'completed'", "SELECT r.id FROM refresh_runs r JOIN restore_jobs j ON j.id = r.restore_job_id
params![job], WHERE j.safety_id = ?1 AND r.target_id = ?2 AND r.id <> ?3",
params![safety, run.target_id, run.id],
|r| r.get(0), |r| r.get(0),
) )
.optional()?; .optional()?)
let Some(Some(safety)) = safety else {
return Ok(Err(UndoRefusal::NothingToUndo));
};
// Jobs are numbered in the order they were queued.
let later: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE target_id = ?1
AND rowid > (SELECT rowid FROM restore_jobs WHERE id = ?2)
AND status IN ('queued','running','applying','completed','recovery_required'))",
params![run.target_id, job],
|r| r.get(0),
)?;
if later {
return Ok(Err(UndoRefusal::NotTheLatest));
}
Ok(Ok(Uuid::parse_str(&safety)?))
} }
pub fn relation_target(&self, relation: &str) -> Result<Option<String>> { pub fn relation_target(&self, relation: &str) -> Result<Option<String>> {
@@ -350,8 +422,8 @@ impl Db {
requester_user_id: Option<&str>, requester_user_id: Option<&str>,
authorized_by: &str, authorized_by: &str,
idempotency_key: &str, idempotency_key: &str,
// a snapshot to restore instead of capturing one, and whether it is an undo of an earlier restore // a snapshot to restore instead of capturing one, and the run it undoes when it is the safety copy of one
snapshot: Option<(Uuid, bool)>, snapshot: Option<(Uuid, Option<&str>)>,
ttl_secs: i64, ttl_secs: i64,
max_active: i64, max_active: i64,
now: i64, now: i64,
@@ -379,8 +451,10 @@ impl Db {
if confirmation != confirmation_text(&source, &target, relation.version) { if confirmation != confirmation_text(&source, &target, relation.version) {
return Ok(Err(StartError::StaleConfirmation)); return Ok(Err(StartError::StaleConfirmation));
} }
let undoing = snapshot.and_then(|(_, of)| of);
// The run being undone does not count as busy: if its apply failed, undoing it is how it is recovered.
let busy: Option<String> = tx let busy: Option<String> = tx
.query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required')", params![relation.target_id], |r| r.get(0)) .query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required') AND id IS NOT ?2", params![relation.target_id, undoing], |r| r.get(0))
.optional()?; .optional()?;
if let Some(id) = busy { if let Some(id) = busy {
return Ok(Err(StartError::TargetBusy(id))); return Ok(Err(StartError::TargetBusy(id)));
@@ -389,12 +463,34 @@ impl Db {
if running >= max_active { if running >= max_active {
return Ok(Err(StartError::TooManyRuns)); return Ok(Err(StartError::TooManyRuns));
} }
if let Some((safety, Some(of))) = snapshot {
// Checked again inside this transaction: what was true when the request was read may not be now.
if !matches!(undo_check(&tx, of, relation_id)?, Ok(found) if found == safety) {
return Ok(Err(StartError::NothingToUndo));
}
if let Some(parent) = get(&tx, of)?.filter(|r| r.status == "recovery_required") {
// The failed apply no longer fences the target: this undo takes over from it, and puts back what
// the restore replaced. What it leaves behind is kept as this undo's own safety copy.
if let Some(job) = &parent.restore_job_id {
tx.execute(
"UPDATE restore_jobs SET status='reconciled', phase='rolled_back', updated_at=?2
WHERE id=?1 AND status='recovery_required' AND phase='apply_failed'",
params![job, now],
)?;
}
finish(&tx, &parent.id, "reconciled", None, now)?;
tx.execute(
"INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), 'restore.rolled_back', ?1)",
params![format!("run={} by={requester}", parent.id)],
)?;
}
}
let id = Uuid::new_v4().to_string(); let id = Uuid::new_v4().to_string();
// A run either takes a fresh backup first, or restores a snapshot the person picked: then it has // A run either takes a fresh backup first, or restores a snapshot the person picked: then it has
// no capture job, only a placeholder, and the snapshot is recorded from the start. // no capture job, only a placeholder, and the snapshot is recorded from the start.
let capture = match snapshot { let capture = match snapshot {
Some((_, true)) => format!("{UNDO}{id}"), Some((_, Some(_))) => format!("{UNDO}{id}"),
Some((_, false)) => format!("{EXISTING}{id}"), Some((_, None)) => format!("{EXISTING}{id}"),
None => { None => {
let application = Uuid::parse_str(&relation.source_application_id)?; let application = Uuid::parse_str(&relation.source_application_id)?;
let Some(capture) = let Some(capture) =

View File

@@ -10,7 +10,10 @@ use axum::body::Bytes;
use futures_core::Stream; use futures_core::Stream;
use std::io; use std::io;
use std::pin::Pin; use std::pin::Pin;
use std::sync::Arc; use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use uuid::Uuid; use uuid::Uuid;
@@ -170,6 +173,26 @@ pub struct ExportGate {
permits: Arc<Semaphore>, permits: Arc<Semaphore>,
/// Free space that must remain after the export has been written. /// Free space that must remain after the export has been written.
min_free: u64, min_free: u64,
/// Bytes promised to exports that are admitted and not finished yet. Free space alone cannot say
/// that, because an export that has only just started has barely written anything.
reserved: Arc<AtomicU64>,
}
/// The most one export may reserve: 64 of them (the concurrency ceiling) still fit in a `u64`.
const MAX_RESERVATION: u64 = 1 << 57;
/// An admitted export: its place among the running ones and the disk it was promised. Both are given
/// back when this is dropped.
pub struct Admission {
_permit: OwnedSemaphorePermit,
reserved: Arc<AtomicU64>,
size: u64,
}
impl Drop for Admission {
fn drop(&mut self) {
self.reserved.fetch_sub(self.size, Ordering::SeqCst);
}
} }
pub enum Refused { pub enum Refused {
@@ -184,6 +207,7 @@ impl ExportGate {
Self { Self {
permits: Arc::new(Semaphore::new(concurrency)), permits: Arc::new(Semaphore::new(concurrency)),
min_free, min_free,
reserved: Arc::default(),
} }
} }
@@ -200,17 +224,31 @@ impl ExportGate {
) )
} }
/// Admit one export of about `size` bytes into `dir`. The permit lives as long as the response body. /// Admit one export of about `size` bytes into `dir`. The slot and the bytes are held for as long as the
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<OwnedSemaphorePermit, Refused> { /// response body, so exports admitted together cannot each count on the same free space.
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<Admission, Refused> {
let permit = self let permit = self
.permits .permits
.clone() .clone()
.try_acquire_owned() .try_acquire_owned()
.map_err(|_| Refused::Busy)?; .map_err(|_| Refused::Busy)?;
// No disk is that large, and the cap keeps the running total from overflowing.
let size = size.min(MAX_RESERVATION);
// Reserve first, then check: concurrent callers can only over-refuse, never over-admit.
let earlier = self.reserved.fetch_add(size, Ordering::SeqCst);
let admission = Admission {
_permit: permit,
reserved: self.reserved.clone(),
size,
};
match free_bytes(dir) { match free_bytes(dir) {
// `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies. // `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies.
Some(free) if free < size.saturating_add(self.min_free) => Err(Refused::NoSpace), // Bytes already written by running exports are no longer free and are counted again in `earlier`; being
_ => Ok(permit), // that cautious is deliberate.
Some(free) if free < earlier.saturating_add(size).saturating_add(self.min_free) => {
Err(Refused::NoSpace)
}
_ => Ok(admission),
} }
} }
} }
@@ -248,7 +286,7 @@ pub fn sweep_stale(data_dir: &std::path::Path) -> usize {
/// the client went away, or the response was discarded) releases the permit and deletes the export. /// the client went away, or the response was discarded) releases the permit and deletes the export.
pub struct Guarded<S> { pub struct Guarded<S> {
inner: Pin<Box<S>>, inner: Pin<Box<S>>,
_permit: OwnedSemaphorePermit, _permit: Admission,
_dir: tempfile::TempDir, _dir: tempfile::TempDir,
db: Db, db: Db,
principal: Principal, principal: Principal,
@@ -261,7 +299,7 @@ pub struct Guarded<S> {
impl<S> Guarded<S> { impl<S> Guarded<S> {
pub fn new( pub fn new(
inner: S, inner: S,
permit: OwnedSemaphorePermit, permit: Admission,
dir: tempfile::TempDir, dir: tempfile::TempDir,
db: Db, db: Db,
principal: Principal, principal: Principal,
@@ -330,14 +368,14 @@ mod tests {
#[test] #[test]
fn a_download_is_named_after_the_application_the_time_and_the_engine() { fn a_download_is_named_after_the_application_the_time_and_the_engine() {
let name = download_name( let name = download_name(
"lti", "app",
taken(), taken(),
Some("Asia/Jakarta"), Some("Europe/Berlin"),
Some("postgres"), Some("postgres"),
id(), id(),
"dump", "dump",
); );
assert_eq!(name, "lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump"); assert_eq!(name, "app_2026-11-14T2030+0100_postgres_a1b2c3d4.dump");
let name = download_name("ledger", taken(), None, Some("mysql"), id(), "sql.gz"); let name = download_name("ledger", taken(), None, Some("mysql"), id(), "sql.gz");
assert_eq!(name, "ledger_2026-11-14T1930Z_mysql_a1b2c3d4.sql.gz"); assert_eq!(name, "ledger_2026-11-14T1930Z_mysql_a1b2c3d4.sql.gz");
// no engine (a folder snapshot): the part is left out // no engine (a folder snapshot): the part is left out
@@ -350,7 +388,7 @@ mod tests {
#[test] #[test]
fn an_unknown_time_zone_falls_back_to_utc() { fn an_unknown_time_zone_falls_back_to_utc() {
let name = download_name( let name = download_name(
"lti", "app",
taken(), taken(),
Some("Mars/Olympus"), Some("Mars/Olympus"),
Some("postgres"), Some("postgres"),
@@ -363,8 +401,8 @@ mod tests {
#[test] #[test]
fn two_snapshots_in_the_same_minute_get_different_names() { fn two_snapshots_in_the_same_minute_get_different_names() {
let other = Uuid::parse_str("ffffffff-0000-4000-8000-000000000000").unwrap(); let other = Uuid::parse_str("ffffffff-0000-4000-8000-000000000000").unwrap();
let a = download_name("lti", taken(), None, Some("postgres"), id(), "dump"); let a = download_name("app", taken(), None, Some("postgres"), id(), "dump");
let b = download_name("lti", taken(), None, Some("postgres"), other, "dump"); let b = download_name("app", taken(), None, Some("postgres"), other, "dump");
assert_ne!(a, b); assert_ne!(a, b);
} }
@@ -404,11 +442,11 @@ mod tests {
#[test] #[test]
fn the_header_carries_both_filename_forms() { fn the_header_carries_both_filename_forms() {
let header = content_disposition("lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump"); let header = content_disposition("app_2026-11-14T2030+0100_postgres_a1b2c3d4.dump");
assert_eq!( assert_eq!(
header, header,
"attachment; filename=\"lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump\"; \ "attachment; filename=\"app_2026-11-14T2030+0100_postgres_a1b2c3d4.dump\"; \
filename*=UTF-8''lti_2026-11-15T0230%2B0700_postgres_a1b2c3d4.dump" filename*=UTF-8''app_2026-11-14T2030%2B0100_postgres_a1b2c3d4.dump"
); );
} }
@@ -596,4 +634,45 @@ mod tests {
"a snapshot bigger than the disk" "a snapshot bigger than the disk"
); );
} }
#[test]
fn concurrent_exports_cannot_each_count_on_the_same_free_space() {
let dir = tempfile::tempdir().unwrap();
let free = free_bytes(dir.path()).expect("statvfs works on the temp dir");
// each export needs a bit over a third of what is free, so two fit on paper but not together
// (the disk may move under us a little, which is why the margin is generous)
let size = free / 3 + free / 20;
let gate = ExportGate::new(8, 0);
let first = gate.admit(dir.path(), size).ok().expect("one fits");
let second = gate.admit(dir.path(), size).ok().expect("two fit");
assert!(
matches!(gate.admit(dir.path(), size), Err(Refused::NoSpace)),
"the third would need more than the disk has once the first two are counted"
);
drop(first);
assert!(
gate.admit(dir.path(), size).is_ok(),
"a finished export gives its bytes back"
);
drop(second);
}
#[test]
fn a_refused_export_leaves_nothing_reserved() {
let dir = tempfile::tempdir().unwrap();
let gate = ExportGate::new(2, 0);
for _ in 0..3 {
assert!(matches!(
gate.admit(dir.path(), u64::MAX),
Err(Refused::NoSpace)
));
}
assert_eq!(gate.reserved.load(Ordering::SeqCst), 0);
let busy = ExportGate::new(1, 0);
let held = busy.admit(dir.path(), 5).ok().unwrap();
assert!(matches!(busy.admit(dir.path(), 7), Err(Refused::Busy)));
assert_eq!(busy.reserved.load(Ordering::SeqCst), 5);
drop(held);
assert_eq!(busy.reserved.load(Ordering::SeqCst), 0);
}
} }

View File

@@ -59,6 +59,7 @@ pub struct Limits {
oidc_login_source: Keyed, oidc_login_source: Keyed,
oidc_callback_source: Keyed, oidc_callback_source: Keyed,
audit_denial: Keyed, audit_denial: Keyed,
admin_token_failure: Keyed,
pub argon2: Arc<Semaphore>, pub argon2: Arc<Semaphore>,
trusted_proxies: Vec<IpAddr>, trusted_proxies: Vec<IpAddr>,
calls: AtomicU64, calls: AtomicU64,
@@ -75,6 +76,7 @@ impl Limits {
oidc_callback_source: RateLimiter::keyed(config.oidc_callback_source), oidc_callback_source: RateLimiter::keyed(config.oidc_callback_source),
// one audit row per source per minute, so a flood cannot fill the audit table // one audit row per source per minute, so a flood cannot fill the audit table
audit_denial: RateLimiter::keyed(per_minute(1, 1)), audit_denial: RateLimiter::keyed(per_minute(1, 1)),
admin_token_failure: RateLimiter::keyed(per_minute(10, 5)),
argon2: Arc::new(Semaphore::new(config.argon2_concurrency)), argon2: Arc::new(Semaphore::new(config.argon2_concurrency)),
trusted_proxies, trusted_proxies,
calls: AtomicU64::new(0), calls: AtomicU64::new(0),
@@ -131,6 +133,7 @@ impl Limits {
self.oidc_login_source.retain_recent(); self.oidc_login_source.retain_recent();
self.oidc_callback_source.retain_recent(); self.oidc_callback_source.retain_recent();
self.audit_denial.retain_recent(); self.audit_denial.retain_recent();
self.admin_token_failure.retain_recent();
} }
} }
@@ -154,6 +157,12 @@ impl Limits {
self.oidc_callback_source.check_key(&source).is_ok() self.oidc_callback_source.check_key(&source).is_ok()
} }
/// Counts one wrong admin token from `source`; false once that source has used up its budget.
pub fn admin_token_failure(&self, source: IpAddr) -> bool {
self.maintain();
self.admin_token_failure.check_key(&source).is_ok()
}
/// True at most once a minute per source: use it to decide whether a denial is audited. /// True at most once a minute per source: use it to decide whether a denial is audited.
pub fn audit_denial(&self, source: IpAddr) -> bool { pub fn audit_denial(&self, source: IpAddr) -> bool {
self.audit_denial.check_key(&source).is_ok() self.audit_denial.check_key(&source).is_ok()

View File

@@ -30,6 +30,7 @@ async fn main() -> Result<()> {
let addr: SocketAddr = listen.parse()?; let addr: SocketAddr = listen.parse()?;
let admin = admin::AdminGate::from_env()?; let admin = admin::AdminGate::from_env()?;
admin.validate_listener(addr)?; admin.validate_listener(addr)?;
let audit_retention = scheduler::audit_retention_from_env()?;
let wormhole = mtls::from_env()?; let wormhole = mtls::from_env()?;
if let Some(config) = &wormhole { if let Some(config) = &wormhole {
admin.validate_listener(config.listen)?; admin.validate_listener(config.listen)?;
@@ -81,6 +82,7 @@ async fn main() -> Result<()> {
state.configure_offsite()?; state.configure_offsite()?;
state.reconcile_capture_catalog().await?; state.reconcile_capture_catalog().await?;
state.start_offsite_worker(); state.start_offsite_worker();
scheduler::start_audit_retention(state.db.clone(), audit_retention);
scheduler::start_orbit_scheduler(state.clone()).await?; scheduler::start_orbit_scheduler(state.clone()).await?;
refresh::start(state.clone()); refresh::start(state.clone());
if state.sessions.enabled() { if state.sessions.enabled() {

View File

@@ -75,7 +75,16 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
mtls.listen mtls.listen
); );
loop { loop {
let (tcp, peer) = listener.accept().await.context("accept wormhole mTLS")?; let (tcp, peer) = match listener.accept().await {
Ok(accepted) => accepted,
Err(error) => {
// Out of file descriptors, an aborted handshake and the like pass; stopping the
// listener would end every Outpost's connection until a restart.
tracing::warn!(%error, "wormhole mTLS accept failed; continuing");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
continue;
}
};
let acceptor = acceptor.clone(); let acceptor = acceptor.clone();
let app = app.clone(); let app = app.clone();
tokio::spawn(async move { tokio::spawn(async move {
@@ -191,7 +200,7 @@ mod tests {
}; };
let mut state = crate::state::HubState::bootstrap( let mut state = crate::state::HubState::bootstrap(
dir.path().join("hub").to_str().unwrap(), dir.path().join("hub").to_str().unwrap(),
"synthetic-vault", "synthetic-vault-passphrase",
) )
.await .await
.unwrap(); .unwrap();

View File

@@ -32,6 +32,51 @@ pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
Ok(()) Ok(())
} }
const DEFAULT_AUDIT_RETENTION_DAYS: i64 = 90;
/// `TESSERA_AUDIT_RETENTION_DAYS`: how long structured audit events are kept.
/// Unset means 90 days; `0` keeps them forever.
pub fn audit_retention_from_env() -> Result<Option<i64>> {
parse_audit_retention(
std::env::var("TESSERA_AUDIT_RETENTION_DAYS")
.ok()
.as_deref(),
)
}
fn parse_audit_retention(value: Option<&str>) -> Result<Option<i64>> {
let Some(value) = value.map(str::trim).filter(|v| !v.is_empty()) else {
return Ok(Some(DEFAULT_AUDIT_RETENTION_DAYS));
};
let days: i64 = value
.parse()
.ok()
.filter(|days| (0..=36_500).contains(days))
.context(
"TESSERA_AUDIT_RETENTION_DAYS must be a whole number of days (0 keeps everything)",
)?;
Ok((days > 0).then_some(days))
}
/// Prunes audit events once now and then every hour.
pub fn start_audit_retention(db: crate::db::Db, retention_days: Option<i64>) {
let Some(days) = retention_days else {
info!("audit retention disabled: audit events are kept forever");
return;
};
tokio::spawn(async move {
loop {
let cutoff = Utc::now().timestamp() - days * 86_400;
match db.prune_audit_events(cutoff) {
Ok(0) => {}
Ok(n) => info!("pruned {n} audit event(s) older than {days} days"),
Err(e) => error!("audit retention: {e}"),
}
sleep(Duration::from_secs(3600)).await;
}
});
}
pub(crate) fn orbit_schedule(expression: &str) -> Result<Schedule, cron::error::Error> { pub(crate) fn orbit_schedule(expression: &str) -> Result<Schedule, cron::error::Error> {
if expression.split_whitespace().count() == 5 { if expression.split_whitespace().count() == 5 {
Schedule::from_str(&format!("0 {expression}")) Schedule::from_str(&format!("0 {expression}"))
@@ -116,6 +161,16 @@ pub(crate) fn tick_capture_schedules(db: &crate::db::Db, now: DateTime<Utc>) ->
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn audit_retention_defaults_to_ninety_days_and_zero_disables_it() {
assert_eq!(parse_audit_retention(None).unwrap(), Some(90));
assert_eq!(parse_audit_retention(Some(" ")).unwrap(), Some(90));
assert_eq!(parse_audit_retention(Some("30")).unwrap(), Some(30));
assert_eq!(parse_audit_retention(Some("0")).unwrap(), None);
assert!(parse_audit_retention(Some("-1")).is_err());
assert!(parse_audit_retention(Some("soon")).is_err());
}
#[test] #[test]
fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() { fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() {
let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap(); let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap();

View File

@@ -409,7 +409,8 @@ mod tests {
#[test] #[test]
fn pg_dump_keeps_the_url_out_of_argv() { fn pg_dump_keeps_the_url_out_of_argv() {
let target = let target =
parse_postgres_url("postgres://migrator:s%3Acret@db.internal:5433/billing").unwrap(); parse_postgres_url("postgres://migrator:s%3Acret@example.invalid:5433/billing")
.unwrap();
assert_eq!(target.password, "s:cret"); assert_eq!(target.password, "s:cret");
let args = dump_args("custom").unwrap(); let args = dump_args("custom").unwrap();
let pgpass = write_pgpass(&target, false).unwrap(); let pgpass = write_pgpass(&target, false).unwrap();

View File

@@ -172,7 +172,7 @@ impl Offsite {
)?; )?;
let size = file.as_file().metadata()?.len(); let size = file.as_file().metadata()?.len();
file.as_file().sync_all()?; file.as_file().sync_all()?;
file.persist(dest)?; file.persist_noclobber(dest)?;
Ok(size) Ok(size)
} }

View File

@@ -43,6 +43,9 @@ struct OutpostRepository {
password: String, password: String,
} }
/// Shortest passphrase accepted for a new vault. Existing vaults keep opening with a warning.
pub const MIN_PASSPHRASE_CHARS: usize = 16;
impl Vault { impl Vault {
pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> { pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
if passphrase == "dev-vault-key" { if passphrase == "dev-vault-key" {
@@ -50,6 +53,10 @@ impl Vault {
"refusing to initialize a vault with the published dev passphrase; choose a private passphrase" "refusing to initialize a vault with the published dev passphrase; choose a private passphrase"
); );
} }
anyhow::ensure!(
passphrase.chars().count() >= MIN_PASSPHRASE_CHARS,
"the vault passphrase must be at least {MIN_PASSPHRASE_CHARS} characters"
);
let root = root.as_ref().to_path_buf(); let root = root.as_ref().to_path_buf();
fs::create_dir_all(root.join("data"))?; fs::create_dir_all(root.join("data"))?;
fs::create_dir_all(root.join("snapshots"))?; fs::create_dir_all(root.join("snapshots"))?;
@@ -81,6 +88,16 @@ impl Vault {
anyhow::bail!("vault not initialized"); anyhow::bail!("vault not initialized");
} }
restrict_dir(&root.join("keys"))?; restrict_dir(&root.join("keys"))?;
// Not refused: that would lock existing deployments out of their own backups.
if passphrase == "dev-vault-key" {
tracing::warn!(
"this vault uses the published dev passphrase; rotate it to a private one"
);
} else if passphrase.chars().count() < MIN_PASSPHRASE_CHARS {
tracing::warn!(
"the vault passphrase is shorter than {MIN_PASSPHRASE_CHARS} characters; a new vault would refuse it"
);
}
let salt = root.join("keys/tessera.salt"); let salt = root.join("keys/tessera.salt");
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = Self::load_index(&root)?; let index = Self::load_index(&root)?;
@@ -655,7 +672,8 @@ impl Vault {
} }
let len = temp.as_file().metadata()?.len(); let len = temp.as_file().metadata()?.len();
temp.as_file().sync_all()?; temp.as_file().sync_all()?;
temp.persist(dest)?; // never replace a file that is already there
temp.persist_noclobber(dest)?;
Ok(len) Ok(len)
} }
@@ -829,7 +847,7 @@ mod tests {
rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes); rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes);
let file = source.join("large.bin"); let file = source.join("large.bin");
fs::write(&file, &bytes).unwrap(); fs::write(&file, &bytes).unwrap();
let mut vault = Vault::init(dir.path().join("vault"), "secret").unwrap(); let mut vault = Vault::init(dir.path().join("vault"), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest { let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(),
@@ -882,7 +900,7 @@ mod tests {
#[test] #[test]
fn init_snap_list_restore() { fn init_snap_list_restore() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap(); let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest { let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(),
@@ -905,7 +923,7 @@ mod tests {
#[test] #[test]
fn dry_run_writes_nothing() { fn dry_run_writes_nothing() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap(); let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest { let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(),
@@ -922,7 +940,7 @@ mod tests {
#[test] #[test]
fn orbit_decay_keeps_other_orbits_recoverable() { fn orbit_decay_keeps_other_orbits_recoverable() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap(); let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let orbit_id = Uuid::new_v4(); let orbit_id = Uuid::new_v4();
let other_id = Uuid::new_v4(); let other_id = Uuid::new_v4();
let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap(); let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap();
@@ -959,7 +977,7 @@ mod tests {
#[test] #[test]
fn new_snapshots_are_encrypted_and_legacy_json_still_reads() { fn new_snapshots_are_encrypted_and_legacy_json_still_reads() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap(); let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let legacy_id = Uuid::new_v4(); let legacy_id = Uuid::new_v4();
let legacy = StoredSnapshot { let legacy = StoredSnapshot {
id: legacy_id, id: legacy_id,
@@ -1018,6 +1036,15 @@ mod tests {
assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6); assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6);
} }
#[test]
fn new_vaults_need_a_long_passphrase_but_existing_short_ones_still_open() {
let dir = tempfile::tempdir().unwrap();
assert!(Vault::init(dir.path(), "fifteen-chars-x").is_err());
assert!(Vault::init(dir.path(), "sixteen-chars-xx").is_ok());
// a vault made before the rule: same data, shorter passphrase never got in, so reopen with the long one
assert!(Vault::open(dir.path(), "sixteen-chars-xx").is_ok());
}
#[test] #[test]
fn init_rejects_published_dev_passphrase() { fn init_rejects_published_dev_passphrase() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();

View File

@@ -107,7 +107,7 @@ Forwarded requests are rejected in this mode, but that is not a proxy trust
boundary: never reverse-proxy a development listener. Compose keeps the mode off boundary: never reverse-proxy a development listener. Compose keeps the mode off
and needs operator/API credentials even with a localhost published port. and needs operator/API credentials even with a localhost published port.
Generate an Argon2id hash and set `TESSERA_OPERATOR_PASSWORD_HASH` to the result. The hub reads the password from stdin in hash mode. For example, from an interactive Bash shell: In the container, run the hash mode through the image: `printf '%s\n' "$pw" | docker run --rm -i --entrypoint tessera-hub <image> --hash-operator-password`. Generate an Argon2id hash and set `TESSERA_OPERATOR_PASSWORD_HASH` to the result. The hub reads the password from stdin in hash mode. For example, from an interactive Bash shell:
```bash ```bash
read -rs -p 'Operator password: ' tessera_operator_password; printf '\n' read -rs -p 'Operator password: ' tessera_operator_password; printf '\n'
@@ -115,7 +115,7 @@ export TESSERA_OPERATOR_PASSWORD_HASH="$(printf '%s\n' "$tessera_operator_passwo
unset tessera_operator_password unset tessera_operator_password
``` ```
Set `TESSERA_OPERATOR_NAME` for the audited identity, or use the default `operator`. Serve the browser over HTTPS outside loopback. Sessions expire after eight hours or a hub restart. Browser mutations require the session's CSRF token. API and CLI callers use the separate `TESSERA_ADMIN_TOKEN`. Use the bundled HTTP CLI on the hub's loopback listener when sending the token. Set `TESSERA_OPERATOR_NAME` for the audited identity, or use the default `operator`. Serve the browser over HTTPS outside loopback. Sessions expire after eight hours. They survive a hub restart as long as the operator credential is unchanged; rotating or removing `TESSERA_OPERATOR_PASSWORD_HASH` invalidates them. Browser mutations require the session's CSRF token. API and CLI callers use the separate `TESSERA_ADMIN_TOKEN`. Use the bundled HTTP CLI on the hub's loopback listener when sending the token.
Legacy full-upload agents now need an explicit orbit assignment. With operator Legacy full-upload agents now need an explicit orbit assignment. With operator
CSRF or an admin API token, call `PUT /api/v1/orbits/{orbit-id}/outpost` with CSRF or an admin API token, call `PUT /api/v1/orbits/{orbit-id}/outpost` with
@@ -270,7 +270,8 @@ immediately. A denial is written to the audit log at most once a minute per sour
- Limiter state is in memory: it resets when the hub restarts and is not shared - Limiter state is in memory: it resets when the hub restarts and is not shared
between hub processes. between hub processes.
**Shared admin token.** `TESSERA_ADMIN_TOKEN` is a transition aid. Set **Shared admin token.** `TESSERA_ADMIN_TOKEN` is a transition aid. It must be at least
32 characters; generate one with `openssl rand -base64 32`. Set
`TESSERA_ADMIN_TOKEN_EXPIRES` (`YYYY-MM-DD`, end of that day UTC, or an RFC 3339 `TESSERA_ADMIN_TOKEN_EXPIRES` (`YYYY-MM-DD`, end of that day UTC, or an RFC 3339
timestamp) and the hub refuses the token after that time. Without it the hub logs a timestamp) and the hub refuses the token after that time. Without it the hub logs a
warning at start. Every use is audited as the `legacy-admin-token` service principal. warning at start. Every use is audited as the `legacy-admin-token` service principal.
@@ -378,13 +379,22 @@ orbit's); otherwise the answer is `422 snapshot_unusable` and nothing is started
everything else is the same: one run per target at a time, idempotency, cancelling until the target is overwritten, and everything else is the same: one run per target at a time, idempotency, cancelling until the target is overwritten, and
the authorisation checks right before overwriting. The same snapshot can be restored to several targets, and again later. the authorisation checks right before overwriting. The same snapshot can be restored to several targets, and again later.
A completed restore can be undone: `undo_of` (the id of that run) restores the safety copy the restore took of its target A restore can be undone: `undo_of` (the id of that run) restores the safety copy the restore took of its target
back onto the same target, through the same checks, countdown, progress and a new safety copy, so the undo can itself be back onto the same target, through the same checks, countdown, progress and a new safety copy, so the undo can itself be
undone. It is refused with `422 nothing_to_undo` when the run is not a completed restore of this relation, when something undone. A restore that completed, one an administrator reconciled, and one whose apply failed (the agent reported it) can
was restored onto the target after it (only the newest restore of a target can be undone), or when the safety copy has be undone; for the last, undoing is the recovery: the failed apply stops fencing the target in the same transaction
been removed. A safety copy is only ever accepted as a source for the target it was taken from, whether it arrives through that starts the undo (job phase `rolled_back`, audited as `restore.rolled_back`). An apply whose agent went silent
(`lease_lost`) may still be writing, so it waits for an administrator to reconcile it first. The request is refused with
`422 nothing_to_undo` when the run is none of these for this relation, when something was restored onto the target after
it (only the newest restore of a target can be undone), or when the safety copy has been removed. A safety copy is only ever accepted as a source for the target it was taken from, whether it arrives through
`undo_of` or `snapshot_id`; the check is made by the hub, and again by the agent (its restore artifact carries `undo_of` or `snapshot_id`; the check is made by the hub, and again by the agent (its restore artifact carries
`rollback`). Run views say `undo` and `undo_available`, never where the copy is. The run is audited as `rollback`). Run views say `undo`, `undo_of` (the restore an undo puts back), `restore_job_id` and `undo_available`, never where
the copy is. A restore that took a safety copy also says `undo_state`: `available` (with `undo_kept_until`, when retention
may first forget the copy: a week after it was taken, and later while it is one of the target's newest few),
`superseded` (something was restored after it) or `expired` (retention has forgotten the copy; this wins over
`superseded`). The Activity log shows `expired` as "Safety backup expired" in place of a link, and lists an undo
under the restore it reverses. Run lists work out all of this with one database pass and a file lookup per copy, and
read the vault only for the newest restore of each target. The run is audited as
`refresh.undo_started`. Undoing needs the same permission as restoring. `refresh.undo_started`. Undoing needs the same permission as restoring.
In the web UI there is no separate Refresh screen. Restoring lives in the Vault: pick an orbit, capture it if you want the In the web UI there is no separate Refresh screen. Restoring lives in the Vault: pick an orbit, capture it if you want the
@@ -392,7 +402,7 @@ latest data (or click a snapshot that is already there), and in the snapshot det
disabled with "No restore point" when no relation has been set up for the orbit. The modal offers the restore points disabled with "No restore point" when no relation has been set up for the orbit. The modal offers the restore points
(Development and/or Staging) that the person may use, shows what will be overwritten, and after **Begin restore** counts (Development and/or Staging) that the person may use, shows what will be overwritten, and after **Begin restore** counts
ten seconds in the browser, during which **Abort** sends nothing. Then it follows four steps (Checking, Safety copy, ten seconds in the browser, during which **Abort** sends nothing. Then it follows four steps (Checking, Safety copy,
Applying, Completed) from the run, and Abort still works until Applying starts. A finished restore offers **Undo this restore**, and the modal offers Applying, Completed) from the run, and Abort still works until Applying starts. A finished restore offers **Undo this restore** (**Roll back** when it was interrupted), and the modal offers
**Undo last restore** for the chosen restore point while that is still possible. Safety copies are not listed with the **Undo last restore** for the chosen restore point while that is still possible. Safety copies are not listed with the
backups. A person needs to see the orbit's snapshots (for example the viewer role on the orbit) and a relation grant; backups. A person needs to see the orbit's snapshots (for example the viewer role on the orbit) and a relation grant;
administrators can also restore to any other registered target from the same modal. administrators can also restore to any other registered target from the same modal.

View File

@@ -139,8 +139,8 @@ Tone: short sentences, metaphor in headings, facts in telemetry panels.
## Security baseline ## Security baseline
1. **Vault key:** New vaults use Argon2id (19 MiB, time cost 2, parallelism 1). The salt is `keys/tessera.salt` (mode 0600) and the parameters are `keys/kdf.json`. A salt with no `kdf.json` stays PBKDF2-HMAC-SHA256, 100,000 iterations, so vaults created before Argon2id still open. The derived key is not stored. Never log the passphrase. New vaults refuse the published passphrase `dev-vault-key`. New snapshot metadata is AES-GCM ciphertext in `{id}.json.enc`. Existing plaintext `{id}.json` files still list and restore. Chunk index JSON stays plaintext. 1. **Vault key:** New vaults use Argon2id (19 MiB, time cost 2, parallelism 1). The salt is `keys/tessera.salt` (mode 0600) and the parameters are `keys/kdf.json`. A salt with no `kdf.json` stays PBKDF2-HMAC-SHA256, 100,000 iterations, so vaults created before Argon2id still open. The derived key is not stored. Never log the passphrase. New vaults refuse a well-known development passphrase. New snapshot metadata is AES-GCM ciphertext in `{id}.json.enc`. Existing plaintext `{id}.json` files still list and restore. Chunk index JSON stays plaintext.
2. **Hub auth:** `TESSERA_ADMIN_TOKEN` is optional and local. When it is unset, the hub logs that snapshot, orbit list/create/run, reconstitute, and pairing routes are open to loopback peers only; every other peer gets 401. When it is set, every peer, including loopback, must send `Authorization: Bearer <token>` or `X-Tessera-Admin-Token`. The compare is constant time. `/health`, OpenAPI, wormhole claim, and wormhole upload are not on this gate. The default listen address is `127.0.0.1:8787`. The canvas does not send the token, so a token-protected hub and a Docker-published port (the peer inside the container is not loopback) will 401 those routes from the page. OIDC is not implemented. 2. **Hub auth:** Browser access uses server-side sessions: OIDC sign-in (authorization code with PKCE) and an emergency operator account. Every route passes one central gate: authenticate, resolve the resource, then check the caller's grants. Management actions are administrator-only; non-admins can only hold `orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download` and per-relation `refresh.run`. Outpost tokens and pairing codes are stored as digests. Requests are rate limited. The per-route matrix is in `docs/auth-endpoint-contract.md`. Behind a reverse proxy, set `TESSERA_TRUSTED_PROXIES` to the proxies you operate. The default listen address is `127.0.0.1:8787`.
3. **Agents:** No vault master key. After pairing, the hub issues an upload token stored in SQLite. The token survives a hub restart. Claim is an atomic update of a pairing code that has not expired. 3. **Agents:** No vault master key. After pairing, the hub issues an upload token stored in SQLite. The token survives a hub restart. Claim is an atomic update of a pairing code that has not expired.
4. **Wormhole:** A Restic agent sends missing chunks to its own authenticated, append-only REST repository and registers the finished snapshot using its paired token. The hub checks that the token belongs to the outpost assigned to that orbit. Legacy uploads require `total_bytes`. Chunks are written at `offset` into a mode `0600` `.part` file. When the ranges cover the payload, the hub stores it in Restic, applies decay, and deletes the `.part`. A later chunk on a sealed session is 409. `TESSERA_WORMHOLE_MTLS=1` (or `true`) starts a separate rustls listener that requires a client certificate. It needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is running, the plain HTTP upload and commit routes return 403. An `https://` agent needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`. 4. **Wormhole:** A Restic agent sends missing chunks to its own authenticated, append-only REST repository and registers the finished snapshot using its paired token. The hub checks that the token belongs to the outpost assigned to that orbit. Legacy uploads require `total_bytes`. Chunks are written at `offset` into a mode `0600` `.part` file. When the ranges cover the payload, the hub stores it in Restic, applies decay, and deletes the `.part`. A later chunk on a sealed session is 409. `TESSERA_WORMHOLE_MTLS=1` (or `true`) starts a separate rustls listener that requires a client certificate. It needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is running, the plain HTTP upload and commit routes return 403. An `https://` agent needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`.
5. **Providers:** Filesystem and Postgres are in this release. The command provider is rejected with `command provider is outside this release; use filesystem or postgres`. Postgres parses `postgres://` or `postgresql://`, writes the password to a mode `0600` pgpass file, and passes `PGPASSFILE`, `PGHOST`, `PGPORT`, `PGUSER`, and `PGDATABASE`. The URL and password are not process arguments. 5. **Providers:** Filesystem and Postgres are in this release. The command provider is rejected with `command provider is outside this release; use filesystem or postgres`. Postgres parses `postgres://` or `postgresql://`, writes the password to a mode `0600` pgpass file, and passes `PGPASSFILE`, `PGHOST`, `PGPORT`, `PGUSER`, and `PGDATABASE`. The URL and password are not process arguments.

View File

@@ -50,7 +50,7 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep
- Icon-only keys (Pause or Resume motion, Big screen, Sign out, Search) share one size, `--key`, and one gap, `--key-gap`, and keep their names in `aria-label` and the tooltip. Read-outs that sit beside keys (Hub online, the Big Screen status and telemetry) are recessed plates of the same height. Telemetry readings carry a lamp: ice for orbits, mint for failed at zero, ember diamond for failed above zero, a pale diamond for snapshots, violet for payload. - Icon-only keys (Pause or Resume motion, Big screen, Sign out, Search) share one size, `--key`, and one gap, `--key-gap`, and keep their names in `aria-label` and the tooltip. Read-outs that sit beside keys (Hub online, the Big Screen status and telemetry) are recessed plates of the same height. Telemetry readings carry a lamp: ice for orbits, mint for failed at zero, ember diamond for failed above zero, a pale diamond for snapshots, violet for payload.
- **Window | Radar** is a two-position view switch on the canopy sill (`ViewSwitch` in `VaultScene.tsx`, a `radiogroup`; arrow keys move between positions). Its thumb rides the shared spring and tints amber for the window and mint for radar. It switches between the realistic and radar looks. The choice is remembered per browser. Without WebGL2 the button is hidden. The radar sweep runs on its own clock rather than the scene's, so it keeps turning on a locked map. Reduced motion switches looks at once and holds the sweep still and evenly lit, and the still quality tier does the same. A page that loads with the radar look applies it at once, with no wave. While the sweep runs the map redraws at the tier's frame-rate cap, so radar costs more battery than a locked realistic map, which draws nothing. - **Window | Radar** is a two-position view switch on the canopy sill (`ViewSwitch` in `VaultScene.tsx`, a `radiogroup`; arrow keys move between positions). Its thumb rides the shared spring and tints amber for the window and mint for radar. It switches between the realistic and radar looks. The choice is remembered per browser. Without WebGL2 the button is hidden. The radar sweep runs on its own clock rather than the scene's, so it keeps turning on a locked map. Reduced motion switches looks at once and holds the sweep still and evenly lit, and the still quality tier does the same. A page that loads with the radar look applies it at once, with no wave. While the sweep runs the map redraws at the tier's frame-rate cap, so radar costs more battery than a locked realistic map, which draws nothing.
- The radar look draws range rings every 6 M, a bearing scale at 30 M just outside the disk, a crosshair and a rotating sweep head whose phosphor fades behind it. The lensed grid only shows outside about 20 M, so it never crowds the disk. The disk is drawn as contour bands equal in log brightness, and the long dim outer disk stays faint so the inner contours carry the weight. - The radar look draws range rings every 6 M, a bearing scale at 30 M just outside the disk, a crosshair and a rotating sweep head whose phosphor fades behind it. The lensed grid only shows outside about 20 M, so it never crowds the disk. The disk is drawn as contour bands equal in log brightness, and the long dim outer disk stays faint so the inner contours carry the weight.
- A realistic and a stylized radar look share the same trace. The radar look arrives as a wave spreading outward from the hole: each pixel picks its look from its distance to a spring-driven front, with a thin leading edge (mint going to radar, amber coming back). `look.ts` holds the spring and queues a request made mid-wave rather than reversing it. `web/blackhole-proto.html` is a standalone page for tuning the look; Vite serves it in development and the build ignores it. Add `?throttle=N` to emulate a GPU N times slower. - A realistic and a stylized radar look share the same trace. The radar look arrives as a wave spreading outward from the hole: each pixel picks its look from its distance to a spring-driven front, with a thin leading edge (mint going to radar, amber coming back). `look.ts` holds the spring and queues a request made mid-wave rather than reversing it.
## Orbit activity ## Orbit activity

View File

@@ -1,89 +1,103 @@
# Kontrak otorisasi HTTP # HTTP authorization contract
Inventaris A01, 11 November 2026. Gate saat ini masih admin global; kolom This is the authorization contract for every HTTP route the hub registers. The
permission/scope adalah kontrak yang harus diterapkan A11–A12, bukan klaim RBAC `access_tests` suite generates its authorization matrix from the table below, and
sudah tersedia. A02 menutup isolasi upload legacy; A03 menghapus fallback loopback. the `auth_contract` tests fail if a registered route has no row, so the table and
the code cannot drift apart silently.
Gate (M5): `authenticate` lalu resolve resource lalu gate. Permission yang dapat diberikan ke non-admin hanya `orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download`; semua permission lain hanya dimiliki administrator terkonfigurasi (403 tanpa lookup resource). Resource di luar scope = 404, terlihat tapi tanpa izin = 403, daftar tanpa satu pun akses = 403. Tes `access_tests` membangkitkan matriks dari tabel ini. Order of checks, everywhere: authenticate, then resolve the resource, then apply
the gate. Grants are read from the database on every request, so a revoke takes
effect on the next request. The permissions that can be granted to a non-admin are
`orbit.read`, `snapshot.read`, `capture.run` and `snapshot.download`; every other
permission belongs only to a configured administrator, and anyone else gets 403
without any resource lookup. A resource outside the caller's scope answers 404, a
visible resource without the needed permission answers 403, and a list for which
the caller holds no access at all answers 403.
Human = sesi user aktif atau service token dengan grant; token Outpost ditolak. A human is an active user session or a service token with a grant; an Outpost
Mutasi cookie memerlukan CSRF. Anonymous/token salah: 401; resource di luar scope: token is rejected on human routes. Cookie-authenticated mutations require a CSRF
404; aksi tanpa permission pada resource terlihat: 403. Parsing request invalid token. An anonymous caller or a wrong token gets 401. Request parsing errors may
dapat menghasilkan 400/415/422 sebelum gate, tetapi tidak boleh mengakses data. answer 400, 415 or 422 before the gate, but never expose data. An Outpost is an
Outpost = token aktif, assignment owner dan lease/fence bila berlaku; bukan token active token with an owner assignment and, where it applies, a lease or fence; it
admin/browser. Semua status/data job hanya di scope owner/admin yang berizin. is not an admin or browser token. Job status and data are visible only within the
owner's scope, or to an administrator.
| Route | Methods | Principal | Permission | Scope | Data yang boleh keluar | Loopback callers get no special treatment: when no credentials are configured and
local development mode is not explicitly enabled, requests are rejected, including
requests that arrive with forwarded-for headers claiming to be local.
| Route | Methods | Principal | Permission | Scope | Data allowed out |
| --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- |
| /health | GET | public | — | — | liveness statis | | /health | GET | public | — | — | static liveness |
| /api-doc/openapi.json | GET | public | — | — | schema tanpa config/secret | | /api-doc/openapi.json | GET | human | session.self | any signed-in caller | requires sign-in or the admin token; public only when TESSERA_PUBLIC_OPENAPI=true |
| /api/v1/operator/session | GET | public | — | current session | status, actor, CSRF sesi sendiri; no-store | | /api/v1/operator/session | GET | public | — | current session | status, actor and CSRF token of the caller's own session; no-store |
| /api/v1/operator/session | DELETE | human | session.self | current session | tidak ada; CSRF wajib | | /api/v1/operator/session | DELETE | human | session.self | current session | nothing; CSRF required |
| /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store | | /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store |
| /api/v1/auth/oidc/login | GET | public | — | OIDC configured | redirect to the IdP; sets one-time Lax correlation cookie; 404 when OIDC is off | | /api/v1/auth/oidc/login | GET | public | — | OIDC configured | redirect to the IdP; sets one-time Lax correlation cookie; 404 when OIDC is off |
| /api/v1/auth/oidc/callback | GET | public | — | login transaction + correlation cookie | redirect to `/`; session cookie only on success, fixed error code otherwise; no tokens | | /api/v1/auth/oidc/callback | GET | public | — | login transaction + correlation cookie | redirect to `/`; session cookie only on success, fixed error code otherwise; no tokens |
| /api/v1/access/grants | GET | human | access.manage | admin | daftar grant, grant refresh per relasi, role, permission yang dapat diberikan dan yang khusus admin; no-store | | /api/v1/access/grants | GET | human | access.manage | admin | list of grants, refresh grants per relation, roles, and which permissions are grantable and which are admin-only; no-store |
| /api/v1/access/grants | POST,PUT | human | access.manage | admin | POST: grant baru (role, permission, atau daftar permission; scope global/orbit; expiry); PUT: ganti atau perpanjang sekumpulan grant orang/grup dan orbit yang sama secara atomik; alasan penolakan dalam `{"reason"}`; diaudit per id | | /api/v1/access/grants | POST,PUT | human | access.manage | admin | POST: a new grant (role, permission, or list of permissions; global or per-orbit scope; expiry); PUT: atomically replace or extend the set of grants for the same person or group and orbit; the reason for a refusal is returned in `{"reason"}`; audited per id |
| /api/v1/access/grants/:id | DELETE | human | access.manage | admin | tidak ada; berlaku pada request berikutnya; diaudit | | /api/v1/access/grants/:id | DELETE | human | access.manage | admin | nothing; effective on the next request; audited |
| /api/v1/access/users | GET | human | access.manage | admin | daftar user (tanpa kredensial); no-store | | /api/v1/access/users | GET | human | access.manage | admin | list of users (no credentials); no-store |
| /api/v1/access/users/:id | PUT | human | access.manage | admin | tidak ada; menonaktifkan juga memutus semua sesi; tidak untuk diri sendiri/akun darurat | | /api/v1/access/users/:id | PUT | human | access.manage | admin | nothing; deactivating a user also ends all of their sessions; not allowed on yourself or the emergency account |
| /api/v1/access/users/:id/revoke-sessions | POST | human | access.manage | admin | tidak ada; semua sesi user berakhir | | /api/v1/access/users/:id/revoke-sessions | POST | human | access.manage | admin | nothing; all of the user's sessions end |
| /api/v1/me/preferences | GET,PUT | human | session.self | current account | pilihan tampilan sendiri (look: window atau radar); no-store; CSRF pada PUT; token/dev tanpa akun: GET kosong, PUT 404 | | /api/v1/me/preferences | GET,PUT | human | session.self | current account | the caller's own display choice (look: window or radar); no-store; CSRF on PUT; for tokens and dev sessions without an account GET is empty and PUT answers 404 |
| /api/v1/orbits/:id | PUT | human | orbit.manage | admin | hanya name (1-128, tanpa karakter kontrol, unik tanpa memedulikan huruf besar); id, provider, jadwal, retensi tidak berubah; snapshot lama tampil dengan nama terkini; diaudit `orbit.renamed` | | /api/v1/orbits/:id | PUT | human | orbit.manage | admin | name only (1-128 characters, no control characters, unique ignoring case); id, provider, schedule and retention are unchanged; existing snapshots show the current name; audited as `orbit.renamed` |
| /api/v1/orbits/:id/environment | PUT | human | orbit.manage | admin | tidak ada; menandai sumber (production/staging/development); diaudit | | /api/v1/orbits/:id/environment | PUT | human | orbit.manage | admin | nothing; labels the source (production, staging or development); audited |
| /api/v1/restore-targets/:id | PUT | human | relation.manage | admin | hanya name (1-128, tanpa karakter kontrol); id, identity, outpost, relasi, dan job lama tidak berubah; diaudit `restore_target.renamed` | | /api/v1/restore-targets/:id | PUT | human | relation.manage | admin | name only (1-128 characters, no control characters); id, identity, Outpost, relations and past jobs are unchanged; audited as `restore_target.renamed` |
| /api/v1/restore-targets/:id/environment | PUT | human | relation.manage | admin | relasi aktif ke target yang diberi label production berakhir seketika; diaudit | | /api/v1/restore-targets/:id/environment | PUT | human | relation.manage | admin | active relations to a target labelled production end immediately; audited |
| /api/v1/relations | GET,POST | human | relation.manage | admin | daftar relasi, orbit dan target untuk wizard (dengan identity); POST membuat relasi atau menyebut aturan yang menolak | | /api/v1/relations | GET,POST | human | relation.manage | admin | list of relations, orbits and targets for the wizard (with identity); POST creates a relation or names the rule that refused it |
| /api/v1/relations/:id | PUT,DELETE | human | relation.manage | admin | PUT = versi baru (id baru, grant tidak ikut); DELETE menonaktifkan; diaudit | | /api/v1/relations/:id | PUT,DELETE | human | relation.manage | admin | PUT creates a new version (new id, grants do not carry over); DELETE deactivates; audited |
| /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | grant refresh.run per relasi (user atau grup, expiry); diaudit | | /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | `refresh.run` grants per relation (user or group, expiry); audited |
| /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | berlaku pada request berikutnya; diaudit | | /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | effective on the next request; audited |
| /api/v1/refresh-relations | GET | human | refresh.run | relasi yang di-grant | nama dan environment saja; tanpa identity, host, Outpost, application id; 403 bila tanpa grant | | /api/v1/refresh-relations | GET | human | refresh.run | granted relations | name and environment only; no identity, host, Outpost or application id; 403 without a grant |
| /api/v1/refresh-runs | GET,POST | human | refresh.run | relasi yang di-grant | POST: relation_id + konfirmasi `REFRESH <sumber> TO <target> v<versi>` + kunci idempotensi; `undo_of` opsional (id run restore selesai terbaru pada targetnya): kembalikan target dari safety copy restore itu (422 `nothing_to_undo`; safety hanya diterima untuk target asalnya); `snapshot_id` opsional: restore snapshot yang sudah ada milik orbit sumber relasi itu (bukan safety, bukan orbit lain; 422 `snapshot_unusable`), tanpa itu run mengambil capture baru; tidak memilih target; 404 bila bukan pemegang grant; GET: run milik sendiri atau relasi yang di-grant (admin: semua), tanpa snapshot id dan pemohon untuk non-admin | | /api/v1/refresh-runs | GET,POST | human | refresh.run | granted relations | POST: relation_id + confirmation `REFRESH <source> TO <target> v<version>` + idempotency key; optional `undo_of` (id of the target's latest restore run that finished, was reconciled, or failed during apply): restore the target from that run's safety copy (422 `nothing_to_undo`; a safety copy is only accepted for its own target); optional `snapshot_id`: restore an existing snapshot of the relation's source orbit (not a safety copy, not another orbit's; 422 `snapshot_unusable`), otherwise the run takes a fresh capture; the caller does not choose the target; 404 for anyone without a grant; GET: the caller's own runs or those of granted relations (admin: all), without snapshot id or requester for non-admins |
| /api/v1/refresh-runs/:id | GET,DELETE | human | refresh.run | admin, pemohon, atau pemegang grant relasinya | GET 404 bagi yang lain; DELETE hanya pemohon atau admin (pemegang grant lain 403) dan hanya sebelum apply, sesudahnya 409 | | /api/v1/refresh-runs/:id | GET,DELETE | human | refresh.run | admin, requester, or holder of a grant on its relation | GET answers 404 for anyone else; DELETE only by the requester or an admin (other grant holders get 403) and only before apply, afterwards 409 |
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store | | /api/v1/operator/login | POST | public | — | emergency account | opaque cookie and CSRF token; rate limited, no-store |
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter | | /api/v1/snapshots | GET | human | snapshot.read | orbit | filtered, safe metadata |
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin | | /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | nothing; pins are checked |
| /api/v1/snapshots/:id/download | GET | human | snapshot.download | snapshot→orbit | arsip mentah: gzip atau format yang sudah terkompresi (`.sql.gz`, `.tar.gz`, `.sqlite.gz`, `.dump`), tanpa Content-Encoding, no-store, nosniff; HEAD 405; slot ekspor dan disk dibatasi | | /api/v1/snapshots/:id/download | GET | human | snapshot.download | snapshot→orbit | raw archive: gzip or an already compressed format (`.sql.gz`, `.tar.gz`, `.sqlite.gz`, `.dump`), no Content-Encoding, no-store, nosniff; HEAD answers 405; export slots and disk are limited |
| /api/v1/orbits | GET | human | orbit.read | orbit | metadata tanpa provider_config | | /api/v1/orbits | GET | human | orbit.read | orbit | metadata without provider_config |
| /api/v1/orbits | POST | human | orbit.manage | admin | metadata aman | | /api/v1/orbits | POST | human | orbit.manage | admin | safe metadata |
| /api/v1/orbits/:id/retention | PUT | human | retention.manage | orbit | tidak ada | | /api/v1/orbits/:id/retention | PUT | human | retention.manage | orbit | nothing |
| /api/v1/orbits/:id/run | POST | human | capture.run | orbit | job/status aman | | /api/v1/orbits/:id/run | POST | human | capture.run | orbit | safe job and status |
| /api/v1/orbits/:id/outpost | PUT | human | outpost.manage | orbit | assignment eksplisit legacy; managed lewat capture profile | | /api/v1/orbits/:id/outpost | PUT | human | outpost.manage | orbit | explicit legacy assignment; managed orbits go through a capture profile |
| /api/v1/reconstitute | POST | human | recovery.manage | snapshot→orbit | sesi restore administratif, bukan self-service | | /api/v1/reconstitute | POST | human | recovery.manage | snapshot→orbit | administrative restore session, not self-service |
| /api/v1/reconstitute/:id | GET,DELETE | human | recovery.manage | restore session→snapshot→orbit | status aman; cancel sebelum apply | | /api/v1/reconstitute/:id | GET,DELETE | human | recovery.manage | restore session→snapshot→orbit | safe status; cancel before apply |
| /api/v1/wormhole/outposts | GET | human | outpost.manage | admin | nama/status; tanpa token | | /api/v1/wormhole/outposts | GET | human | outpost.manage | admin | names and status; no tokens |
| /api/v1/wormhole/pairing | POST | human | outpost.manage | admin | code berumur pendek | | /api/v1/wormhole/pairing | POST | human | outpost.manage | admin | short-lived code |
| /api/v1/wormhole/claim | POST | public | pairing.consume | one-time code | token baru sekali ke claimant; limiter per sumber + global, kode tersimpan sebagai digest | | /api/v1/wormhole/claim | POST | public | pairing.consume | one-time code | new token returned once to the claimant; limited per source and globally; the code is stored only as a digest |
| /api/v1/wormhole/outposts/:id/rotate | POST | human | outpost.manage | paired Outpost | token baru sekali (no-store); token lama hidup selama grace; audit | | /api/v1/wormhole/outposts/:id/rotate | POST | human | outpost.manage | paired Outpost | new token returned once (no-store); the old token stays valid for a grace period; audited |
| /api/v1/wormhole/outposts/:id/revoke | POST | human | outpost.manage | Outpost | tidak ada; semua kredensial ditolak pada request berikutnya; audit | | /api/v1/wormhole/outposts/:id/revoke | POST | human | outpost.manage | Outpost | nothing; every credential is rejected from the next request; audited |
| /api/v1/wormhole/upload/init | POST | outpost | upload.assigned | orbit owner | session ID milik owner | | /api/v1/wormhole/upload/init | POST | outpost | upload.assigned | orbit owner | upload session id owned by the caller |
| /api/v1/wormhole/upload/chunk | POST | outpost | upload.assigned | session owner + orbit owner | tidak ada | | /api/v1/wormhole/upload/chunk | POST | outpost | upload.assigned | session owner + orbit owner | nothing |
| /api/v1/wormhole/restic/commit | POST | outpost | upload.assigned | orbit owner + repository owner | snapshot ID owner | | /api/v1/wormhole/restic/commit | POST | outpost | upload.assigned | orbit owner + repository owner | snapshot id of the owner |
| /api/v1/capture-profiles | GET | human | orbit.read | profile→orbit | profile terfilter; tanpa DSN | | /api/v1/capture-profiles | GET | human | orbit.read | profile→orbit | filtered profiles; no DSN |
| /api/v1/capture-profiles | POST | human | orbit.manage | orbit | profile aman | | /api/v1/capture-profiles | POST | human | orbit.manage | orbit | safe profile |
| /api/v1/capture-profiles/:id | PUT | human | orbit.manage | admin | hanya schedule dan retention (absen = tetap, null = hapus); validasi sama dengan POST; kursor jadwal maju ke saat perubahan; diaudit | | /api/v1/capture-profiles/:id | PUT | human | orbit.manage | admin | schedule and retention only (absent = unchanged, null = remove); same validation as POST; the schedule cursor moves to the time of the change; audited |
| /api/v1/capture-profiles/:id/jobs | POST | human | capture.run | profile→orbit | job aman | | /api/v1/capture-profiles/:id/jobs | POST | human | capture.run | profile→orbit | safe job |
| /api/v1/capture-jobs | GET | human | orbit.read | job→orbit | histori terfilter | | /api/v1/capture-jobs | GET | human | orbit.read | job→orbit | filtered history |
| /api/v1/capture-jobs/:id | GET | human | orbit.read | job→orbit | status aman | | /api/v1/capture-jobs/:id | GET | human | orbit.read | job→orbit | safe status |
| /api/v1/capture-jobs/:id/events | GET | human | orbit.read | job→orbit | phase/timestamp tanpa log DB | | /api/v1/capture-jobs/:id/events | GET | human | orbit.read | job→orbit | phases and timestamps, no database logs |
| /api/v1/wormhole/capture/:application/claim | POST | outpost | capture.assigned | profile owner | lease milik owner | | /api/v1/wormhole/capture/:application/claim | POST | outpost | capture.assigned | profile owner | lease owned by the caller |
| /api/v1/wormhole/capture/:id/report | POST | outpost | capture.assigned | job owner + lease | tidak ada | | /api/v1/wormhole/capture/:id/report | POST | outpost | capture.assigned | job owner + lease | nothing |
| /api/v1/wormhole/capture/:id/payload | POST | outpost | capture.assigned | job owner + lease | tidak ada | | /api/v1/wormhole/capture/:id/payload | POST | outpost | capture.assigned | job owner + lease | nothing |
| /api/v1/wormhole/capture/:id/restic | POST | outpost | capture.assigned | job owner + lease + repository | commit owner | | /api/v1/wormhole/capture/:id/restic | POST | outpost | capture.assigned | job owner + lease + repository | commit of the owner |
| /api/v1/restore-targets | POST | human | orbit.manage | target→orbit | identity terverifikasi admin; tanpa kredensial | | /api/v1/restore-targets | POST | human | orbit.manage | target→orbit | identity verified by an admin; no credentials |
| /api/v1/capture-profiles/:id/restore-targets | GET | human | recovery.manage | admin | identity target (instance/database) hanya untuk admin sampai self-service M6; tanpa kredensial | | /api/v1/capture-profiles/:id/restore-targets | GET | human | recovery.manage | admin | target identity (instance, database) for admins only; no credentials |
| /api/v1/snapshots/:id/restore-targets | GET | human | recovery.manage | admin | identity target hanya untuk admin sampai self-service M6; tanpa kredensial | | /api/v1/snapshots/:id/restore-targets | GET | human | recovery.manage | admin | target identity for admins only; no credentials |
| /api/v1/restore-jobs | GET,POST | human | recovery.manage | admin | restore administratif dan daftar terbaru; refresh.run lewat relasi terpisah (M6) | | /api/v1/restore-jobs | GET,POST | human | recovery.manage | admin | administrative restore and the recent list; self-service refresh goes through relations (`refresh.run`) instead |
| /api/v1/snapshots/:id/restore-jobs | GET | human | recovery.manage | admin | histori restore memuat target dan aktor; admin saja sampai M6 | | /api/v1/snapshots/:id/restore-jobs | GET | human | recovery.manage | admin | restore history with target and actor; admin only |
| /api/v1/restore-jobs/:id | GET,DELETE | human | recovery.manage | job→snapshot + target | status aman; cancel sebelum apply | | /api/v1/restore-jobs/:id | GET,DELETE | human | recovery.manage | job→snapshot + target | safe status; cancel before apply |
| /api/v1/restore-jobs/:id/reconcile | POST | human | recovery.manage | job→target | status recovery admin | | /api/v1/restore-jobs/:id/reconcile | POST | human | recovery.manage | job→target | administrative recovery status |
| /api/v1/wormhole/restore-targets/:id/claim | POST | outpost | restore.assigned | target owner | lease + artifact metadata | | /api/v1/wormhole/restore-targets/:id/claim | POST | outpost | restore.assigned | target owner | lease + artifact metadata |
| /api/v1/wormhole/restore/:id/payload | GET | outpost | restore.assigned | job owner + lease/fence | raw payload hanya agent | | /api/v1/wormhole/restore/:id/payload | GET | outpost | restore.assigned | job owner + lease/fence | raw payload, agent only |
| /api/v1/wormhole/restore/:id/report | POST | outpost | restore.assigned | job owner + lease/fence | tidak ada | | /api/v1/wormhole/restore/:id/report | POST | outpost | restore.assigned | job owner + lease/fence | nothing |
| /api/v1/wormhole/restore/:id/safety | POST | outpost | restore.assigned | job owner + lease/fence | safety snapshot owner | | /api/v1/wormhole/restore/:id/safety | POST | outpost | restore.assigned | job owner + lease/fence | safety snapshot of the owner |
| /api/v1/wormhole/restore/:id/apply | POST | outpost | restore.assigned | job owner + lease/fence | izin apply setelah revalidasi | | /api/v1/wormhole/restore/:id/apply | POST | outpost | restore.assigned | job owner + lease/fence | permission to apply, after revalidation |
SPA/assets publik berisi UI statis, bukan data vault. GET juga menerima HEAD sesuai The SPA and its assets are public and contain only the static UI, not vault data.
Axum, dengan gate sama. Aksi refresh internal tidak memberikan capture.run bebas GET routes also answer HEAD, as Axum does, behind the same gate. Internal refresh
atau snapshot.download. Recovery legacy tetap jalur admin dan tidak menjadi jalan actions never grant free-standing `capture.run` or `snapshot.download`. Legacy
pintas refresh self-service. recovery stays an administrator path and is not a shortcut around self-service
refresh.

View File

@@ -1,22 +1,93 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Build a clean, single-commit tree of the current HEAD for a fresh public repository. Nothing is pushed. # Build a clean, single-commit tree of the current HEAD for a fresh public repository. Nothing is pushed.
# Usage: [TESSERA_PRIVATE_TERMS=/path/to/terms.txt] scripts/export-public.sh /path/to/empty-dir #
# Usage: TESSERA_PRIVATE_TERMS=/path/to/terms.txt scripts/export-public.sh /path/to/empty-dir
# scripts/export-public.sh --allow-unchecked /path/to/empty-dir
# #
# TESSERA_PRIVATE_TERMS names a file, kept outside the repository, with one term per line (host names, # TESSERA_PRIVATE_TERMS names a file, kept outside the repository, with one term per line (host names,
# customer names, internal systems). If any of them occurs in the exported tree the export is refused. # customer names, internal systems, personal names). The export is refused when any term occurs in the exported
# tree. The variable must be set and the file must exist and contain at least one term; otherwise the script fails.
# Pass --allow-unchecked only if you knowingly want to skip that check.
#
# Independently of the terms file, a given terms file also enables two pattern checks on the export: personal
# e-mail addresses (anything that is not a documentation/placeholder address) and organisation-specific hosts.
set -euo pipefail set -euo pipefail
out="${1:?target directory}"
allow_unchecked=0
out=""
for arg in "$@"; do
case "$arg" in
--allow-unchecked) allow_unchecked=1 ;;
-*) echo "unknown option: $arg" >&2; exit 2 ;;
*) [ -z "$out" ] || { echo "only one target directory" >&2; exit 2; }; out="$arg" ;;
esac
done
[ -n "$out" ] || { echo "usage: $0 [--allow-unchecked] <empty-target-dir>" >&2; exit 2; }
terms="${TESSERA_PRIVATE_TERMS:-}"
if [ "$allow_unchecked" -eq 0 ]; then
if [ -z "$terms" ]; then
echo "refusing to export: TESSERA_PRIVATE_TERMS is not set (or pass --allow-unchecked to skip the private-terms check)" >&2
exit 1
fi
if [ ! -f "$terms" ]; then
echo "refusing to export: TESSERA_PRIVATE_TERMS=$terms is not a file" >&2
exit 1
fi
if ! grep -q '[^[:space:]]' "$terms"; then
echo "refusing to export: $terms contains no terms" >&2
exit 1
fi
fi
mkdir -p "$out"
[ -z "$(ls -A "$out" 2>/dev/null)" ] || { echo "target must be empty" >&2; exit 1; } [ -z "$(ls -A "$out" 2>/dev/null)" ] || { echo "target must be empty" >&2; exit 1; }
root="$(git rev-parse --show-toplevel)" root="$(git rev-parse --show-toplevel)"
git -C "$root" diff --quiet HEAD || { echo "commit or stash first" >&2; exit 1; } git -C "$root" diff --quiet HEAD || { echo "commit or stash first" >&2; exit 1; }
git -C "$root" archive HEAD | tar -x -C "$out" git -C "$root" archive HEAD | tar -x -C "$out"
if [ -n "${TESSERA_PRIVATE_TERMS:-}" ]; then
if grep -rIl -i -F -f "$TESSERA_PRIVATE_TERMS" "$out" --exclude-dir=node_modules >/dev/null; then # Local tooling and agent state never belongs in a public tree, even if an old commit tracked it.
for path in .serena .claude .cursor .idea .vscode graft floorplan .ignore web/AGENTS.md AGENTS.md CLAUDE.md \
web/blackhole-proto.html tasks; do
rm -rf "${out:?}/$path"
done
if [ -n "$terms" ] && [ -f "$terms" ] && grep -q '[^[:space:]]' "$terms"; then
fail=0
# 1. literal private terms (case-insensitive)
if hits="$(grep -rIl -i -F -f "$terms" "$out" --exclude-dir=node_modules)"; [ -n "$hits" ]; then
echo "private terms found in:" >&2 echo "private terms found in:" >&2
grep -rIl -i -F -f "$TESSERA_PRIVATE_TERMS" "$out" --exclude-dir=node_modules >&2 echo "$hits" >&2
exit 1 fail=1
fi fi
# 2. personal e-mail addresses: any address that is not a documentation or no-reply placeholder
email='[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}'
placeholder='@(example\.(com|org|net|invalid)|[A-Za-z0-9.-]*\.(example|invalid|test|localhost)|users\.noreply\.github\.com|noreply\.[A-Za-z0-9.-]+)$|:(noreply|no-reply)@'
if hits="$(grep -rIoE "$email" "$out" --exclude-dir=node_modules --exclude=Cargo.lock --exclude=package-lock.json \
| grep -vE "$placeholder" || true)"; [ -n "$hits" ]; then
echo "possible personal e-mail addresses (review, then remove or allow-list):" >&2
echo "$hits" | sort -u >&2
fail=1
fi
# 3. organisation-specific hosts (any host label containing the org name after an @ or in a URL)
org="sen""kensha" # split so that this script does not match itself
if hits="$(grep -rIiEl "@[A-Za-z0-9.-]*$org|https?://[A-Za-z0-9.-]*$org" "$out" --exclude-dir=node_modules || true)"; [ -n "$hits" ]; then
echo "organisation-specific hosts found in:" >&2
echo "$hits" >&2
fail=1
fi
[ "$fail" -eq 0 ] || exit 1
else else
echo "note: TESSERA_PRIVATE_TERMS is not set, so no check for private terms was made" >&2 echo "warning: --allow-unchecked given, so no check for private terms or personal e-mail addresses was made" >&2
fi fi
echo "clean tree at $out; review it, then: git init && git add -A && git commit"
cat <<EOF
clean tree at $out; review it, then create the public history with a neutral author, for example:
cd "$out"
git init
git add -A
git -c user.name="<PUBLIC NAME>" -c user.email="<PUBLIC EMAIL OR noreply ADDRESS>" commit -m "Initial release"
Do not run a bare 'git commit' there: it would use your global git identity.
EOF

View File

@@ -89,8 +89,8 @@ def main():
assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result
continue continue
assert result["status"] == "completed", (name, result) assert result["status"] == "completed", (name, result)
target = root / f"{name}.sql" target = root / "hub" / "exports" / f"{name}.sql"
session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": str(target)}) session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": target.name})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
sql = target.read_text() sql = target.read_text()
assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰")) assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰"))

View File

@@ -125,8 +125,8 @@ def main():
assert failed["snapshot_id"] is None assert failed["snapshot_id"] is None
snapshots = api("snapshots") snapshots = api("snapshots")
assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]} assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]}
dump = root / "backup.dump" dump = root / "hub" / "exports" / "backup.dump"
session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": str(dump)}) session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": dump.name})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump) command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump)
restored = command("psql", *pg, "-d", "target_db", "-Atc", restored = command("psql", *pg, "-d", "target_db", "-Atc",
@@ -174,7 +174,7 @@ def main():
}) })
assert "provider_config" not in legacy assert "provider_config" not in legacy
command(BIN / "tessera", "--hub-url", hub_url, "snap", "--orbit", "legacy-fixture", command(BIN / "tessera", "--hub-url", hub_url, "snap", "--orbit", "legacy-fixture",
env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin"}, stdout=DEVNULL) env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin-token-0123456789abcdef"}, stdout=DEVNULL)
assert any(snap["orbit_id"] == legacy["id"] for snap in api("snapshots")) assert any(snap["orbit_id"] == legacy["id"] for snap in api("snapshots"))
for log in (hub_log, agent_log): for log in (hub_log, agent_log):
log.seek(0) log.seek(0)

View File

@@ -49,7 +49,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False
hub_port = port() hub_port = port()
env = {**fixture_env(), "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key", env = {**fixture_env(), "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key",
"TESSERA_LISTEN": f"127.0.0.1:{hub_port}", "TESSERA_DATA_DIR": str(root / "hub"), "TESSERA_LISTEN": f"127.0.0.1:{hub_port}", "TESSERA_DATA_DIR": str(root / "hub"),
"TESSERA_ADMIN_TOKEN": "fixture-admin", **(settings or {})} "TESSERA_ADMIN_TOKEN": "fixture-admin-token-0123456789abcdef", **(settings or {})}
hub_url = f"http://127.0.0.1:{hub_port}" hub_url = f"http://127.0.0.1:{hub_port}"
log = cleanup.enter_context((root / "hub.log").open("w+")) log = cleanup.enter_context((root / "hub.log").open("w+"))
hub = Popen([BIN / "tessera-hub"], env=env, stdout=log, stderr=log) hub = Popen([BIN / "tessera-hub"], env=env, stdout=log, stderr=log)
@@ -57,7 +57,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False
def api(path, body=None, token=None, expected=200, extra=None, raw=False, method=None): def api(path, body=None, token=None, expected=200, extra=None, raw=False, method=None):
payload = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None payload = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None
headers = {"Authorization": "Bearer fixture-admin", "Content-Type": "application/json"} headers = {"Authorization": "Bearer fixture-admin-token-0123456789abcdef", "Content-Type": "application/json"}
if token: if token:
headers["X-Tessera-Upload-Token"] = token headers["X-Tessera-Upload-Token"] = token
headers.update(extra or {}) headers.update(extra or {})

View File

@@ -1,3 +0,0 @@
# Web animation
Follow the [animation guideline](../docs/UI.md#animation-guideline) for component transitions and scene motion. Use the shared Framer Motion physics spring and retarget the same element or MotionValue so interruption preserves velocity.

View File

@@ -1,39 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Black hole prototype</title>
<style>
html, body { margin: 0; height: 100%; background: #0a0c10; color: #d9dad6; font: 12px/1.4 ui-monospace, monospace; overflow: hidden; }
canvas { position: fixed; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; }
canvas:active { cursor: grabbing; }
#panel { position: fixed; top: 12px; left: 12px; width: 250px; max-height: calc(100% - 24px); overflow: auto; padding: 10px 12px; background: #111418e6; border: 1px solid #2b3138; border-radius: 8px; backdrop-filter: blur(10px); }
#panel.hidden { display: none; }
#panel h1 { margin: 0 0 6px; font-size: 12px; letter-spacing: .1em; text-transform: uppercase; color: #e8b57e; }
#panel label { display: grid; grid-template-columns: 78px 1fr 38px; gap: 6px; align-items: center; margin: 4px 0; }
#panel input[type=range] { width: 100%; }
#panel .row { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; }
#panel button { font: inherit; color: inherit; background: #191d22; border: 1px solid #393e45; border-radius: 5px; padding: 4px 8px; cursor: pointer; }
#panel pre { margin: 8px 0 0; white-space: pre-wrap; color: #9298a0; }
.tag { position: fixed; pointer-events: none; font: 500 10px/1 ui-monospace, monospace; letter-spacing: .1em; text-transform: uppercase; color: #e8b57e; opacity: 0; white-space: nowrap; }
.tag::before { content: ""; display: inline-block; width: 22px; height: 1px; background: #e8b57e99; vertical-align: middle; margin-right: 6px; }
.tag.left { transform: translateX(-100%); }
.tag.left::before { display: none; }
.tag.left::after { content: ""; display: inline-block; width: 22px; height: 1px; background: #e8b57e99; vertical-align: middle; margin-left: 6px; }
.tag.mint { color: #8bcbb3; }
.tag.mint::before { display: none; }
#modes { display: flex; gap: 6px; margin: 4px 0 8px; }
#modes button.on { border-color: #e8b57e; color: #ffe2c9; }
#fail { position: fixed; inset: 0; display: none; place-items: center; text-align: center; }
</style>
</head>
<body>
<canvas id="stage"></canvas>
<div id="fail">WebGL2 is not available in this browser.</div>
<div class="tag" id="tagShadow">Shadow · 3√3 M</div>
<div class="tag" id="tagDisk">Accretion disk · 6–26 M</div>
<div id="panel"><h1>Black hole</h1><div id="modes"></div></div>
<script type="module" src="/src/proto/blackhole-proto.ts"></script>
</body>
</html>

View File

@@ -2,7 +2,7 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tessera Vault</title> <title>Tessera Vault</title>
</head> </head>
<body class="bg-space-950 text-star-100 overflow-hidden"> <body class="bg-space-950 text-star-100 overflow-hidden">

View File

@@ -78,3 +78,112 @@ test("labels days relative to now", () => {
assert.equal(dayLabel(NOW - 86_400_000, NOW), "Yesterday"); assert.equal(dayLabel(NOW - 86_400_000, NOW), "Yesterday");
assert.notEqual(dayLabel(NOW - 5 * 86_400_000, NOW), "Today"); assert.notEqual(dayLabel(NOW - 5 * 86_400_000, NOW), "Today");
}); });
test("lists an undo under the restore it reverses, and a redo under that undo", () => {
const snapshots = [snapshot("s1", "ledger", "2026-11-14T02:00:00Z")];
const run = (id, job, extra = {}) => ({ id, restore_job_id: job, relation_id: "r", status: "completed", ...extra });
const refreshRuns = [
run("r1", "j1", { undo_available: false }),
run("r2", "j2", { undo: true, undo_of: "r1", undo_available: false }),
run("r3", "j3", { undo: true, undo_of: "r2", undo_available: true }),
];
const restoreJobs = [
restore("j1", "completed", "completed", "2026-11-14T03:00:00Z"),
restore("j2", "completed", "completed", "2026-11-14T04:00:00Z", { snapshot_id: "safety-1" }),
restore("j3", "completed", "completed", "2026-11-14T05:00:00Z", { snapshot_id: "safety-2" }),
];
const entries = build({ snapshots, restoreJobs, refreshRuns });
const roots = entries.filter(({ kind }) => kind === "restore");
assert.deepEqual(roots.map(({ id }) => id), ["restore-j1"], "only the restore is on its own");
const [undo] = roots[0].children;
assert.equal(undo.id, "restore-j2");
assert.equal(undo.variant, "undo");
assert.equal(undo.children[0].variant, "redo");
// the newest one can be put back, and what opening it offers is the opposite of what it did
assert.equal(undo.opens, null);
assert.equal(undo.children[0].opens.kind, "undo");
assert.equal(activityCounts(entries).running, 0);
});
test("a restore sits where its most urgent undo does, and an undo whose restore is missing stands alone", () => {
const refreshRuns = [
{ id: "r1", restore_job_id: "j1", relation_id: "r" },
{ id: "r2", restore_job_id: "j2", relation_id: "r", undo: true, undo_of: "r1" },
{ id: "r9", restore_job_id: "j9", relation_id: "r", undo: true, undo_of: "gone" },
];
const restoreJobs = [
restore("j1", "completed", "completed", "2026-11-10T03:00:00Z"),
restore("j2", "running", "safety", "2026-11-14T10:00:00Z"),
restore("j9", "completed", "completed", "2026-11-12T03:00:00Z"),
];
const entries = build({ restoreJobs, refreshRuns });
assert.deepEqual(entries.map(({ id, slotGroup }) => [id, slotGroup]), [["restore-j1", "running"], ["restore-j9", "history"]]);
assert.equal(activityCounts(entries).running, 1);
});
test("someone who may only read runs still gets the restore history, with undos under their restores", () => {
const run = (id, extra = {}) => ({ id, relation_id: "r", source_name: "ledger", target_name: "staging", status: "completed", restore_phase: "completed", snapshot_taken_at: sec("2026-11-14T02:00:00Z"), created_at: sec("2026-11-14T03:00:00Z"), ...extra });
const refreshRuns = [
run("r1"),
run("r2", { undo: true, undo_of: "r1", created_at: sec("2026-11-14T04:00:00Z"), undo_available: false }),
run("r3", { undo: true, undo_of: "r2", created_at: sec("2026-11-14T05:00:00Z"), undo_available: true }),
run("r4", { status: "restoring", restore_phase: "safety", created_at: sec("2026-11-14T11:00:00Z") }),
run("r5", { status: "recovery_required", restore_phase: "apply_failed", created_at: sec("2026-11-13T01:00:00Z") }),
run("r6", { status: "cancelled", restore_phase: null, created_at: sec("2026-11-12T01:00:00Z") }),
];
const entries = build({ refreshRuns });
assert.deepEqual(entries.map(({ id }) => id), ["restore-run-r5", "restore-run-r4", "restore-run-r1", "restore-run-r6"]);
const [locked, live, restored] = entries;
assert.equal(locked.group, "needs");
assert.equal(live.progress, 2);
assert.match(restored.title, /^ledger · .+ → staging$/);
assert.equal(restored.opens, null, "no snapshot id reaches them, and it cannot be undone any more");
const [undo] = restored.children;
assert.equal(undo.variant, "undo");
assert.equal(undo.children[0].variant, "redo");
assert.equal(undo.children[0].opens.kind, "undo");
assert.deepEqual(activityCounts(entries), { running: 1, needs: 1 });
});
test("a restore known by its run and its job is one entry, with the job's detail", () => {
const refreshRuns = [{ id: "r1", restore_job_id: "j1", relation_id: "r", source_name: "x", target_name: "y", status: "completed", created_at: sec("2026-11-14T03:00:00Z") }];
const entries = build({
snapshots: [snapshot("s1", "media-vault", "2026-11-14T02:00:00Z")],
restoreJobs: [restore("j1", "completed", "completed", "2026-11-14T03:00:00Z")],
refreshRuns,
}).filter(({ kind }) => kind === "restore");
assert.equal(entries.length, 1);
assert.match(entries[0].title, /pg-staging \/ orders$/);
});
test("a restore whose safety backup expired says so instead of leading anywhere", () => {
const run = (id, extra = {}) => ({ id, relation_id: "r", source_name: "ledger", target_name: "staging", status: "completed", restore_phase: "completed", created_at: sec("2026-11-14T03:00:00Z"), ...extra });
const gone = build({ refreshRuns: [run("r1", { undo_state: "expired", undo_available: false })] })[0];
assert.equal(gone.opens, null);
assert.equal(gone.note, "Safety backup expired");
// an administrator's restore job would normally open its snapshot; expired, it must not suggest the copy is there
const withJob = build({
snapshots: [snapshot("s1", "ledger", "2026-11-14T02:00:00Z")],
restoreJobs: [restore("j1", "completed", "completed", "2026-11-14T03:00:00Z")],
refreshRuns: [run("r1", { restore_job_id: "j1", undo_state: "expired" })],
}).find(({ id }) => id === "restore-j1");
assert.equal(withJob.opens, null);
assert.equal(withJob.note, "Safety backup expired");
// superseded is not expired: its copy may still be there, and it keeps its normal link
const old = build({
snapshots: [snapshot("s1", "ledger", "2026-11-14T02:00:00Z")],
restoreJobs: [restore("j1", "completed", "completed", "2026-11-14T03:00:00Z")],
refreshRuns: [run("r1", { restore_job_id: "j1", undo_state: "superseded" })],
}).find(({ id }) => id === "restore-j1");
assert.deepEqual(old.opens, { kind: "snapshot", id: "s1" });
});
test("an interrupted restore that can be rolled back says so, and a rolled back one is marked", () => {
const run = (id, extra) => ({ id, relation_id: "r", source_name: "ledger", target_name: "staging", created_at: sec("2026-11-14T03:00:00Z"), ...extra });
const [locked] = build({ refreshRuns: [run("r1", { status: "recovery_required", restore_phase: "apply_failed", undo_available: true })] });
assert.equal(locked.group, "needs");
assert.match(locked.meta, /roll back available/);
assert.equal(locked.opens.kind, "undo");
const [done] = build({ refreshRuns: [run("r2", { status: "reconciled", restore_phase: "rolled_back" })] });
assert.equal(done.state, "Rolled back");
});

View File

@@ -59,3 +59,10 @@ test("restore points are named by environment, and by target only when two share
); );
assert.equal(relationLabels([rel("a", null, "odd")])[0].label, "odd"); assert.equal(relationLabels([rel("a", null, "odd")])[0].label, "odd");
}); });
test("an interrupted restore offers a rollback only when its safety copy can be used", () => {
const names = { target: "Staging" };
const stuck = { status: "recovery_required", restore_phase: "apply_failed" };
assert.match(outcomeOf({ ...stuck, undo_available: true }, names).detail, /roll it back/i);
assert.match(outcomeOf(stuck, names).detail, /administrator has to recover/i);
});

View File

@@ -3,7 +3,7 @@ import { AnimatePresence, useMotionValue } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { import {
fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchRefreshRelations, fetchSnapshots, savePreferences, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchRefreshRelations, fetchSnapshots, savePreferences,
enqueueCapture, runOrbit, type Orbit, enqueueCapture, runOrbit, type Orbit, type RefreshRun,
} from "./api"; } from "./api";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD"; import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel"; import { HUDPanel } from "./components/hud/HUDPanel";
@@ -91,7 +91,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null); const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null);
const [play, setPlay] = useState(true); const [play, setPlay] = useState(true);
const [restoreBusy, setRestoreBusy] = useState(false); const [restoreBusy, setRestoreBusy] = useState(false);
const [restoreTarget, setRestoreTarget] = useState<{ id: string | null }>(); const [restoreTarget, setRestoreTarget] = useState<{ id: string | null; undo?: RefreshRun }>();
const reducedMotion = useReducedMotion(); const reducedMotion = useReducedMotion();
const tools = useRef<HTMLDivElement>(null); const tools = useRef<HTMLDivElement>(null);
useScreenTransition(tools, bigScreen, reducedMotion); useScreenTransition(tools, bigScreen, reducedMotion);
@@ -237,7 +237,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
? { orbitId: captureOrbitId, key: capture.submittedAt, snapshotId: capture.data ?? undefined } ? { orbitId: captureOrbitId, key: capture.submittedAt, snapshotId: capture.data ?? undefined }
: undefined, [captureOrbitId, capture.submittedAt, capture.isError, capture.data]); : undefined, [captureOrbitId, capture.submittedAt, capture.isError, capture.data]);
const captureReady = !!captureEffect?.snapshotId && !!snaps.data?.some(({ id }) => id === captureEffect.snapshotId); const captureReady = !!captureEffect?.snapshotId && !!snaps.data?.some(({ id }) => id === captureEffect.snapshotId);
const activity = useActivity(snaps.data, orbits.data, caps.admin); const activity = useActivity(snaps.data, orbits.data, { admin: caps.admin, refresh: caps.refresh });
// Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access. // Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access.
const railItems = useMemo( const railItems = useMemo(
() => (caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")), () => (caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")),
@@ -293,6 +293,12 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
setMode(next); setMode(next);
} }
/** Open the dialog that puts back a restore (or undo) shown in the Activity log. */
function openUndo(run: RefreshRun) {
if (!restoreBusy) setRestoreTarget({ id: null, undo: run });
setMode("reconstitute");
}
function selectSearchResult(result: SearchResult) { function selectSearchResult(result: SearchResult) {
if (result.kind === "navigation") openConsole(result.id); if (result.kind === "navigation") openConsole(result.id);
else if (result.kind === "snapshot") openSnapshot(result.id); else if (result.kind === "snapshot") openSnapshot(result.id);
@@ -424,7 +430,8 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
entries={activity.entries} counts={activity.counts} updatedAt={activity.updatedAt} entries={activity.entries} counts={activity.counts} updatedAt={activity.updatedAt}
restoresUnavailable={activity.restoresUnavailable} capturesUnavailable={activity.capturesUnavailable} restoresUnavailable={activity.restoresUnavailable} capturesUnavailable={activity.capturesUnavailable}
onOpen={(target) => { onOpen={(target) => {
if (target.kind === "snapshot") openSnapshot(target.id); if ("run" in target) openUndo(target.run);
else if (target.kind === "snapshot") openSnapshot(target.id);
else { else {
selectOrbit(target.id); selectOrbit(target.id);
setMode("scene"); setMode("scene");
@@ -454,7 +461,18 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
)} )}
</AnimatePresence> </AnimatePresence>
<SpringPane active={mode === "reconstitute"}> <SpringPane active={mode === "reconstitute"}>
{restoreSnapshot {restoreTarget?.undo
? (
<RestoreWizard
key={restoreTarget.undo.id}
undo={restoreTarget.undo}
relations={restorePoints.filter((r) => r.id === restoreTarget.undo!.relation_id)}
admin={caps.admin}
onBusyChange={setRestoreBusy}
onDone={() => setMode("activity")}
/>
)
: restoreSnapshot
? ( ? (
<RestoreWizard <RestoreWizard
key={restoreSnapshot.id} key={restoreSnapshot.id}

View File

@@ -139,6 +139,14 @@ export type RefreshRun = {
undo?: boolean; undo?: boolean;
/** A completed restore that can still be undone (the newest of its target, safety copy still there). */ /** A completed restore that can still be undone (the newest of its target, safety copy still there). */
undo_available?: boolean; undo_available?: boolean;
/** Why a restore with a safety copy can or cannot be put back: `expired` means retention has forgotten the copy. */
undo_state?: "available" | "superseded" | "expired";
/** While it can be undone: when its safety copy is first at risk of being forgotten (seconds since the epoch). */
undo_kept_until?: number;
/** For an undo: the run whose restore it puts back. */
undo_of?: string;
/** The restore job this run queued. */
restore_job_id?: string;
id: string; relation_id: string; source_name: string; target_name: string; status: string; blocked_reason: string | null; id: string; relation_id: string; source_name: string; target_name: string; status: string; blocked_reason: string | null;
capture_status: string | null; capture_phase: string | null; snapshot_taken_at: number | null; capture_status: string | null; capture_phase: string | null; snapshot_taken_at: number | null;
restore_status: string | null; restore_phase: string | null; restore_status: string | null; restore_phase: string | null;

View File

@@ -6,14 +6,14 @@ import { Segmented } from "../ui/Segmented";
type Kind = "all" | "backup" | "restore"; type Kind = "all" | "backup" | "restore";
const PAGE = 80; const PAGE = 80;
function Row({ entry, now, onOpen }: { entry: ActivityEntry; now: number; onOpen: (target: ActivityTarget) => void }) { function Row({ entry, now, onOpen, depth = 0 }: { entry: ActivityEntry; now: number; onOpen: (target: ActivityTarget) => void; depth?: number }) {
const opens = entry.opens; const opens = entry.opens;
const content = ( const content = (
<> <>
<span className="act-time">{entry.group === "running" && entry.id.startsWith("orbit-") ? "now" : entry.at === null ? "—" : clock(entry.at)}</span> <span className="act-time">{entry.group === "running" && entry.id.startsWith("orbit-") ? "now" : entry.at === null ? "—" : clock(entry.at)}</span>
<span className="act-kind" data-kind={entry.kind}> <span className="act-kind" data-kind={entry.kind}>
<i className="act-glyph" data-tone={entry.tone} aria-hidden="true" /> <i className="act-glyph" data-tone={entry.tone} aria-hidden="true" />
{entry.kind === "backup" ? "Backup" : "Restore"} {entry.kind === "backup" ? "Backup" : entry.variant === "redo" ? "Redo" : entry.variant === "undo" ? "Undo" : "Restore"}
</span> </span>
<span className="act-text"> <span className="act-text">
<span className="act-title">{entry.title}</span> <span className="act-title">{entry.title}</span>
@@ -29,14 +29,24 @@ function Row({ entry, now, onOpen }: { entry: ActivityEntry; now: number; onOpen
</span> </span>
)} )}
</span> </span>
<span className="act-open">{opens ? `${opens.kind} ›` : "removed"}</span> <span className="act-open" data-note={!opens && entry.note ? "true" : undefined}>{opens ? `${opens.kind} ›` : entry.note ?? (depth ? "" : "removed")}</span>
</> </>
); );
void now; void now;
return opens ? ( return opens ? (
<button type="button" className="act-row" data-group={entry.group} data-tone={entry.tone} onClick={() => onOpen(opens)}>{content}</button> <button type="button" className="act-row" data-group={entry.group} data-tone={entry.tone} data-child={depth || undefined} style={depth ? { "--depth": depth } as React.CSSProperties : undefined} onClick={() => onOpen(opens)}>{content}</button>
) : ( ) : (
<div className="act-row" data-group={entry.group} data-tone={entry.tone} data-static="true">{content}</div> <div className="act-row" data-group={entry.group} data-tone={entry.tone} data-child={depth || undefined} style={depth ? { "--depth": depth } as React.CSSProperties : undefined} data-static="true">{content}</div>
);
}
/** A restore with its undos beneath it, each indented one step under what it reverses. */
function Tree({ entry, now, onOpen, depth = 0 }: { entry: ActivityEntry; now: number; onOpen: (target: ActivityTarget) => void; depth?: number }) {
return (
<>
<Row entry={entry} now={now} onOpen={onOpen} depth={depth} />
{entry.children?.map((next) => <Tree key={next.id} entry={next} now={now} onOpen={onOpen} depth={depth + 1} />)}
</>
); );
} }
@@ -58,23 +68,26 @@ export function ActivityView({ entries, counts, restoresUnavailable, capturesUna
}, []); }, []);
const term = query.trim().toLowerCase(); const term = query.trim().toLowerCase();
const matching = entries.filter((entry) => // A restore stays in the log when it or any undo under it matches, so an undo is never shown without its restore.
(kind === "all" || entry.kind === kind) && (!term || `${entry.title} ${entry.meta}`.toLowerCase().includes(term))); const matches = (entry: ActivityEntry): boolean =>
const visible = matching.slice(0, Math.max(shown, matching.filter(({ group }) => group !== "history").length)); ((kind === "all" || entry.kind === kind) && (!term || `${entry.title} ${entry.meta}`.toLowerCase().includes(term)))
|| (entry.children ?? []).some(matches);
const matching = entries.filter(matches);
const visible = matching.slice(0, Math.max(shown, matching.filter(({ slotGroup }) => slotGroup !== "history").length));
const sections: { label: string; tone?: string; items: ActivityEntry[] }[] = []; const sections: { label: string; tone?: string; items: ActivityEntry[] }[] = [];
for (const entry of visible) { for (const entry of visible) {
const label = entry.group === "needs" ? "Needs you" : entry.group === "running" ? "Running now" const label = entry.slotGroup === "needs" ? "Needs you" : entry.slotGroup === "running" ? "Running now"
: entry.at === null ? "Earlier" : dayLabel(entry.at, now); : entry.slotAt === null ? "Earlier" : dayLabel(entry.slotAt, now);
const last = sections.at(-1); const last = sections.at(-1);
if (last?.label === label) last.items.push(entry); if (last?.label === label) last.items.push(entry);
else sections.push({ label, tone: entry.group === "history" ? undefined : entry.group, items: [entry] }); else sections.push({ label, tone: entry.slotGroup === "history" ? undefined : entry.slotGroup, items: [entry] });
} }
const age = updatedAt ? Math.max(0, Math.round((now - updatedAt) / 1000)) : undefined; const age = updatedAt ? Math.max(0, Math.round((now - updatedAt) / 1000)) : undefined;
return ( return (
<div className="activity"> <div className="activity">
<div className="activity-bar"> <div className="activity-bar">
<p className="activity-lead">One log of everything that has run or is running. Open an entry to see its snapshot; restores and exports start there.</p> <p className="activity-lead">One log of everything that has run or is running. Open a backup to restore it; open a restore to undo it. Undos are listed under the restore they reverse.</p>
<dl className="activity-counts"> <dl className="activity-counts">
<div><dt><i className="act-glyph" data-tone="amber" aria-hidden="true" />Running</dt><dd>{counts.running}</dd></div> <div><dt><i className="act-glyph" data-tone="amber" aria-hidden="true" />Running</dt><dd>{counts.running}</dd></div>
<div data-alert={counts.needs > 0}><dt><i className="act-glyph" data-tone="red" aria-hidden="true" />Needs you</dt><dd>{counts.needs}</dd></div> <div data-alert={counts.needs > 0}><dt><i className="act-glyph" data-tone="red" aria-hidden="true" />Needs you</dt><dd>{counts.needs}</dd></div>
@@ -94,7 +107,7 @@ export function ActivityView({ entries, counts, restoresUnavailable, capturesUna
</div> </div>
{(restoresUnavailable || capturesUnavailable) && ( {(restoresUnavailable || capturesUnavailable) && (
<p role="alert" className="activity-warning"> <p role="alert" className="activity-warning">
{restoresUnavailable ? "Restore history is unavailable. This hub may be too old to list restore jobs." : "Outpost backup jobs are unavailable."} {restoresUnavailable ? "Restore history is unavailable. This hub may be too old to list restore runs." : "Outpost backup jobs are unavailable."}
{" "}The rest of the log is still shown. {" "}The rest of the log is still shown.
</p> </p>
)} )}
@@ -102,7 +115,7 @@ export function ActivityView({ entries, counts, restoresUnavailable, capturesUna
{sections.map((section) => ( {sections.map((section) => (
<section key={section.label} aria-label={section.label}> <section key={section.label} aria-label={section.label}>
<h3 data-tone={section.tone}>{section.label}</h3> <h3 data-tone={section.tone}>{section.label}</h3>
{section.items.map((entry) => <Row key={entry.id} entry={entry} now={now} onOpen={onOpen} />)} {section.items.map((entry) => <Tree key={entry.id} entry={entry} now={now} onOpen={onOpen} />)}
</section> </section>
))} ))}
{!sections.length && ( {!sections.length && (

View File

@@ -3,7 +3,7 @@ import { motion } from "motion/react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { cancelRefresh, fetchRefreshRun, fetchRefreshRuns, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api"; import { cancelRefresh, fetchRefreshRun, fetchRefreshRuns, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api";
import { formatBytes, formatWhen } from "../../lib/format"; import { formatBytes, formatWhen } from "../../lib/format";
import { isFinal, outcomeOf, progressOf, relationLabels, STAGES } from "../../lib/restoreRun"; import { isFinal, outcomeOf, progressOf, relationLabels, STAGES, undoDepth, undoVerb } from "../../lib/restoreRun";
import { Button } from "../ui/Button"; import { Button } from "../ui/Button";
import { Segmented } from "../ui/Segmented"; import { Segmented } from "../ui/Segmented";
import { DatabaseRestore } from "../reconstitute/DatabaseRestore"; import { DatabaseRestore } from "../reconstitute/DatabaseRestore";
@@ -28,23 +28,30 @@ type Phase = "idle" | "countdown" | "running";
* when there are several), presses Begin restore, has ten seconds to abort, and then follows four steps until the * when there are several), presses Begin restore, has ten seconds to abort, and then follows four steps until the
* target holds the backup. Administrators can still restore to any other registered target. * target holds the backup. Administrators can still restore to any other registered target.
*/ */
export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: { export function RestoreWizard({ snapshot, undo, relations, admin, onBusyChange, onDone }: {
snapshot: Snapshot; /** The snapshot to restore. Absent when the dialog was opened from a restore in the Activity log, to undo it. */
snapshot?: Snapshot;
/** The restore (or undo) this dialog was opened to put back. */
undo?: RefreshRun;
/** The relations from this snapshot's orbit that the person may restore through. */ /** The relations from this snapshot's orbit that the person may restore through. */
relations: RefreshRelation[]; relations: RefreshRelation[];
admin: boolean; admin: boolean;
onBusyChange: (busy: boolean) => void; onBusyChange: (busy: boolean) => void;
/** Leave the dialog once a run opened for an undo has finished. */
onDone?: () => void;
}) { }) {
const points = useMemo(() => relationLabels(relations.filter((r) => r.usable)), [relations]); const points = useMemo(() => relationLabels(relations.filter((r) => r.usable)), [relations]);
const [pointId, setPointId] = useState(points[0]?.id ?? ""); const [pointId, setPointId] = useState(undo?.relation_id ?? points[0]?.id ?? "");
const point = points.find((p) => p.id === pointId) ?? points[0]; const point = points.find((p) => p.id === pointId) ?? points[0];
const [phase, setPhase] = useState<Phase>("idle"); const [phase, setPhase] = useState<Phase>("idle");
const [left, setLeft] = useState(COUNTDOWN); const [left, setLeft] = useState(COUNTDOWN);
const [runId, setRunId] = useState<string>(); const [runId, setRunId] = useState<string>();
const [refusal, setRefusal] = useState<string>(); const [refusal, setRefusal] = useState<string>();
const [other, setOther] = useState(false); const [other, setOther] = useState(false);
// Set while an undo is being started or followed: the run whose restore is being put back. // Set while an undo is being started or followed: the restore (or undo) being put back. Its presence is the
const [undoOf, setUndoOf] = useState<string>(); // wizard's undo mode, which shows what is being put back instead of the snapshot the person opened.
const [undoRun, setUndoRun] = useState<RefreshRun | undefined>(undo);
const undoOf = undoRun?.id;
// One key per attempt: the same press can never start two restores, even if the request is retried. // One key per attempt: the same press can never start two restores, even if the request is retried.
const attempt = useRef(globalThis.crypto?.randomUUID?.() ?? String(Math.random())); const attempt = useRef(globalThis.crypto?.randomUUID?.() ?? String(Math.random()));
@@ -69,7 +76,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
if (left <= 0) { if (left <= 0) {
setPhase("running"); setPhase("running");
if (!point) return; if (!point) return;
startRefresh(point, attempt.current, undoOf ? { undo_of: undoOf } : { snapshot_id: snapshot.id }) startRefresh(point, attempt.current, undoOf ? { undo_of: undoOf } : { snapshot_id: snapshot!.id })
.then((started) => setRunId(started.id)) .then((started) => setRunId(started.id))
.catch((error) => { .catch((error) => {
setRefusal(REFUSALS[refusalReason(error) ?? ""] ?? "The restore could not be started."); setRefusal(REFUSALS[refusalReason(error) ?? ""] ?? "The restore could not be started.");
@@ -80,39 +87,62 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
} }
const timer = window.setTimeout(() => setLeft((value) => value - 1), 1000); const timer = window.setTimeout(() => setLeft((value) => value - 1), 1000);
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, [phase, left, point, snapshot.id, undoOf]); }, [phase, left, point, snapshot?.id, undoOf]);
const abortable = phase === "countdown" || (phase === "running" && !finished && progress.index < 2); const abortable = phase === "countdown" || (phase === "running" && !finished && progress.index < 2);
const abort = async () => { const abort = async () => {
if (phase === "countdown") { if (phase === "countdown") {
setPhase("idle"); setPhase("idle");
setUndoRun(undo);
setLeft(COUNTDOWN); setLeft(COUNTDOWN);
} else if (runId) { } else if (runId) {
try { await cancelRefresh(runId); } catch { /* it moved past the point where it can be cancelled */ } try { await cancelRefresh(runId); } catch { /* it moved past the point where it can be cancelled */ }
} }
}; };
const again = () => { const again = () => {
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); setUndoOf(undefined); // Opened to undo one restore: once it is done there is nothing left to do here.
if (!snapshot && onDone) { onDone(); return; }
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); setUndoRun(undefined);
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random()); attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
}; };
// The newest restore on the chosen restore point, if it can still be undone. // The newest restore on the chosen restore point, if it can still be undone.
const recent = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, enabled: phase === "idle", retry: false, refetchInterval: 15_000 }); const recent = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, retry: false, refetchInterval: 15_000 });
const runsById = new Map((Array.isArray(recent.data) ? recent.data : []).map((r) => [r.id, r]));
const undoable = Array.isArray(recent.data) ? recent.data.find((r) => r.relation_id === point?.id && r.undo_available) : undefined; const undoable = Array.isArray(recent.data) ? recent.data.find((r) => r.relation_id === point?.id && r.undo_available) : undefined;
const beginUndo = (of: string) => { const beginUndo = (of: RefreshRun) => {
setRefusal(undefined); setRunId(undefined); setUndoOf(of); setLeft(COUNTDOWN); setPhase("countdown"); setRefusal(undefined); setRunId(undefined); setUndoRun(of); setLeft(COUNTDOWN); setPhase("countdown");
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random()); attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
}; };
const radius = 52; const radius = 52;
const circumference = 2 * Math.PI * radius; const circumference = 2 * Math.PI * radius;
const target = point?.label ?? "the database"; const target = point?.label ?? "the database";
const outcome = run.data && finished ? outcomeOf(run.data, { target, orbit: snapshot.orbit_name, when: formatWhen(snapshot.taken_at) }) : undefined; const outcome = run.data && finished ? outcomeOf(run.data, { target, orbit: snapshot?.orbit_name, when: snapshot ? formatWhen(snapshot.taken_at) : undefined }) : undefined;
const database = snapshot.capture; const database = snapshot?.capture;
const undoing = !!undoRun;
// An undo of an undo puts back what the first undo replaced, so it is a redo.
const verb = (r: RefreshRun) => undoVerb(undoDepth(r, runsById));
// What a run was: a restore, the undo of one, or the redo of that undo.
const what = (r: RefreshRun) => { const depth = undoDepth(r, runsById); return depth === 0 ? "restore" : depth % 2 === 1 ? "undo" : "redo"; };
const undoneAt = undoRun ? formatWhen(new Date(undoRun.updated_at * 1000).toISOString()) : "";
return ( return (
<div className="restore-layout"> <div className="restore-layout">
<div className="restore-top"> <div className="restore-top">
{undoRun ? (
<>
<p className="restore-lead">{verb(undoRun)} the last {what(undoRun)} on {target}.</p>
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">↺</span>
<div className="min-w-0">
<p className="restore-snap-name">{target} as it was before {undoneAt}</p>
<p className="restore-snap-meta">From the safety copy taken just before that {what(undoRun)}</p>
</div>
</div>
</>
) : snapshot && (
<>
<p className="restore-lead">Review the restore point before starting.</p> <p className="restore-lead">Review the restore point before starting.</p>
<div className="restore-snap"> <div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">◇</span> <span className="restore-snap-glyph" aria-hidden="true">◇</span>
@@ -121,14 +151,16 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
<p className="restore-snap-meta">{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}</p> <p className="restore-snap-meta">{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}</p>
</div> </div>
</div> </div>
</>
)}
</div> </div>
{other && admin && database ? ( {other && admin && database && snapshot ? (
<DatabaseRestore snapshot={snapshot.id} application={database.application_id} applicationName={snapshot.orbit_name} engine={database.engine} /> <DatabaseRestore snapshot={snapshot!.id} application={database.application_id} applicationName={snapshot?.orbit_name ?? ""} engine={database.engine} />
) : ( ) : (
<> <>
<div className="restore-fields"> <div className="restore-fields">
<div> <div hidden={undoing}>
<p className="field-label mb-1.5">Restore point</p> <p className="field-label mb-1.5">Restore point</p>
{points.length > 1 ? ( {points.length > 1 ? (
<Segmented label="Restore point" value={point?.id ?? ""} disabled={phase !== "idle"} onChange={setPointId} <Segmented label="Restore point" value={point?.id ?? ""} disabled={phase !== "idle"} onChange={setPointId}
@@ -139,19 +171,27 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
</div> </div>
<div className="restore-warning" role="note"> <div className="restore-warning" role="note">
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 2 14.5 13.5h-13Z" /><path d="M8 6.5v3M8 11.5v.01" /></svg> <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 2 14.5 13.5h-13Z" /><path d="M8 6.5v3M8 11.5v.01" /></svg>
<p>Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot.orbit_name} itself is only read.</p> {undoing ? (
<p>This replaces everything on {target} with its state from before {undoneAt}. Whatever changed on {target} since is lost, but its current state is kept as a new safety copy, so this can be reversed too.</p>
) : (
<p>Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot?.orbit_name} itself is only read. What {target} holds now is kept as a safety copy first, for at least a week, so the restore can be undone.</p>
)}
</div> </div>
<div className="flex gap-2.5"> <div className="flex gap-2.5">
<Button variant="danger" className="flex-1" disabled={!abortable} onClick={() => void abort()}>Abort</Button> <Button variant="danger" className="flex-1" disabled={!abortable} onClick={() => void abort()}>Abort</Button>
<Button variant="primary" className="flex-1" disabled={!point || phase !== "idle"} onClick={() => { setRefusal(undefined); setUndoOf(undefined); setLeft(COUNTDOWN); setPhase("countdown"); }}> <Button variant="primary" className="flex-1" disabled={!point || phase !== "idle"} onClick={() => { setRefusal(undefined); setLeft(COUNTDOWN); setPhase("countdown"); }}>
Begin restore {undoRun ? `Begin ${verb(undoRun).toLowerCase()}` : "Begin restore"}
</Button> </Button>
</div> </div>
{refusal && <p role="alert" className="text-sm text-orbit-red">{refusal}</p>} {refusal && <p role="alert" className="text-sm text-orbit-red">{refusal}</p>}
{undoable && phase === "idle" && !runId && ( {undoable && !undoRun && phase === "idle" && !runId && (
<div className="restore-undo"> <div className="restore-undo">
<p>The last restore on {target} was {formatWhen(new Date(undoable.updated_at * 1000).toISOString())}. Its safety copy can put {target} back as it was before.</p> <p>
<Button onClick={() => beginUndo(undoable.id)}>Undo last restore</Button> {undoable.undo ? `${target} was last put back (${what(undoable)}) on` : `${target} was last restored on`} {formatWhen(new Date(undoable.updated_at * 1000).toISOString())}.
{" "}{`${verb(undoable)} returns it to what it held before.`}
{undoable.undo_kept_until ? ` Its safety copy is kept at least until ${formatWhen(new Date(undoable.undo_kept_until * 1000).toISOString())}.` : ""}
</p>
<Button onClick={() => beginUndo(undoable)}>{`${verb(undoable)} last ${what(undoable)}`}</Button>
</div> </div>
)} )}
{admin && database && phase === "idle" && !runId && ( {admin && database && phase === "idle" && !runId && (
@@ -161,7 +201,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
<aside className="restore-status"> <aside className="restore-status">
<p className="restore-status-label">{phase === "running" ? "Progress" : "Countdown"}</p> <p className="restore-status-label">{phase === "running" ? "Progress" : "Countdown"}</p>
{phase === "idle" && <p className="restore-idle">No restore is running. Begin restore to start the countdown.</p>} {phase === "idle" && <p className="restore-idle">Nothing is running. Begin to start the countdown.</p>}
{phase === "countdown" && ( {phase === "countdown" && (
<motion.div className="restore-count" initial={{ opacity: 0 }} animate={{ opacity: 1 }}> <motion.div className="restore-count" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
<div className="restore-ring"> <div className="restore-ring">
@@ -172,7 +212,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
</svg> </svg>
<span className="restore-ring-text"><b>{left}</b><i>seconds</i></span> <span className="restore-ring-text"><b>{left}</b><i>seconds</i></span>
</div> </div>
<p className="restore-count-note">{undoOf ? `Undoing the last restore on ${target} in ${left}s.` : `Restoring to ${target} in ${left}s.`}<br />Abort restores nothing.</p> <p className="restore-count-note">{undoRun ? `${verb(undoRun)}ing on ${target} in ${left}s.` : `Restoring to ${target} in ${left}s.`}<br />Abort restores nothing.</p>
</motion.div> </motion.div>
)} )}
{phase === "running" && ( {phase === "running" && (
@@ -200,8 +240,8 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
<p>{outcome.title}</p> <p>{outcome.title}</p>
<p>{outcome.detail}</p> <p>{outcome.detail}</p>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{run.data?.undo_available && <Button onClick={() => beginUndo(run.data!.id)}>Undo this restore</Button>} {run.data?.undo_available && <Button variant="primary" onClick={() => beginUndo(run.data!)}>{run.data.status === "recovery_required" ? "Roll back" : run.data.undo ? verb(run.data) : "Undo this restore"}</Button>}
<Button onClick={again}>{outcome.tone === "good" ? "Restore again" : "Try again"}</Button> <Button onClick={again}>{outcome.tone === "good" ? "Done" : "Try again"}</Button>
</div> </div>
</div> </div>
)} )}

View File

@@ -1,27 +1,32 @@
import { useMemo } from "react"; import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { fetchCaptureJobs, fetchRecentRestoreJobs, type Orbit, type Snapshot } from "../api"; import { fetchCaptureJobs, fetchRecentRestoreJobs, fetchRefreshRuns, type Orbit, type Snapshot } from "../api";
import { activityCounts, buildActivity } from "../lib/activity"; import { activityCounts, buildActivity } from "../lib/activity";
/** Everything the hub reports as backups and restores, folded into one log. Polling shares keys with the Orbits console. */ /** Everything the hub reports as backups and restores, folded into one log. Polling shares keys with the Orbits console. */
export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[], canSeeRestores = true) { export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[], { admin = true, refresh = true } = {}) {
// Restore history is administrator-only; asking would only produce a 403. // Restore jobs carry databases and people, so only administrators may read them; asking would only produce a 403.
const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false, enabled: canSeeRestores }); const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false, enabled: admin });
// Which restore an undo reverses, and which of them can still be put back.
const runs = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, refetchInterval: 5_000, retry: false, enabled: refresh });
const captures = useQuery({ queryKey: ["capture-jobs", "", ""], queryFn: () => fetchCaptureJobs("", ""), refetchInterval: 5_000, retry: 1 }); const captures = useQuery({ queryKey: ["capture-jobs", "", ""], queryFn: () => fetchCaptureJobs("", ""), refetchInterval: 5_000, retry: 1 });
const restoreData = restores.data; const restoreData = restores.data;
const captureData = captures.data; const captureData = captures.data;
const runData = Array.isArray(runs.data) ? runs.data : undefined;
const entries = useMemo(() => buildActivity({ const entries = useMemo(() => buildActivity({
snapshots: snapshots ?? [], snapshots: snapshots ?? [],
orbits: orbits ?? [], orbits: orbits ?? [],
captureJobs: captureData ?? [], captureJobs: captureData ?? [],
restoreJobs: restoreData ?? [], restoreJobs: restoreData ?? [],
refreshRuns: runData ?? [],
now: Date.now(), now: Date.now(),
}), [snapshots, orbits, captureData, restoreData]); }), [snapshots, orbits, captureData, restoreData, runData]);
return { return {
entries, entries,
counts: activityCounts(entries), counts: activityCounts(entries),
restoresUnavailable: canSeeRestores && restores.isError, // Runs are enough to list restores; jobs only add detail for an administrator.
restoresUnavailable: refresh ? runs.isError && (!admin || restores.isError) : admin && restores.isError,
capturesUnavailable: captures.isError, capturesUnavailable: captures.isError,
updatedAt: Math.max(restores.dataUpdatedAt, captures.dataUpdatedAt), updatedAt: Math.max(restores.dataUpdatedAt, runs.dataUpdatedAt, captures.dataUpdatedAt),
}; };
} }

View File

@@ -979,11 +979,14 @@ button:disabled { cursor: default; }
.activity-list h3 { padding: 10px 16px 6px; background: #0b0d10; border-bottom: 1px solid #1f2327; font: 500 9.5px/1.4 var(--font-mono); letter-spacing: .14em; text-transform: uppercase; color: var(--quiet); } .activity-list h3 { padding: 10px 16px 6px; background: #0b0d10; border-bottom: 1px solid #1f2327; font: 500 9.5px/1.4 var(--font-mono); letter-spacing: .14em; text-transform: uppercase; color: var(--quiet); }
.activity-list h3[data-tone="needs"] { color: var(--color-orbit-red); } .activity-list h3[data-tone="needs"] { color: var(--color-orbit-red); }
.activity-list h3[data-tone="running"] { color: var(--color-orbit-amber); } .activity-list h3[data-tone="running"] { color: var(--color-orbit-amber); }
.act-row { width: 100%; box-sizing: border-box; display: grid; grid-template-columns: 56px 82px minmax(0, 1fr) 188px 84px; gap: 14px; align-items: center; min-height: 52px; padding: 6px 16px; border-bottom: 1px solid #1a1d21; text-align: left; } .act-row { width: 100%; box-sizing: border-box; display: grid; grid-template-columns: 56px 82px minmax(0, 1fr) 188px minmax(84px, max-content); gap: 14px; align-items: center; min-height: 52px; padding: 6px 16px; border-bottom: 1px solid #1a1d21; text-align: left; }
button.act-row:hover { background: #14171b; } button.act-row:hover { background: #14171b; }
.act-row[data-group="needs"] { background: #1a1214; box-shadow: inset 2px 0 var(--color-orbit-red); } .act-row[data-group="needs"] { background: #1a1214; box-shadow: inset 2px 0 var(--color-orbit-red); }
button.act-row[data-group="needs"]:hover { background: #20161a; } button.act-row[data-group="needs"]:hover { background: #20161a; }
.act-row[data-static] { opacity: .65; } .act-row[data-static] { opacity: .65; }
.act-row[data-child] { position: relative; padding-left: calc(16px + 24px * var(--depth, 1)); background: #0c0e11; }
.act-row[data-child]::before { content: ""; position: absolute; left: calc(24px * var(--depth, 1)); top: 0; bottom: 50%; width: 10px; border-left: 1px solid #3a3f46; border-bottom: 1px solid #3a3f46; border-bottom-left-radius: 6px; }
.act-open[data-note] { color: var(--quiet); font-style: italic; text-align: right; }
.act-time { font: 11px var(--font-mono); color: var(--quiet); } .act-time { font: 11px var(--font-mono); color: var(--quiet); }
.act-kind { display: flex; align-items: center; gap: 7px; font: 500 9.5px/1 var(--font-mono); letter-spacing: .1em; text-transform: uppercase; } .act-kind { display: flex; align-items: center; gap: 7px; font: 500 9.5px/1 var(--font-mono); letter-spacing: .1em; text-transform: uppercase; }
.act-kind[data-kind="backup"] { color: #9db8e8; } .act-kind[data-kind="backup"] { color: #9db8e8; }

View File

@@ -1,8 +1,12 @@
import type { CaptureJob, Orbit, RestoreJob, Snapshot } from "../api"; import type { CaptureJob, Orbit, RefreshRun, RestoreJob, Snapshot } from "../api";
import { formatBytes, formatWhen } from "./format.ts"; import { formatBytes, formatWhen } from "./format.ts";
import { undoDepth } from "./restoreRun.ts";
/** Where an entry leads. Restores and exports start from a snapshot, so that is where most entries go. */ /** Where an entry leads. Restores and exports start from a snapshot, so that is where most entries go. */
export type ActivityTarget = { kind: "snapshot" | "orbit"; id: string }; export type ActivityTarget =
| { kind: "snapshot" | "orbit"; id: string }
/** A restore (or undo) that can still be put back: opens the undo (or redo) dialog for this run. */
| { kind: "undo" | "redo"; run: RefreshRun };
export type ActivityEntry = { export type ActivityEntry = {
id: string; id: string;
@@ -17,8 +21,19 @@ export type ActivityEntry = {
opens: ActivityTarget | null; opens: ActivityTarget | null;
/** Position along the five phases of a job in flight, 0 to 4. */ /** Position along the five phases of a job in flight, 0 to 4. */
progress?: number; progress?: number;
/** Said in place of the link, when the entry leads nowhere on purpose (for instance, its safety backup expired). */
note?: string;
/** An undo (a restore put back) or a redo (an undo put back), shown under the restore it reverses. */
variant?: "undo" | "redo";
/** The undo or redo of this restore, oldest first. They are listed under it, not on their own. */
children?: ActivityEntry[];
/** Where the entry sits in the log: its own group and time, or the most urgent and newest of its subtree. */
slotGroup: "needs" | "running" | "history";
slotAt: number | null;
}; };
type Draft = Omit<ActivityEntry, "slotGroup" | "slotAt" | "children"> & { children?: Draft[] };
const captureLabels: Record<string, string> = { const captureLabels: Record<string, string> = {
queued: "Waiting for outpost", queued: "Waiting for outpost",
claimed: "Assigned to agent", claimed: "Assigned to agent",
@@ -41,6 +56,7 @@ const restoreLabels: Record<string, string> = {
wrong_target: "Target identity check failed", wrong_target: "Target identity check failed",
invalid_payload: "Archive check failed", invalid_payload: "Archive check failed",
safety_failed: "Safety copy could not be verified", safety_failed: "Safety copy could not be verified",
rolled_back: "Rolled back",
apply_failed: "Apply failed", apply_failed: "Apply failed",
lease_lost: "Agent disconnected during apply", lease_lost: "Agent disconnected during apply",
reconciled: "Recovery verified", reconciled: "Recovery verified",
@@ -48,23 +64,36 @@ const restoreLabels: Record<string, string> = {
}; };
const restoreOrder: string[][] = [["queued", "claimed"], ["checking"], ["safety"], ["ready", "applying"], ["completed", "reconciled"]]; const restoreOrder: string[][] = [["queued", "claimed"], ["checking"], ["safety"], ["ready", "applying"], ["completed", "reconciled"]];
const EXPIRED = "Safety backup expired";
const shortId = (id: string) => id.slice(0, 8); const shortId = (id: string) => id.slice(0, 8);
const inFlight = (status: string) => status === "queued" || status === "running" || status === "applying"; const inFlight = (status: string) => status === "queued" || status === "running" || status === "applying";
function restoreEntry(job: RestoreJob, snapshots: Map<string, Snapshot>): ActivityEntry { function restoreEntry(job: RestoreJob, snapshots: Map<string, Snapshot>, run: RefreshRun | undefined, runs: Map<string, RefreshRun>): Draft {
const source = snapshots.get(job.snapshot_id); const source = snapshots.get(job.snapshot_id);
const from = source ? `${source.orbit_name} · ${formatWhen(source.taken_at)}` : `Snapshot ${shortId(job.snapshot_id)}`; const from = source ? `${source.orbit_name} · ${formatWhen(source.taken_at)}` : `Snapshot ${shortId(job.snapshot_id)}`;
const phase = restoreLabels[job.phase] ?? job.status; const phase = restoreLabels[job.phase] ?? job.status;
const depth = run ? undoDepth(run, runs) : 0;
// What this row did (an undo, then a redo of it, then an undo of that) and what opening it offers are opposites.
const variant = depth === 0 ? undefined : depth % 2 === 1 ? "undo" as const : "redo" as const;
const where = `${job.target.name} / ${job.target.identity.database}`;
// An undo restores the safety copy of an earlier restore, which has no snapshot to open: it opens its own dialog.
// A restore whose safety backup retention has forgotten says so, instead of leading anywhere that suggests it is there.
const expired = run?.undo_state === "expired";
const opens: ActivityTarget | null = expired ? null : run?.undo_available ? { kind: variant === "undo" ? "redo" : "undo", run }
: source ? { kind: "snapshot", id: source.id } : null;
const base = { const base = {
id: `restore-${job.id}`, id: `restore-${job.id}`,
kind: "restore" as const, kind: "restore" as const,
variant,
at: job.created_at * 1000, at: job.created_at * 1000,
title: `${from} → ${job.target.name} / ${job.target.identity.database}`, title: variant ? `${variant === "redo" ? "Redo" : "Undo"} → ${where}` : `${from} → ${where}`,
opens: source ? { kind: "snapshot" as const, id: source.id } : null, opens,
note: expired ? EXPIRED : undefined,
}; };
if (job.status === "recovery_required") { if (job.status === "recovery_required") {
return { ...base, group: "needs", tone: "red", state: "Recovery required", return { ...base, group: "needs", tone: "red", state: "Recovery required",
meta: `Restore · ${phase.toLowerCase()} · target locked until verified · open the snapshot` }; meta: `Restore · ${phase.toLowerCase()} · ${run?.undo_available ? "roll back available" : "target locked until verified · open the snapshot"}` };
} }
if (inFlight(job.status)) { if (inFlight(job.status)) {
const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(job.phase))); const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(job.phase)));
@@ -78,11 +107,54 @@ function restoreEntry(job: RestoreJob, snapshots: Map<string, Snapshot>): Activi
return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: `Restore · by ${job.actor}` }; return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: `Restore · by ${job.actor}` };
} }
const recovered = job.status === "reconciled"; const recovered = job.status === "reconciled";
return { ...base, group: "history", tone: "green", state: recovered ? "Recovered" : "Complete", const rolledBack = job.phase === "rolled_back";
meta: `Restore · ${job.safety_snapshot_id ? "safety copy kept · " : ""}by ${job.actor}` }; const noun = variant === "redo" ? "Redo" : variant === "undo" ? "Undo" : "Restore";
const undoable = run?.undo_available ? ` · ${variant === "undo" ? "redo" : "undo"} available` : "";
return { ...base, group: "history", tone: "green", state: rolledBack ? "Rolled back" : recovered ? "Recovered" : "Complete",
meta: `${noun} · ${job.safety_snapshot_id ? "safety copy kept · " : ""}by ${job.actor}${undoable}` };
} }
function captureEntry(job: CaptureJob, orbits: Map<string, Orbit>): ActivityEntry | undefined { /** The id a restore has in the log: its job's when it has one, so a run and its job are one entry. */
const restoreId = (run: RefreshRun) => (run.restore_job_id ? `restore-${run.restore_job_id}` : `restore-run-${run.id}`);
const runStopped: Record<string, string> = { restore_failed: "Failed", blocked: "Stopped", expired: "Expired", capture_failed: "Could not start" };
/**
* A restore as the run shows it, for people who may not read restore jobs (those are administrator-only): what was
* restored where, how far it got, and whether it can be put back. It carries no database names or who started it.
*/
function runEntry(run: RefreshRun, runs: Map<string, RefreshRun>): Draft {
const depth = undoDepth(run, runs);
const variant = depth === 0 ? undefined : depth % 2 === 1 ? "undo" as const : "redo" as const;
const taken = run.snapshot_taken_at ? formatWhen(new Date(run.snapshot_taken_at * 1000).toISOString()) : undefined;
const noun = variant === "redo" ? "Redo" : variant === "undo" ? "Undo" : "Restore";
const base = {
id: restoreId(run),
kind: "restore" as const,
variant,
at: run.created_at * 1000,
title: variant ? `${noun} → ${run.target_name}` : `${run.source_name}${taken ? ` · ${taken}` : ""} → ${run.target_name}`,
opens: run.undo_available ? { kind: variant === "undo" ? "redo" as const : "undo" as const, run } : null,
// A restore known only by its run has nothing to open unless it can be put back; that is not "removed".
note: run.undo_state === "expired" ? EXPIRED : run.undo_available ? undefined : "",
};
const phase = (run.restore_phase && restoreLabels[run.restore_phase]) || undefined;
if (run.status === "recovery_required") {
return { ...base, group: "needs", tone: "red", state: "Recovery required",
meta: `${noun} · ${(phase ?? "interrupted").toLowerCase()} · ${run.undo_available ? "roll back available" : "target locked until an administrator verifies it"}` };
}
if (run.status === "capturing" || run.status === "restoring") {
const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(run.restore_phase ?? "queued")));
return { ...base, group: "running", tone: "amber", state: phase ?? "Running", progress, meta: `${noun} · step ${progress + 1} of 5` };
}
if (run.status === "cancelled") return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: noun };
const stopped = runStopped[run.status];
if (stopped) return { ...base, group: "history", tone: "red", state: stopped, meta: `${noun}${phase && run.status === "restore_failed" ? ` · ${phase.toLowerCase()}` : ""}` };
return { ...base, group: "history", tone: "green", state: run.restore_phase === "rolled_back" ? "Rolled back" : run.status === "reconciled" ? "Recovered" : "Complete",
meta: `${noun}${run.undo_available ? ` · ${variant === "undo" ? "redo" : "undo"} available` : ""}` };
}
function captureEntry(job: CaptureJob, orbits: Map<string, Orbit>): Draft | undefined {
const orbit = orbits.get(job.profile.orbit_id); const orbit = orbits.get(job.profile.orbit_id);
const name = orbit?.name ?? job.profile.application_id; const name = orbit?.name ?? job.profile.application_id;
const base = { const base = {
@@ -104,17 +176,35 @@ function captureEntry(job: CaptureJob, orbits: Map<string, Orbit>): ActivityEntr
return undefined; return undefined;
} }
export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, now }: { const urgency = { needs: 0, running: 1, history: 2 } as const;
/** Entries sit in the log by their own group and time, except a restore, which sits by its most urgent and newest undo. */
function place(entry: Draft): ActivityEntry {
const children = entry.children?.map(place);
let slotGroup = entry.group;
let slotAt = entry.at;
for (const child of children ?? []) {
if (urgency[child.slotGroup] < urgency[slotGroup]) slotGroup = child.slotGroup;
if ((child.slotAt ?? -Infinity) > (slotAt ?? -Infinity)) slotAt = child.slotAt;
}
return { ...entry, children, slotGroup, slotAt };
}
export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, refreshRuns = [], now }: {
snapshots: readonly Snapshot[]; snapshots: readonly Snapshot[];
orbits: readonly Orbit[]; orbits: readonly Orbit[];
captureJobs: readonly CaptureJob[]; captureJobs: readonly CaptureJob[];
restoreJobs: readonly RestoreJob[]; restoreJobs: readonly RestoreJob[];
/** The hub's restore runs: they say which restore an undo reverses. */
refreshRuns?: readonly RefreshRun[];
now: number; now: number;
}): ActivityEntry[] { }): ActivityEntry[] {
const snapshotById = new Map(snapshots.map((snapshot) => [snapshot.id, snapshot])); const snapshotById = new Map(snapshots.map((snapshot) => [snapshot.id, snapshot]));
const orbitById = new Map(orbits.map((orbit) => [orbit.id, orbit])); const orbitById = new Map(orbits.map((orbit) => [orbit.id, orbit]));
const jobForSnapshot = new Map(captureJobs.filter((job) => job.snapshot_id).map((job) => [job.snapshot_id!, job])); const jobForSnapshot = new Map(captureJobs.filter((job) => job.snapshot_id).map((job) => [job.snapshot_id!, job]));
const entries: ActivityEntry[] = []; const runByJob = new Map(refreshRuns.filter((run) => run.restore_job_id).map((run) => [run.restore_job_id!, run]));
const runById = new Map(refreshRuns.map((run) => [run.id, run]));
const entries: Draft[] = [];
for (const snapshot of snapshots) { for (const snapshot of snapshots) {
const job = jobForSnapshot.get(snapshot.id); const job = jobForSnapshot.get(snapshot.id);
@@ -146,13 +236,40 @@ export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, now
opens: { kind: "orbit", id: orbit.id } }); opens: { kind: "orbit", id: orbit.id } });
} }
} }
for (const job of restoreJobs) entries.push(restoreEntry(job, snapshotById)); // Every restore comes from its run, which anyone with the refresh permission may read; an administrator's restore
// job adds the database, the person and the snapshot, and restores started without a run (another registered
// target) are only known by their job.
const jobById = new Map(restoreJobs.map((job) => [job.id, job]));
const parentOf = new Map<string, string>();
for (const run of refreshRuns) {
const job = run.restore_job_id ? jobById.get(run.restore_job_id) : undefined;
entries.push(job ? restoreEntry(job, snapshotById, run, runById) : runEntry(run, runById));
const parent = run.undo_of ? runById.get(run.undo_of) : undefined;
if (parent) parentOf.set(restoreId(run), restoreId(parent));
}
for (const job of restoreJobs) if (!runByJob.has(job.id)) entries.push(restoreEntry(job, snapshotById, undefined, runById));
const rank = { needs: 0, running: 1, history: 2 } as const; // An undo hangs under the restore it reverses, and a redo under that undo, when that restore is in the log.
return entries.sort((a, b) => rank[a.group] - rank[b.group] || (b.at ?? -Infinity) - (a.at ?? -Infinity) || a.id.localeCompare(b.id)); const byId = new Map(entries.map((entry) => [entry.id, entry]));
const top: Draft[] = [];
for (const entry of entries) {
const parent = byId.get(parentOf.get(entry.id) ?? "");
if (parent && parent !== entry) (parent.children ??= []).push(entry);
else top.push(entry);
}
const oldestFirst = (entry: Draft) => { entry.children?.sort((x, y) => (x.at ?? 0) - (y.at ?? 0)); entry.children?.forEach(oldestFirst); };
top.forEach(oldestFirst);
return top.map(place)
.sort((a, b) => urgency[a.slotGroup] - urgency[b.slotGroup] || (b.slotAt ?? -Infinity) - (a.slotAt ?? -Infinity) || a.id.localeCompare(b.id));
} }
export function activityCounts(entries: readonly ActivityEntry[]) { /** Every entry in the log, undos included. */
export function flatten(entries: readonly ActivityEntry[]): ActivityEntry[] {
return entries.flatMap((entry) => [entry, ...flatten(entry.children ?? [])]);
}
export function activityCounts(all: readonly ActivityEntry[]) {
const entries = flatten(all);
return { return {
running: entries.filter(({ group }) => group === "running").length, running: entries.filter(({ group }) => group === "running").length,
needs: entries.filter(({ group }) => group === "needs").length, needs: entries.filter(({ group }) => group === "needs").length,

View File

@@ -2,10 +2,23 @@
export const STAGES = ["Checking", "Safety copy", "Applying", "Completed"] as const; export const STAGES = ["Checking", "Safety copy", "Applying", "Completed"] as const;
type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null; undo?: boolean }; type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null; undo?: boolean; undo_available?: boolean };
const STOPPED = new Set(["restore_failed", "recovery_required", "blocked", "expired", "capture_failed"]); const STOPPED = new Set(["restore_failed", "recovery_required", "blocked", "expired", "capture_failed"]);
/** How many undos deep a run is: a restore is 0, its undo 1, the undo of that undo 2. */
export function undoDepth(run: { undo_of?: string | null; undo?: boolean }, byId: ReadonlyMap<string, { undo_of?: string | null; undo?: boolean }>): number {
let depth = 0;
for (let at: typeof run | undefined = run, seen = 0; at?.undo && seen < 50; seen++) {
depth++;
at = at.undo_of ? byId.get(at.undo_of) : undefined;
}
return depth;
}
/** What opening a run offers: putting back a restore is an undo, putting back an undo is a redo, and so on. */
export const undoVerb = (depth: number) => (depth % 2 === 0 ? "Undo" : "Redo");
/** The step a restore job's phase belongs to. */ /** The step a restore job's phase belongs to. */
function stageOfPhase(phase: string | null): number { function stageOfPhase(phase: string | null): number {
switch (phase) { switch (phase) {
@@ -76,7 +89,13 @@ export function outcomeOf(
case "restore_failed": case "restore_failed":
return { tone: "bad", title: "The restore failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` }; return { tone: "bad", title: "The restore failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` };
case "recovery_required": case "recovery_required":
return { tone: "bad", title: "The restore was interrupted", detail: `It stopped while overwriting ${target}. Do not use that database; an administrator has to recover it.` }; return {
tone: "bad",
title: "The restore was interrupted",
detail: run.undo_available
? `It stopped while overwriting ${target}, which may be half restored. Do not use that database: roll it back to what it held before, or ask an administrator to recover it.`
: `It stopped while overwriting ${target}. Do not use that database; an administrator has to recover it.`,
};
case "blocked": case "blocked":
return { tone: "bad", title: "The restore was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` }; return { tone: "bad", title: "The restore was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` };
case "expired": case "expired":

View File

@@ -1,268 +0,0 @@
import { createBlackholeRenderer, defaultParams, type BlackholeParams } from "../lib/blackhole/renderer";
import { farthestCornerM } from "../lib/blackhole/layout";
import { createLook, requestLook, stepLook, styleAt, waveParams } from "../lib/blackhole/look";
import { QUALITY_TIERS, chooseTier, initialTier } from "../lib/blackhole/quality";
const canvas = document.querySelector<HTMLCanvasElement>("#stage")!;
const panel = document.querySelector<HTMLDivElement>("#panel")!;
const probe = document.createElement("canvas").getContext("webgl2");
const probeInfo = probe?.getExtension("WEBGL_debug_renderer_info");
const software = /swiftshader|llvmpipe|software/i.test(String(probeInfo ? probe!.getParameter(probeInfo.UNMASKED_RENDERER_WEBGL) : ""));
const nav = navigator as Navigator & { deviceMemory?: number };
const dpr = Math.min(window.devicePixelRatio || 1, 2);
let tier = initialTier({
software, cores: navigator.hardwareConcurrency, memoryGb: nav.deviceMemory,
pixels: window.innerWidth * window.innerHeight * dpr * dpr,
});
const renderer = createBlackholeRenderer(canvas, { skySize: QUALITY_TIERS[tier].skySize });
if (!renderer) {
document.querySelector<HTMLElement>("#fail")!.style.display = "grid";
throw new Error("WebGL2 unavailable");
}
// ?throttle=N draws the scene N times per frame, standing in for a GPU N times slower.
const throttle = Math.max(1, Math.round(Number(new URLSearchParams(location.search).get("throttle")) || 1));
if (throttle > 1) {
const draw = renderer.render;
renderer.render = (time, drawParams) => { for (let i = 0; i < throttle; i++) draw(time, drawParams); };
}
const params: BlackholeParams = { ...defaultParams };
const state = { frozenWave: false, scale: 1, speed: 1, paused: false, swayAmount: 1, maxFps: 30, auto: true, tierName: "" };
let diskClock = 0;
let last = performance.now();
let lastRender = 0;
let drawMs = 0;
let dirty = true;
let raf = 0;
let sweeping = false;
const readout = document.createElement("pre");
// The radar look arrives as a wave spreading outward from the hole (see lib/blackhole/look.ts).
const look = createLook(0);
let wave = waveParams(look, 0);
const modeBar = document.querySelector<HTMLDivElement>("#modes")!;
for (const [name, value] of [["realistic", 0], ["radar", 1]] as const) {
const element = document.createElement("button");
element.textContent = name;
element.dataset.mode = name;
element.addEventListener("click", () => setMode(value));
modeBar.append(element);
}
function setMode(value: 0 | 1) {
requestLook(look, value);
for (const element of modeBar.children) element.classList.toggle("on", (element as HTMLElement).dataset.mode === (value ? "radar" : "realistic"));
wake();
}
function applyWave() {
const center = { x: params.centerX * window.innerWidth, y: params.centerY * window.innerHeight };
const maxRadius = farthestCornerM(center, { width: window.innerWidth, height: window.innerHeight }, params.pxPerM);
wave = waveParams(look, maxRadius);
Object.assign(params, wave, { styleKind: 1 });
}
const tagShadow = document.querySelector<HTMLElement>("#tagShadow")!;
const tagDisk = document.querySelector<HTMLElement>("#tagDisk")!;
const ringTags = [6, 12, 18, 24, 30].map((range) => {
const element = document.createElement("div");
element.className = "tag mint";
element.textContent = `${range} M`;
document.body.append(element);
return { range, element };
});
// Labels appear as the wave front passes them, using the same maths as the shader.
function placeTags() {
const cx = params.centerX * window.innerWidth, cy = params.centerY * window.innerHeight;
const at = (radius: number) => styleAt(wave, radius);
// A small legend in the corner, revealed as the wave front reaches it.
const legend = at(params.diskOut + 2);
tagShadow.style.opacity = String(legend);
tagShadow.style.left = "24px";
tagShadow.style.top = `${window.innerHeight - 54}px`;
tagDisk.style.opacity = String(legend);
tagDisk.style.left = "24px";
tagDisk.style.top = `${window.innerHeight - 34}px`;
for (const { range, element } of ringTags) {
const angle = (62 * Math.PI) / 180;
element.style.opacity = String(at(range) * 0.75);
element.style.left = `${cx + range * params.pxPerM * Math.cos(angle) + 4}px`;
element.style.top = `${cy - range * params.pxPerM * Math.sin(angle) - 12}px`;
}
}
const sliders: Record<string, HTMLInputElement> = {};
function wake() {
dirty = true;
if (!raf) raf = requestAnimationFrame(frame);
}
function slider(label: string, get: () => number, set: (value: number) => void, min: number, max: number, step: number, apply?: () => void) {
const row = document.createElement("label");
const input = document.createElement("input");
const value = document.createElement("span");
input.type = "range";
Object.assign(input, { min, max, step, value: get() });
const show = () => { value.textContent = Number(input.value).toFixed(step < 0.1 ? 2 : 1); };
input.addEventListener("input", () => { set(Number(input.value)); show(); apply?.(); wake(); });
show();
row.append(label, input, value);
panel.append(row);
sliders[label] = input;
}
function resize() {
renderer!.resize(window.innerWidth, window.innerHeight, dpr, state.scale);
wake();
}
function applyTier(next: number) {
tier = next;
const preset = QUALITY_TIERS[tier];
state.scale = preset.scale;
state.maxFps = preset.maxFps;
state.tierName = preset.name;
state.paused = preset.maxFps === 0;
params.steps = preset.steps;
params.stepScale = preset.stepScale;
params.bloomPasses = preset.bloomPasses;
resize();
}
/** Time a handful of synchronised frames and step the quality down until the budget holds. */
function calibrate() {
if (!state.auto) return;
for (let attempt = 0; attempt < QUALITY_TIERS.length; attempt++) {
const samples: number[] = [];
for (let i = 0; i < 24; i++) {
const start = performance.now();
renderer!.render(i * 0.016, params);
renderer!.finish();
samples.push(performance.now() - start);
}
const next = chooseTier({ tier, samples, sinceChangeMs: Infinity });
if (next === tier) return;
applyTier(next);
}
}
const physical = (key: keyof BlackholeParams) => () => params[key] as number;
const assign = (key: keyof BlackholeParams) => (value: number) => { (params as Record<string, unknown>)[key] = value; };
slider("elevation °", () => params.elevation * 180 / Math.PI, (v) => { params.elevation = v * Math.PI / 180; }, 5, 88, 0.5);
slider("scale M→px", physical("pxPerM"), assign("pxPerM"), 4, 40, 0.1);
slider("sky", physical("sky"), assign("sky"), 0, 1.5, 0.05);
slider("disk gain", physical("diskGain"), assign("diskGain"), 0.2, 4, 0.05);
slider("doppler", physical("doppler"), assign("doppler"), 0, 1, 0.05);
slider("bloom", physical("bloom"), assign("bloom"), 0, 3, 0.05);
slider("exposure", physical("exposure"), assign("exposure"), 0.3, 3, 0.05);
slider("absorb", physical("absorb"), assign("absorb"), 0, 1, 0.05);
slider("disk speed", () => state.speed, (v) => { state.speed = v; }, 0, 4, 0.05);
slider("sway", () => state.swayAmount, (v) => { state.swayAmount = v; }, 0, 4, 0.05);
const row = document.createElement("div");
row.className = "row";
const button = (label: string, action: () => void) => {
const element = document.createElement("button");
element.textContent = label;
element.addEventListener("click", () => { action(); wake(); });
row.append(element);
return element;
};
const select = document.createElement("select");
for (const option of ["auto", ...QUALITY_TIERS.map(({ name }) => name)]) select.append(new Option(option, option));
select.addEventListener("change", () => {
state.auto = select.value === "auto";
if (state.auto) { applyTier(initialTier({ software, cores: navigator.hardwareConcurrency, memoryGb: nav.deviceMemory, pixels: window.innerWidth * window.innerHeight * dpr * dpr })); calibrate(); }
else applyTier(QUALITY_TIERS.findIndex(({ name }) => name === select.value));
});
row.append(select);
button("pause", () => { state.paused = !state.paused; });
button("shadow ring", () => { params.showShadow = !params.showShadow; });
button("hide panel", () => panel.classList.add("hidden"));
panel.append(row, readout);
window.addEventListener("keydown", (event) => { if (event.key === "h") panel.classList.toggle("hidden"); });
let dragY: number | undefined;
canvas.addEventListener("pointerdown", (event) => { dragY = event.clientY; canvas.setPointerCapture(event.pointerId); });
canvas.addEventListener("pointermove", (event) => {
if (dragY === undefined) return;
params.elevation = Math.max(0.09, Math.min(1.53, params.elevation + (event.clientY - dragY) * 0.004));
dragY = event.clientY;
sliders["elevation °"].value = String(params.elevation * 180 / Math.PI);
wake();
});
canvas.addEventListener("pointerup", () => { dragY = undefined; });
let settle = 0;
window.addEventListener("resize", () => {
resize();
clearTimeout(settle);
settle = window.setTimeout(calibrate, 400);
});
function frame(now: number) {
raf = 0;
if (!dirty && state.paused && !look.running && !sweeping) return;
if (!look.running && !sweeping && state.maxFps > 0 && now - lastRender < 1000 / state.maxFps - 2 && !dirty) { raf = requestAnimationFrame(frame); return; }
const delta = Math.min(0.1, (now - last) / 1000);
last = now;
lastRender = now;
if (!state.frozenWave) {
stepLook(look, delta);
applyWave();
}
params.sweep = diskClock * 0.8;
// Persistence fades in and out instead of popping when motion pauses.
const sweepTarget = state.paused ? 0 : 1;
params.sweepAmount += (sweepTarget - params.sweepAmount) * Math.min(1, delta * 7);
sweeping = Math.abs(sweepTarget - params.sweepAmount) > 0.004;
if (!sweeping) params.sweepAmount = sweepTarget;
placeTags();
if (!state.paused) diskClock += delta * state.speed;
params.sway = 0.06 * state.swayAmount * Math.sin(diskClock * 0.05);
const start = performance.now();
renderer!.render(diskClock, params);
drawMs += (performance.now() - start - drawMs) * 0.1;
dirty = false;
const { info } = renderer!;
readout.textContent = `${info.renderer}${info.software ? " (SOFTWARE: timings not representative)" : ""}\n` +
`tier: ${state.tierName}${state.auto ? " (auto)" : ""} cap ${state.maxFps} fps${throttle > 1 ? ` THROTTLE ×${throttle}` : ""}\n` +
`canvas ${canvas.width}×${canvas.height} scene ×${state.scale}\n` +
`sky ${info.skySize}² cubemap, baked in ${info.skyBakeMs.toFixed(0)} ms\n` +
`cpu submit ${drawMs.toFixed(2)} ms${state.paused ? "\nIDLE: not rendering" : ""}`;
if (!state.paused || look.running || sweeping) raf = requestAnimationFrame(frame);
}
async function benchmark(scales = [0.5, 0.75, 1], frames = 60) {
const saved = state.scale;
const results: Record<string, number> = {};
for (const scale of scales) {
state.scale = scale;
renderer!.resize(window.innerWidth, window.innerHeight, dpr, scale);
renderer!.render(0, params);
renderer!.finish();
const start = performance.now();
for (let i = 0; i < frames; i++) { renderer!.render(i * 0.016, params); renderer!.finish(); }
results[String(scale)] = Number(((performance.now() - start) / frames).toFixed(2));
}
state.scale = saved;
renderer!.resize(window.innerWidth, window.innerHeight, dpr, saved);
return { renderer: renderer!.info.renderer, software: renderer!.info.software, canvas: [canvas.width, canvas.height], msPerFrame: results };
}
// Debug: hold the wave at a given progress so a still can be inspected. Pass null to release it.
function previewWave(progress: number | null, to: 0 | 1 = 1) {
if (progress === null) { state.frozenWave = false; Object.assign(look, createLook(to)); wake(); return; }
state.frozenWave = true;
Object.assign(look, { from: (1 - to) as 0 | 1, to, progress, velocity: 0, running: true, queued: undefined });
applyWave();
placeTags();
renderer!.render(diskClock, params);
}
Object.assign(window, { __bh: { params, state, benchmark, renderer, wake, applyTier, throttle, setMode, look, previewWave, tier: () => tier } });
modeBar.children[0].classList.add("on");
applyTier(tier);
calibrate();
wake();