Compare commits

..

41 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
648c8c6a2a feat: undo a restore from the safety copy it took
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
- POST /refresh-runs accepts undo_of: restores the safety copy of a completed restore back onto the same
  target through the normal run engine (checks, countdown, progress, and a new safety copy so the undo can be
  undone); refused when something was restored after it or the copy is gone
- a safety copy is accepted as a source only for the target it was taken from (hub and agent both check)
- run views carry undo and undo_available; audited as refresh.undo_started
- the modal offers Undo last restore and, after a restore, Undo this restore
- proven with a real agent and PostgreSQL: restore, undo back to the original contents, undo of the undo

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 16:47:02 +07:00
854e3572e9 chore: take deployment-specific material out of the repository for the first release
- MBU parity map, cutover runbook and the tasks/ planning notes move outside the repo
- tests/mbu becomes tests/fixtures with generic application names and no placement inventory
- test fixtures in Rust and web use neutral names
- scripts/export-public.sh checks an external list of private terms instead of naming them

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 21:50:27 +07:00
89 changed files with 4745 additions and 2636 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;
@@ -126,7 +250,8 @@ async fn run(
let verified = tokio::time::timeout(timeout, async { let verified = tokio::time::timeout(timeout, async {
let identity = target.identity().await?; let identity = target.identity().await?;
ensure!( ensure!(
identity == lease.job.target.identity && identity != lease.artifact.identity, identity == lease.job.target.identity
&& (lease.artifact.rollback || identity != lease.artifact.identity),
"restore target identity does not match" "restore target identity does not match"
); );
if let Some(source) = source { if let Some(source) = source {
@@ -158,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;
@@ -175,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),
@@ -197,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,
@@ -213,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),
@@ -223,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

@@ -89,6 +89,10 @@ pub struct RestoreArtifact {
pub format: CaptureFormat, pub format: CaptureFormat,
pub identity: DatabaseIdentity, pub identity: DatabaseIdentity,
pub sha256: String, pub sha256: String,
/// The artifact is the safety copy a restore took of the very target it is now restored onto (an undo).
/// Its source identity is then the target's own, so the "target is the source" refusal does not apply.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub rollback: bool,
} }
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]

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

@@ -24,5 +24,5 @@ mod session;
pub use orbit::run_orbit_internal; pub use orbit::run_orbit_internal;
pub(crate) use relations::identity_facts; pub(crate) use relations::identity_facts;
pub(crate) use restore::artifact; pub(crate) use restore::{artifact, rollback_artifact};
pub use routes::router; pub use routes::router;

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

@@ -69,9 +69,97 @@ struct RunView {
requested_by: Option<String>, requested_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
snapshot_id: Option<String>, snapshot_id: Option<String>,
/// This run put a target back from the safety copy of an earlier restore.
undo: bool,
/// For an undo, the run whose restore it puts back; the Activity log shows the undo under it.
#[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,
/// 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>,
} }
fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> { /// What `undo_views` found out about one run.
#[derive(Clone, Copy)]
struct Undo {
state: &'static str,
kept_until: Option<i64>,
}
/// 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,
@@ -98,6 +186,12 @@ fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, Stat
expires_at: run.expires_at, expires_at: run.expires_at,
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_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),
}) })
} }
@@ -134,6 +228,10 @@ struct Start {
/// relation's own source. /// relation's own source.
#[serde(default)] #[serde(default)]
snapshot_id: Option<Uuid>, snapshot_id: Option<Uuid>,
/// Put the target back as it was before this earlier restore: restore that restore's safety copy onto the same
/// target. The run must be a completed restore of this relation and the newest one of its target.
#[serde(default)]
undo_of: Option<Uuid>,
} }
fn valid_key(key: &str) -> bool { fn valid_key(key: &str) -> bool {
@@ -144,27 +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,
/// when it was taken (seconds since the epoch).
fn fitting_snapshot(
state: &HubState,
vault: &tessera_store::Vault,
relation: &str,
snapshot: Uuid,
) -> Result<Option<i64>, StatusCode> {
let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else {
return Ok(None);
};
let Some(stored) = vault.get_snapshot(snapshot).map_err(internal)? else {
return Ok(None);
};
let manifest = &stored.manifest;
let target = match state.db.relation_target(relation).map_err(internal)? {
Some(id) => Uuid::parse_str(&id)
.ok()
.and_then(|id| state.db.restore_target(id).ok().flatten()),
None => None,
};
let fits = manifest.orbit_id.to_string() == source
&& if manifest.is_restore_safety() {
// a safety copy only ever goes back onto the target it was taken from
target
.as_ref()
.is_some_and(|target| crate::api::rollback_artifact(manifest, target).is_some())
} else {
crate::api::artifact(manifest).is_some()
};
Ok(fits.then(|| stored.taken_at.timestamp()))
}
async fn snapshot_fits( async fn snapshot_fits(
state: &HubState, state: &HubState,
relation: &str, relation: &str,
snapshot: Uuid, snapshot: Uuid,
) -> Result<bool, StatusCode> { ) -> Result<bool, StatusCode> {
let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else { let vault = state.vault.read().await;
return Ok(false); Ok(fitting_snapshot(state, &vault, relation, snapshot)?.is_some())
};
let manifest = state
.vault
.read()
.await
.get_snapshot(snapshot)
.map_err(internal)?
.map(|s| s.manifest);
Ok(manifest.is_some_and(|manifest| {
manifest.orbit_id.to_string() == source
&& !manifest.is_restore_safety()
&& crate::api::artifact(&manifest).is_some()
}))
} }
async fn start( async fn start(
@@ -179,13 +296,33 @@ async fn start(
} }
super::gate::relation(&state, &actor, body.relation_id)?; super::gate::relation(&state, &actor, body.relation_id)?;
let relation = body.relation_id.to_string(); let relation = body.relation_id.to_string();
if let Some(snapshot) = body.snapshot_id { // What to restore: a snapshot the person picked, the safety copy that undoes an earlier restore, or (neither)
// a fresh capture.
let mut chosen: Option<(Uuid, Option<String>)> = None;
if let Some(of) = body.undo_of {
if body.snapshot_id.is_some() {
return Err(StatusCode::BAD_REQUEST);
}
let candidate = state
.db
.undo_candidate(&of.to_string(), &relation)
.map_err(internal)?;
let Ok(safety) = candidate else {
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
};
// the copy may have been removed since
if !snapshot_fits(&state, &relation, safety).await? {
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
}
chosen = Some((safety, Some(of.to_string())));
} 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(
StatusCode::UNPROCESSABLE_ENTITY, StatusCode::UNPROCESSABLE_ENTITY,
"snapshot_unusable", "snapshot_unusable",
)); ));
} }
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 {
@@ -214,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,
body.snapshot_id, 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(),
@@ -223,7 +362,11 @@ async fn start(
match started { match started {
Ok((run, created)) => { Ok((run, created)) => {
if created { if created {
crate::refresh::audit_run(&state, &run.id, "capturing"); crate::refresh::audit_run(
&state,
&run.id,
if run.is_undo() { "undo" } else { "capturing" },
);
} }
let status = if created { let status = if created {
StatusCode::ACCEPTED StatusCode::ACCEPTED
@@ -233,10 +376,13 @@ async fn start(
Ok(( Ok((
status, status,
no_store(), no_store(),
Json(view(&state, &run, actor.subject.admin)?), 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,
@@ -283,10 +429,11 @@ async fn list(
} }
} }
.map_err(internal)?; .map_err(internal)?;
let views = runs let undo = undo_views(&state, &runs).await?;
.iter() let mut views = Vec::with_capacity(runs.len());
.map(|run| view(&state, run, actor.subject.admin)) for run in &runs {
.collect::<Result<Vec<_>, _>>()?; views.push(view(&state, run, actor.subject.admin, undo.get(&run.id))?);
}
Ok((no_store(), Json(views))) Ok((no_store(), Json(views)))
} }
@@ -318,7 +465,10 @@ async fn show(
) )
.map_err(internal)?; .map_err(internal)?;
let run = run.ok_or(StatusCode::NOT_FOUND)?; let run = run.ok_or(StatusCode::NOT_FOUND)?;
Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?))) Ok((
no_store(),
Json(view_one(&state, &run, actor.subject.admin).await?),
))
} }
async fn cancel( async fn cancel(
@@ -364,7 +514,11 @@ async fn cancel(
{ {
Ok(run) => { Ok(run) => {
crate::refresh::audit_run(&state, &run.id, "cancelled"); crate::refresh::audit_run(&state, &run.id, "cancelled");
Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?)).into_response()) Ok((
no_store(),
Json(view_one(&state, &run, actor.subject.admin).await?),
)
.into_response())
} }
Err(CancelError::Unknown) => Err(StatusCode::NOT_FOUND), Err(CancelError::Unknown) => Err(StatusCode::NOT_FOUND),
Err(CancelError::TooLate) => Ok(reason(StatusCode::CONFLICT, "too_late")), Err(CancelError::TooLate) => Ok(reason(StatusCode::CONFLICT, "too_late")),

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());
@@ -1753,21 +1753,21 @@ async fn an_administrator_can_rename_a_target_and_everything_that_points_at_it_k
&admin, &admin,
"PUT", "PUT",
&uri, &uri,
Some(json!({"name": "presensi · dev · app_dev"})), Some(json!({"name": "billing · dev · app_dev"})),
) )
.await; .await;
assert_eq!(status, StatusCode::NO_CONTENT); assert_eq!(status, StatusCode::NO_CONTENT);
let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await; let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await;
let target = &overview["targets"][0]; let target = &overview["targets"][0];
assert_eq!(target["name"], "presensi · dev · app_dev"); assert_eq!(target["name"], "billing · dev · app_dev");
assert_eq!(target["id"], lab.target.to_string()); assert_eq!(target["id"], lab.target.to_string());
assert_eq!( assert_eq!(
target["identity"]["database"], "staging_app", target["identity"]["database"], "staging_app",
"identity is untouched" "identity is untouched"
); );
let relation = &overview["relations"][0]; let relation = &overview["relations"][0];
assert_eq!(relation["target_name"], "presensi · dev · app_dev"); assert_eq!(relation["target_name"], "billing · dev · app_dev");
assert_eq!( assert_eq!(
relation["id"], lab.relation, relation["id"], lab.relation,
"the relation is the same relation" "the relation is the same relation"
@@ -1777,9 +1777,9 @@ async fn an_administrator_can_rename_a_target_and_everything_that_points_at_it_k
let (_, mine) = lab let (_, mine) = lab
.send(&qa, "GET", "/api/v1/refresh-relations", None) .send(&qa, "GET", "/api/v1/refresh-relations", None)
.await; .await;
assert_eq!(mine[0]["target_name"], "presensi · dev · app_dev"); assert_eq!(mine[0]["target_name"], "billing · dev · app_dev");
let confirmation = format!( let confirmation = format!(
"REFRESH prod-db TO presensi · dev · app_dev v{}", "REFRESH prod-db TO billing · dev · app_dev v{}",
lab.relation_version lab.relation_version
); );
let (status, body) = lab let (status, body) = lab
@@ -1884,7 +1884,7 @@ async fn renaming_an_orbit_renames_its_old_snapshots_everywhere_they_are_shown()
let uri = format!("/api/v1/orbits/{}", lab.orbit); let uri = format!("/api/v1/orbits/{}", lab.orbit);
assert_eq!( assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": " broiler "}))) lab.send(&admin, "PUT", &uri, Some(json!({"name": " warehouse "})))
.await .await
.0, .0,
StatusCode::NO_CONTENT StatusCode::NO_CONTENT
@@ -1892,21 +1892,21 @@ async fn renaming_an_orbit_renames_its_old_snapshots_everywhere_they_are_shown()
// the snapshot was written under the old name; it is shown under the current one // the snapshot was written under the old name; it is shown under the current one
let (_, listed) = lab.send(&admin, "GET", "/api/v1/snapshots", None).await; let (_, listed) = lab.send(&admin, "GET", "/api/v1/snapshots", None).await;
assert_eq!(listed[0]["orbit_name"], "broiler", "{listed}"); assert_eq!(listed[0]["orbit_name"], "warehouse", "{listed}");
assert!(lab assert!(lab
.download_disposition(snapshot) .download_disposition(snapshot)
.await .await
.contains("filename=\"broiler_")); .contains("filename=\"warehouse_"));
let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await; let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await;
assert!(overview["orbits"] assert!(overview["orbits"]
.as_array() .as_array()
.unwrap() .unwrap()
.iter() .iter()
.any(|o| o["name"] == "broiler")); .any(|o| o["name"] == "warehouse"));
let (_, mine) = lab let (_, mine) = lab
.send(&qa, "GET", "/api/v1/refresh-relations", None) .send(&qa, "GET", "/api/v1/refresh-relations", None)
.await; .await;
assert_eq!(mine[0]["source_name"], "broiler"); assert_eq!(mine[0]["source_name"], "warehouse");
// nothing but the name moved: the relation, its confirmation text and the id are the same relation // nothing but the name moved: the relation, its confirmation text and the id are the same relation
assert_eq!(overview["relations"][0]["id"], lab.relation); assert_eq!(overview["relations"][0]["id"], lab.relation);
assert!( assert!(
@@ -2188,3 +2188,375 @@ async fn the_screens_get_what_they_need_to_offer_restore_for_an_orbit() {
"{kinds:?}" "{kinds:?}"
); );
} }
// ---- undoing a restore: put the target back from the safety copy the restore took ----
impl Lab {
async fn start_undo(&self, caller: &Caller, key: &str, run: &str) -> (StatusCode, Value) {
self.send(
caller,
"POST",
"/api/v1/refresh-runs",
Some(json!({"relation_id": self.relation, "confirmation": self.confirmation(), "idempotency_key": key, "undo_of": run})),
)
.await
}
/// A completed restore of a fresh capture, with its safety copy in the vault.
async fn restored_once(&self, key: &str) -> 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;
self.finish_restore().await;
assert_eq!(self.run(&run).status, "completed");
run
}
}
#[tokio::test]
async fn a_completed_restore_can_be_undone_from_its_safety_copy_and_the_undo_can_be_undone() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa");
let first = lab.restored_once("first").await;
let (_, view) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
.await;
assert_eq!(view["undo_available"], true, "{view}");
assert!(
view.get("safety_snapshot_id").is_none(),
"no snapshot id reaches a non-administrator: {view}"
);
let (status, undo) = lab.start_undo(&qa, "undo-1", &first).await;
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
assert_eq!(undo["undo"], true);
let undo_id = undo["id"].as_str().unwrap().to_string();
let captures = lab.capture_jobs();
lab.tick().await;
// the restore job takes the first restore's safety copy back onto the same target
let (job, _) = lab
.restore_until_ready()
.await
.expect("an undo job is waiting");
let artifact: Value = serde_json::from_str(&lab.scalar::<String>(&format!(
"SELECT artifact FROM restore_jobs WHERE id='{job}'"
)))
.unwrap();
assert_eq!(artifact["rollback"], true, "{artifact}");
assert_eq!(lab.capture_jobs(), captures, "an undo captures nothing");
let (_, token) = (
job.clone(),
lab.scalar::<String>(&format!(
"SELECT lease_token FROM restore_jobs WHERE id='{job}'"
)),
);
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
lab.report_applied(&job, &token).await;
lab.tick().await;
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
let (_, old) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
.await;
let (_, new) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{undo_id}"), None)
.await;
assert_eq!(
(old["undo_available"].clone(), new["undo_available"].clone()),
(json!(false), json!(true))
);
assert!(lab
.audit_log()
.iter()
.any(|(event, _)| event == "restore.queued"));
}
#[tokio::test]
async fn an_undo_is_refused_when_there_is_nothing_sound_to_go_back_to() {
let lab = fresh().await;
let admin = lab.admin();
// a run that has not finished, and one that does not exist
let (_, running) = lab.start(&admin, "running").await;
let running = running["id"].as_str().unwrap().to_string();
for (what, id) in [
("unfinished", running.clone()),
("unknown", Uuid::new_v4().to_string()),
] {
let (status, body) = lab.start_undo(&admin, &format!("u-{what}"), &id).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{what}: {body}");
assert_eq!(body["reason"], "nothing_to_undo", "{what}");
}
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
lab.finish_restore().await;
// the safety copy has been removed from the vault
let safety = lab.scalar::<String>("SELECT safety_id FROM restore_jobs LIMIT 1");
lab.state
.vault
.write()
.await
.forget(&[Uuid::parse_str(&safety).unwrap()])
.unwrap();
let (status, body) = lab.start_undo(&admin, "gone", &running).await;
assert_eq!(
(status, body["reason"].clone()),
(StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")),
"{body}"
);
assert_eq!(
lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"),
1,
"nothing was started"
);
}
#[tokio::test]
async fn a_safety_copy_is_only_ever_restored_onto_the_target_it_came_from() {
let lab = fresh().await;
let admin = lab.admin();
let first = lab.restored_once("first").await;
let own_safety =
Uuid::parse_str(&lab.scalar::<String>("SELECT safety_id FROM restore_jobs LIMIT 1"))
.unwrap();
let hints = lab
.state
.vault
.read()
.await
.get_snapshot(own_safety)
.unwrap()
.unwrap()
.manifest
.restore_hints;
// the same kind of copy, but taken from some other target
let mut foreign_hints = hints.clone();
foreign_hints["target_id"] = json!(Uuid::new_v4());
let foreign = lab
.plant_snapshot(lab.orbit, &["restore-safety"], foreign_hints)
.await;
let (status, body) = lab.start_snapshot(&admin, "foreign", foreign).await;
assert_eq!(
(status, body["reason"].clone()),
(StatusCode::UNPROCESSABLE_ENTITY, json!("snapshot_unusable")),
"{body}"
);
// its own copy is fine, through the plain snapshot route as well
let (status, body) = lab.start_snapshot(&admin, "own", own_safety).await;
assert_eq!(status, StatusCode::ACCEPTED, "{body}");
let _ = first;
}
#[tokio::test]
async fn only_someone_who_may_use_the_relation_can_undo_through_it() {
let lab = fresh().await;
let first = lab.restored_once("first").await;
let stranger = lab.person("stranger");
let status = lab.start_undo(&stranger, "s", &first).await.0;
assert!(
status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND,
"{status}"
);
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

@@ -234,10 +234,42 @@ pub(crate) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArti
format, format,
identity, identity,
sha256, sha256,
rollback: false,
}, },
)) ))
} }
/// The artifact for putting a target back from the safety copy a restore took of it, or `None` when the
/// snapshot is not such a copy, was taken from some other target, or lacks what a restore needs. The copy is a
/// dump of the target itself, so its source identity is the target's own.
pub(crate) fn rollback_artifact(
manifest: &SnapshotManifest,
target: &tessera_core::restore::RestoreTarget,
) -> Option<RestoreArtifact> {
if !manifest.is_restore_safety() || manifest.safety_target()? != target.id.to_string() {
return None;
}
let format = match (
manifest.provider.as_str(),
manifest.restore_hints.get("format")?.as_str()?,
) {
("postgres", "custom") => CaptureFormat::PostgresCustom,
("postgres", "plain") => CaptureFormat::PostgresSql,
("mysql", "plain") => CaptureFormat::MysqlSql,
_ => return None,
};
let sha256 = manifest.restore_hints.get("sha256")?.as_str()?.to_owned();
if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
(format.engine() == Some(target.engine)).then(|| RestoreArtifact {
format,
identity: target.identity.clone(),
sha256,
rollback: true,
})
}
async fn job( async fn job(
ConnectInfo(peer): ConnectInfo<SocketAddr>, ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
@@ -338,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())
@@ -349,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((
@@ -361,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())
@@ -403,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.
@@ -430,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())
@@ -506,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,14 +79,154 @@ 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.
/// `capture_job_id` of a run that restores a snapshot somebody picked instead of capturing a new one. /// `capture_job_id` of a run that restores a snapshot somebody picked instead of capturing a new one.
const EXISTING: &str = "existing:"; const EXISTING: &str = "existing:";
/// Same, for a run that puts a target back from the safety copy of an earlier restore.
const UNDO: &str = "undo:";
/// Does this run take its snapshot from the request instead of from a capture of its own?
fn picked_snapshot(run: &RefreshRun) -> bool {
run.capture_job_id.starts_with(EXISTING) || run.capture_job_id.starts_with(UNDO)
}
impl RefreshRun {
/// This run put a target back from a safety copy.
pub fn is_undo(&self) -> bool {
self.capture_job_id.starts_with(UNDO)
}
}
/// 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.
#[derive(Debug, PartialEq, Eq)]
pub enum UndoRefusal {
/// No such run, not of this relation, not a restore that can be put back, or it took no safety copy.
NothingToUndo,
/// Something else was restored onto the target after it. Undoing an older restore would also undo that.
NotTheLatest,
}
/// A relation's source orbit, for checking that a snapshot belongs to it.
impl Db { impl Db {
/// The safety copy that undoes `run`, if the run is a restore of this relation that can be put back and the
/// newest restore of its target. Whether the copy still exists in the vault is for the caller to check.
pub fn undo_candidate(
&self,
run: &str,
relation: &str,
) -> 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 mut infos = std::collections::HashMap::new();
for run in runs {
if let Some(info) = undo_info(&conn, run)? {
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 conn = self.conn.lock().unwrap();
Ok(conn
.query_row(
"SELECT r.id FROM refresh_runs r JOIN restore_jobs j ON j.id = r.restore_job_id
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),
)
.optional()?)
}
pub fn relation_target(&self, relation: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(relation_of(&conn, relation)?.map(|r| r.target_id))
}
pub fn relation_source_orbit(&self, relation: &str) -> Result<Option<String>> { pub fn relation_source_orbit(&self, relation: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
Ok(relation_of(&conn, relation)?.map(|r| r.source_orbit_id)) Ok(relation_of(&conn, relation)?.map(|r| r.source_orbit_id))
@@ -282,7 +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,
snapshot: Option<Uuid>, // a snapshot to restore instead of capturing one, and the run it undoes when it is the safety copy of one
snapshot: Option<(Uuid, Option<&str>)>,
ttl_secs: i64, ttl_secs: i64,
max_active: i64, max_active: i64,
now: i64, now: i64,
@@ -310,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)));
@@ -320,11 +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(_) => format!("{EXISTING}{id}"), Some((_, Some(_))) => format!("{UNDO}{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) =
@@ -340,7 +506,7 @@ impl Db {
authorized_by,idempotency_key,status,capture_job_id,snapshot_id,created_at,updated_at,expires_at) authorized_by,idempotency_key,status,capture_job_id,snapshot_id,created_at,updated_at,expires_at)
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?13,?13,?14)", VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?13,?13,?14)",
params![id, relation.id, relation.version, relation.source_orbit_id, relation.source_application_id, relation.target_id, params![id, relation.id, relation.version, relation.source_orbit_id, relation.source_application_id, relation.target_id,
requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|s| s.to_string()), now, now + ttl_secs], requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|(s, _)| s.to_string()), now, now + ttl_secs],
)?; )?;
Ok(Ok((get(&tx, &id)?.expect("just inserted"), true))) Ok(Ok((get(&tx, &id)?.expect("just inserted"), true)))
})()?; })()?;
@@ -446,7 +612,7 @@ impl Db {
if run.status != "capturing" || run.restore_job_id.is_some() { if run.status != "capturing" || run.restore_job_id.is_some() {
return Ok(Linked::NotReady); return Ok(Linked::NotReady);
} }
let snapshot = if run.capture_job_id.starts_with(EXISTING) { let snapshot = if picked_snapshot(&run) {
let Some(snapshot) = run.snapshot_id.clone() else { let Some(snapshot) = run.snapshot_id.clone() else {
return Ok(Linked::NotReady); return Ok(Linked::NotReady);
}; };
@@ -613,7 +779,7 @@ fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result<Sync> {
Ok(Sync::Moved(status.into())) Ok(Sync::Moved(status.into()))
}; };
match run.status.as_str() { match run.status.as_str() {
"capturing" if run.capture_job_id.starts_with(EXISTING) => { "capturing" if picked_snapshot(&run) => {
// Nothing to capture: the snapshot was chosen when the run was started. // Nothing to capture: the snapshot was chosen when the run was started.
match (&run.snapshot_id, &run.restore_job_id) { match (&run.snapshot_id, &run.restore_job_id) {
(Some(snapshot), None) => Ok(Sync::NeedRestore(snapshot.clone())), (Some(snapshot), None) => Ok(Sync::NeedRestore(snapshot.clone())),

View File

@@ -76,7 +76,7 @@ pub(crate) fn restore_target_mismatch(
) -> Option<&'static str> { ) -> Option<&'static str> {
if Some(target.engine) != artifact.format.engine() { if Some(target.engine) != artifact.format.engine() {
Some("Database engine differs from the snapshot") Some("Database engine differs from the snapshot")
} else if target.identity == artifact.identity { } else if target.identity == artifact.identity && !artifact.rollback {
Some("Target is the source database") Some("Target is the source database")
} else { } else {
None None
@@ -562,6 +562,7 @@ mod tests {
let artifact = RestoreArtifact { let artifact = RestoreArtifact {
format: CaptureFormat::PostgresCustom, format: CaptureFormat::PostgresCustom,
sha256: "0".repeat(64), sha256: "0".repeat(64),
rollback: false,
identity: DatabaseIdentity { identity: DatabaseIdentity {
instance: "123".into(), instance: "123".into(),
database: "source".into(), database: "source".into(),

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,16 +368,16 @@ 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("boiler", taken(), None, Some("mysql"), id(), "sql.gz"); let name = download_name("ledger", taken(), None, Some("mysql"), id(), "sql.gz");
assert_eq!(name, "boiler_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
assert_eq!( assert_eq!(
download_name("docs", taken(), None, None, id(), "tar.gz"), download_name("docs", taken(), None, None, id(), "tar.gz"),
@@ -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

@@ -47,6 +47,7 @@ fn now() -> i64 {
pub fn audit_name(status: &str) -> (&'static str, AuditOutcome) { pub fn audit_name(status: &str) -> (&'static str, AuditOutcome) {
match status { match status {
"capturing" => ("refresh.started", AuditOutcome::Succeeded), "capturing" => ("refresh.started", AuditOutcome::Succeeded),
"undo" => ("refresh.undo_started", AuditOutcome::Succeeded),
"restoring" => ("refresh.restore_queued", AuditOutcome::Succeeded), "restoring" => ("refresh.restore_queued", AuditOutcome::Succeeded),
"completed" => ("refresh.completed", AuditOutcome::Succeeded), "completed" => ("refresh.completed", AuditOutcome::Succeeded),
"reconciled" => ("refresh.reconciled", AuditOutcome::Succeeded), "reconciled" => ("refresh.reconciled", AuditOutcome::Succeeded),
@@ -104,10 +105,18 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
.await .await
.get_snapshot(snapshot_id)? .get_snapshot(snapshot_id)?
.map(|s| s.manifest); .map(|s| s.manifest);
let artifact = manifest let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
// A safety copy is restorable only onto the target it was taken from (an undo); anything else must be a
// capture with its source identity.
let artifact = manifest.as_ref().and_then(|manifest| {
if manifest.is_restore_safety() {
target
.as_ref() .as_ref()
.and_then(crate::api::artifact) .and_then(|target| crate::api::rollback_artifact(manifest, target))
.map(|(_, artifact)| artifact); } else {
crate::api::artifact(manifest).map(|(_, artifact)| artifact)
}
});
let Some(artifact) = artifact else { let Some(artifact) = artifact else {
// The snapshot is missing or lacks what a restore needs (format, checksum, source identity). // The snapshot is missing or lacks what a restore needs (format, checksum, source identity).
state state
@@ -117,9 +126,9 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
return Ok(true); return Ok(true);
}; };
// The driver looks again: a run that was told to restore a snapshot only restores one of its own source. // The driver looks again: a run that was told to restore a snapshot only restores one of its own source.
let belongs = manifest.as_ref().is_some_and(|manifest| { let belongs = manifest
manifest.orbit_id.to_string() == run.source_orbit_id && !manifest.is_restore_safety() .as_ref()
}); .is_some_and(|manifest| manifest.orbit_id.to_string() == run.source_orbit_id);
if !belongs { if !belongs {
state state
.db .db
@@ -127,7 +136,6 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
audit_run(state, &run.id, "blocked"); audit_run(state, &run.id, "blocked");
return Ok(true); return Ok(true);
} }
let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
let clash = match target { let clash = match target {
Some(target) => { Some(target) => {
let source = Uuid::parse_str(&run.source_orbit_id)?; let source = Uuid::parse_str(&run.source_orbit_id)?;

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,12 +379,31 @@ 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 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
undone. A restore that completed, one an administrator reconciled, and one whose apply failed (the agent reported it) can
be undone; for the last, undoing is the recovery: the failed apply stops fencing the target in the same transaction
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
`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.
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
latest data (or click a snapshot that is already there), and in the snapshot detail press **Restore**. The button is latest data (or click a snapshot that is already there), and in the snapshot detail press **Restore**. The button is
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. Safety copies are not listed with the 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
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

@@ -1,50 +0,0 @@
# Paritas Backup & Restore Center MBU
Inventaris 10 November 2026. Targetnya adalah Tessera dapat mengambil alih backup dan restore database di backup.mbugroup.id, termasuk pemulihan dari arsip lama. Uji awal memakai topologi yang ditemukan di deployment dan data sintetis di lingkungan terisolasi.
## Deployment yang diperiksa
- Teleport `mbu-backup-jumphost` memiliki IP publik yang cocok dengan DNS situs. Nginx meneruskan trafik ke port lokal 8088. Docker Compose menjalankan container `backup-restore-center` dari `/opt/apps-backup`, dengan source dan data dipasang dari host.
- Situs mengarahkan pengguna ke login. Source yang terpasang menunjukkan sesi browser, dashboard per aplikasi, riwayat dengan filter aplikasi dan status, pembaruan otomatis selama job aktif, log job, serta audit login dan tindakan.
- Cron host mengantrekan backup semua aplikasi pada 19.00 UTC atau 02.00 WIB hari berikutnya. Worker menjalankan antrean FIFO per aplikasi dan memulihkan status job yang tertinggal saat restart. Batas satu perintah adalah 1.800 detik.
- Inventaris S3 berisi 228 objek `.sql.gz` dengan total 7.486.456.004 byte. Dump terbesar sekitar 66 MB. Konfigurasi aktif menghapus dump yang lebih tua dari 14 hari dan mempertahankan minimal satu per aplikasi. Lima backup adalah fallback berbasis jumlah. Dashboard mendukung unduh lewat URL bertanda tangan dan hapus per backup. File staging lokal dibersihkan setelah job.
- Snapshot read-only SQLite berisi 968 baris job, termasuk backup dan restore gagal. Tiga timer retensi systemd pada host menunjuk ke direktori set terpisah di bawah `/var/lib`. Inventaris 228 objek mencakup katalog aplikasi web.
## Kasus penerimaan dari deployment
| Kasus | Aplikasi | Yang harus dibuktikan |
| --- | --- | --- |
| PostgreSQL langsung | `lti`, `presensi`, `sso`, `helpdesk`, `manbu` | Capture dengan TLS, restore ke target terdaftar, verifikasi skema dan isi. Sertakan target bernama `manbu_development`. |
| PostgreSQL dengan penyesuaian restore | `daily_checklist` | Reset schema, jalankan SQL pascarestore, serta bedakan error kompatibilitas yang ditoleransi dari kegagalan yang harus terlihat. |
| PostgreSQL lewat bastion | `odoo_mas`, `odoo_fta` | Gunakan host key yang dipin. Uji reset berupa pembuatan ulang database pada target sementara untuk MAS. FTA harus bisa capture dengan target restore kosong. |
| MySQL lewat SSH | `boiler` | Gunakan fixture MySQL dengan routine, event, view, dan DEFINER. Verifikasi dump konsisten, kompatibilitas restore, dan rollback dengan backup pengaman pada target seperti staging. |
| Backup tanpa target | `dashboard_management`, `odoo_fta` | Backup manual dan terjadwal tetap tersedia. Permintaan restore ke database ditolak sampai ada target terdaftar. |
| Arsip lama | Kesepuluh aplikasi | Rekonsiliasi per aplikasi, waktu, ukuran, format, dan identitas objek. Uji migrasi ulang tanpa duplikasi serta restore sampel dari PostgreSQL dan MySQL. |
Untuk restore database, operator memilih snapshot dan target, lalu mengetik konfirmasi. Backup pengaman target harus selesai dan tersimpan sebelum perubahan pertama. Uji target salah, sumber produksi sebagai target, kegagalan backup pengaman, kegagalan di tengah restore, dan pemulihan dari backup pengaman. PostgreSQL lama menggunakan SQL polos terkompresi tanpa owner dan ACL. Restore lama memiliki penanganan kompatibilitas untuk `transaction_timeout` dan `pg_stat_statements`.
## Peta kapabilitas untuk ditinjau
| Modul | Tanggung jawab dan selisih Tessera | Bergantung pada |
| --- | --- | --- |
| `operator-access` | Sesi browser dan audit operator. Tessera punya token admin untuk API. Canvas belum dapat beroperasi dengan token itu. Uji juga membuktikan respons daftar orbit mengandung kredensial provider. | — |
| `database-capture` | Profil aplikasi dengan secret reference, PostgreSQL langsung atau melalui bastion, dan MySQL lewat SSH. Tessera sudah dapat dump PostgreSQL langsung, tetapi parser membuang parameter query URL seperti `sslmode`. | — |
| `backup-catalog` | Penyimpanan off-host S3, metadata, daftar, unduh, hapus, dan retensi 14 hari atau fallback jumlah. Tessera sudah memakai Restic lokal serta retensi GFS. | — |
| `database-recovery` | Target yang diizinkan, konfirmasi, backup pengaman, restore database, dan SQL pascarestore. Reconstitute saat ini mengekspor payload ke path di hub. | `database-capture`, `backup-catalog` |
| `job-operations` | Jadwal WIB, antrean persisten per aplikasi, batas waktu, status dan log per fase, serta pemulihan setelah restart. Tessera sudah memiliki orbit manual dan cron UTC. Jadwal sekarang menunggu capture satu per satu dalam satu tick dan mengecek waktu eksekusi berikutnya tanpa catatan eksekusi per slot. | `operator-access`, `database-capture`, `backup-catalog`, `database-recovery` |
| `legacy-transition` | Impor atau akses arsip lama, rekonsiliasi riwayat operasional, uji paralel dan peralihan. | `backup-catalog`, `database-recovery`, `job-operations` |
Urutan usulan dimulai dengan akses operator dan kontrak rahasia, lalu capture dan katalog, restore database, operasi job, dan transisi. Fitur Tessera yang melampaui layanan lama dan masuk uji regresi mencakup enkripsi dan deduplikasi Restic, retensi GFS, serta capture filesystem dan outpost Wormhole.
## Bukti uji awal
- PostgreSQL 14 sementara dengan data sintetis berhasil melewati pembuatan orbit, capture manual, penyegelan Restic, ekspor lewat Reconstitute, dan `pg_restore` manual ke database kedua. Isi baris diverifikasi di target. Ini menguji jalur ekspor yang ada.
- API tanpa autentikasi pada hub bertoken mengembalikan 401. Daftar orbit dengan token mengembalikan URL koneksi yang mengandung password sintetis.
- Rust workspace lulus 22 tes dan tes Restic yang biasanya diabaikan juga lulus ketika dijalankan terpisah. Sepuluh tes web, typecheck, dan build lulus.
- Pemeriksaan produksi membaca source, metadata agregat job, dan inventaris objek. Validasi koneksi dan restore terhadap data produksi, uji paralel, serta peralihan belum dijalankan.
## Implementasi dan bukti fixture
Lihat [panduan capture database](DATABASE-CAPTURE.md) dan [matriks fixture](../tests/mbu/README.md). Jalur lokal mencakup PostgreSQL langsung dan lewat bastion, MySQL langsung dan lewat SSH, antrean per aplikasi, jadwal zona waktu, histori fase, katalog Restic, dan salinan S3. Fixture juga mencakup restore PostgreSQL/MySQL ke target terdaftar, verifikasi safety backup, rekonsiliasi gangguan, serta impor arsip SQL dan histori SQLite. [Runbook peralihan](MBU-CUTOVER.md) memisahkan bukti fixture dari penerimaan staging MBU.
Inventaris Teleport bisa dibaca lewat Machine ID. Verifikasi placement dan versi pada host produksi menunggu akun OS yang diizinkan pada node terkait. Angka inventaris arsip lama di atas tetap merupakan hasil pemeriksaan awal.

View File

@@ -1,56 +0,0 @@
# Runbook peralihan Tessera MBU
Status per 10 November 2026. Rehearsal lokal memakai data sintetis dan endpoint loopback. Akses staging MBU, sampel arsip lama, dan window produksi memerlukan persetujuan operator.
## Siapkan staging
1. Konfirmasi node dan akun OS yang disetujui untuk MAS, FTA, dan Boiler. Catat versi server dan client, jalur direct atau SSH, host key, dan hak backup/restore. Letakkan secret di agent atau host SSH yang menjalankan client.
2. Sediakan data dir Tessera, operator HTTPS, kredensial API terpisah, dan prefix Restic S3 staging. Gunakan akses baca pada bucket arsip lama. Catat pemilik tiga timer retensi host dan integrasi di luar dashboard lama.
3. Daftarkan sepuluh aplikasi dengan UUID stabil, jadwal 02.00 WIB, dan target uji yang disetujui. Pakai [peta paritas](MBU-BACKUP-PARITY.md). FTA dan Dashboard Management cukup menjalankan capture.
4. Jalankan [fixture lokal](../tests/mbu/README.md), lalu ulangi manual dan jadwal per aplikasi pada staging. Catat ID job, waktu slot, usia snapshot terbaru, durasi, ukuran, hasil checksum dan pemulihan, ID safety backup, serta status salinan S3.
## Rekonsiliasi arsip
1. Jalankan `tessera legacy-import --inventory-only` per prefix. Bandingkan key, ETag, waktu sumber, ukuran, dan total dengan inventaris lama. Simpan laporan JSON bersama bukti staging.
2. Impor ke vault staging dan ulangi untuk memeriksa idempotensi. Pulihkan sampel PostgreSQL dan MySQL yang disetujui ke target sementara. Impor salinan SQLite lama yang konsisten dan simpan ID arsip histori untuk `tessera legacy-history`.
3. Bandingkan delta objek setelah uji paralel. Ulangi inventaris dan impor sebelum peralihan. Simpan jumlah, byte, dan daftar selisih per aplikasi.
## Simulasikan rollback
1. Jalankan restore ke target sementara. Putuskan agent setelah reset pada kasus recreate. Restart hub, tunggu lease berakhir, dan pastikan status `recovery_required` menahan target dan kedua snapshot.
2. Hentikan proses apply sebelumnya dan verifikasi sesi database sudah berhenti. Unduh safety backup dari job. Pulihkan ke target sementara yang sama dengan client engine, verifikasi schema, isi, dan izin, lalu masukkan konfirmasi `RECONCILE <job-id>`. Catat hasil verifikasi dan audit.
3. Simulasikan repo primer tidak tersedia. Pulihkan arsip dari prefix S3 memakai UUID snapshot. Bandingkan checksum dan isi database dengan baseline. Catat apakah salinan dan password recovery tersedia dari host lain.
4. Uji peralihan trafik di staging. Kembalikan routing ke layanan lama dan pastikan operator dapat menjalankan backup serta membuka histori. Cocokkan jadwal dan integrasi eksternal setelah rollback.
## Keputusan operator
Penuhi bukti per aplikasi sebelum operator menyetujui perubahan domain. Catat window, pemilik keputusan, target yang diuji, periode paralel, batas freshness dan durasi, serta perubahan Nginx atau DNS yang dibutuhkan. Tahan peralihan bila ada arsip yang belum terekonsiliasi, salinan S3 tidak dapat dipulihkan, jadwal terlewat, restore menghasilkan isi berbeda, atau target masih terkunci.
Pada window yang disetujui, ambil inventaris delta terakhir, verifikasi backup terbaru tiap aplikasi, lalu alihkan trafik. Cek sign-in, histori, backup manual, dan download. Pantau siklus 02.00 WIB. Pertahankan layanan dan artefak lama selama periode rollback yang disepakati.
Jika kriteria rollback tercapai, kembalikan routing, aktifkan jadwal lama sesuai keputusan operator, dan catat job atau objek Tessera sejak peralihan untuk rekonsiliasi. Tunda restore pada target yang statusnya belum diketahui sampai safety backup dan hasil verifikasi tersedia.
## Hasil rehearsal lokal
Ketiga outpost memproses 10 backup manual dan 10 backup dari scheduler. Semua 20 snapshot tersalin ke S3 fixture. Delapan target dipulihkan dan diperiksa isinya. Dua aplikasi capture-only tetap dapat backup. Download arsip LTI berhasil setelah repo primer dipindahkan sementara.
| Aplikasi | Manual (detik) | Terjadwal (detik) | Freshness (detik) | Ukuran (byte) | Restore |
| --- | ---: | ---: | ---: | ---: | --- |
| lti | 3 | 5 | 39 | 1391 | Lulus |
| presensi | 3 | 5 | 39 | 1416 | Lulus |
| sso | 4 | 5 | 39 | 1391 | Lulus |
| helpdesk | 3 | 5 | 39 | 1416 | Lulus |
| manbu | 4 | 6 | 38 | 1401 | Lulus |
| daily_checklist | 2 | 10 | 34 | 1071 | Lulus |
| odoo_mas | 3 | 6 | 38 | 1416 | Lulus |
| odoo_fta | 2 | 6 | 38 | 1416 | Capture-only |
| dashboard_management | 2 | 5 | 39 | 1476 | Capture-only |
| boiler | 3 | 6 | 38 | 3132 | Lulus |
Freshness diukur setelah semua salinan selesai. Fixture PostgreSQL terpisah menguji putus agent setelah reset, restart hub, penolakan permit lama, pemulihan safety dump, dan audit rekonsiliasi.
## Bukti yang menunggu staging MBU
- Akun OS yang disetujui, versi client/server, dan jalur sebenarnya pada MAS, FTA, dan Boiler.
- Rekonsiliasi arsip asli serta restore sampel yang telah disetujui.
- Metrik uji paralel, kepemilikan integrasi eksternal, drill routing, dan persetujuan operator untuk window produksi.

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; `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,17 +1,93 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Build a clean, single-commit tree for the public repository. Nothing is pushed. # Build a clean, single-commit tree of the current HEAD for a fresh public repository. Nothing is pushed.
# Usage: 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,
# 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"
# Deployment-specific and planning material stays in the private repository.
rm -rf "$out/tasks" "$out/tests/mbu" "$out/docs/MBU-BACKUP-PARITY.md" "$out/docs/MBU-CUTOVER.md" "$out/floorplan" "$out/graft" # Local tooling and agent state never belongs in a public tree, even if an old commit tracked it.
if grep -rIlE "mbugroup|backup\.mbu|hafizh|senkensha\.space" "$out" --exclude-dir=node_modules --exclude=export-public.sh >/dev/null; then for path in .serena .claude .cursor .idea .vscode graft floorplan .ignore web/AGENTS.md AGENTS.md CLAUDE.md \
echo "private references remain:" >&2 web/blackhole-proto.html tasks; do
grep -rIlE "mbugroup|backup\.mbu|hafizh|senkensha\.space" "$out" --exclude-dir=node_modules --exclude=export-public.sh >&2 rm -rf "${out:?}/$path"
exit 1 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 "$hits" >&2
fail=1
fi fi
echo "clean tree at $out; review it, then: git init && git add -A && git commit" # 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
echo "warning: --allow-unchecked given, so no check for private terms or personal e-mail addresses was made" >&2
fi
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

@@ -1,212 +0,0 @@
# Rencana implementasi auth, OIDC, RBAC, dan self-service data
Tanggal: 11 November 2026. Status: fondasi A01–A04 diimplementasikan; A00 masih memiliki temuan audit. OIDC, RBAC scoped dan workflow self-service belum tersedia.
Daftar tugas: [auth-self-service-todo.md](auth-self-service-todo.md).
Riset library/tool per task dan keputusan reuse: [auth-self-service-libraries.md](auth-self-service-libraries.md).
Rencana MBU pada plan.md/todo.md dipertahankan; ini perluasan akses dan workflow di atas capture/restore yang sudah tersedia.
## 1. Hasil yang dituju
DevOps mendaftarkan sumber production dan tujuan staging, memverifikasi identitas database, membuat relasi berarah, dan memberi akses kepada akun/grup. QA masuk dengan akun sendiri, memilih relasi yang diizinkan, meminta dump baru, dan memulihkan snapshot hasil job itu ke staging. Developer masuk dengan akun sendiri, memilih orbit yang diizinkan, dan mengunduh snapshot sebagai arsip terkompresi; dapat meminta capture baru jika diberi izin terpisah.
Tidak ada persetujuan DevOps per eksekusi setelah relasi dan grant disiapkan. QA tetap mengonfirmasi tujuan yang akan ditimpa. Hak restore tidak otomatis memberikan hak download, dan hak download tidak otomatis memberikan hak capture.
## 2. Asumsi dan batas awal
- Satu organisasi dan satu hub aktif, SQLite tetap digunakan. Multi-tenant/multi-replica bukan bagian rilis ini.
- Satu issuer OIDC tepercaya per deployment pada rilis awal; login normal melalui SSO. Akun lokal yang ada menjadi admin darurat, bukan akun bersama pengguna harian.
- Kredensial database tetap di agent/config lokal DevOps; pengguna tidak boleh memasukkan host, DSN, perintah SQL, atau path tujuan bebas.
- MVP QA memakai capture profile database managed yang sudah memiliki metadata integritas/identitas dan Outpost. Orbit hub/legacy yang belum restore-ready tetap dapat dilihat/diunduh sesuai grant tetapi tidak ditawarkan sebagai sumber refresh otomatis. UI menyebut alasan dan langkah konversinya.
- Production adalah sumber; target production ditolak oleh workflow self-service meskipun admin memiliki banyak izin. Pemulihan bencana production tetap melalui jalur administrasi terpisah.
- Data asli dapat diizinkan sesuai kebutuhan tim. Tidak menambahkan masking diam-diam; ekspor raw production adalah izin eksplisit dengan pemberitahuan dan audit. Data yang sudah diunduh tidak dapat dicabut dari laptop oleh Tessera.
- Durasi dump, versi PostgreSQL/MySQL, IdP, batas unduhan, dan kebijakan raw-data mengikuti deployment; angka awal di bawah adalah default usulan.
## 3. Peta capability dan urutan
| Modul | Tanggung jawab | Dependensi |
| --- | --- | --- |
| access-foundation | Principal, gate server, audit, isolasi agent/token | — |
| identity | OIDC, sesi individual, akun darurat | access-foundation |
| scoped-access | Grant aksi/resource, role, administrasi akses | identity |
| orbit-relations | Environment, binding target, relasi sumber → tujuan | scoped-access |
| refresh | Capture baru → snapshot spesifik → restore durable | orbit-relations |
| compressed-export | Ekspor terkompresi, kuota, streaming, audit | scoped-access |
| release-verification | Migrasi, regresi, uji IdP dan dua user story | semua |
Urutan: compatibility spike library (A00) → tutup celah akses → identitas → permission → relasi → refresh dan export → rollout. Perbaikan isolasi/fail-closed A01–A03 tidak perlu menunggu spike library yang independen.
Tidak menambah policy engine eksternal, message broker, atau workflow engine; gunakan gate terpusat dan transaksi/job SQLite yang sudah ada.
Temuan aktual A00: baseline sesuai rencana tetapi RustSec tidak bersih (10 vulnerability baseline dan warning unsound Tokio). Spike membuktikan tower-sessions 0.15 dapat dipakai melalui Extension tanpa upgrade Axum. Time/TLS fixture telah diperbaiki; remediation SQLite/Tokio runtime dan triage RSA tetap wajib sebelum dependency auth siap rilis. A05 dapat melanjutkan primitive existing secara independen; A07/A09/A11 tidak boleh menganggap A00 sudah diterima. Bila patched SQLite memerlukan compiler/binding baru, buat slice upgrade tersendiri dengan fixture DB lama. Bukti: `tests/auth-compat/README.md`.
## 4. Model akses
RBAC menentukan kumpulan aksi; grant resource dan relasi menentukan di mana aksi berlaku. Nama QA/developer tidak otomatis memberikan akses seluruh production.
| Aksi | Admin DevOps | QA pada scope grant | Developer pada scope grant |
| --- | --- | --- | --- |
| Lihat orbit/snapshot dan status yang aman | Ya | Ya | Ya |
| Kelola orbit/profile/Outpost/relasi | Ya | Tidak | Tidak |
| Kelola user/group/grant/token | Ya | Tidak | Tidak |
| Minta capture baru | Ya | Bila diberi capture.run | Bila diberi capture.run |
| Refresh staging | Ya, tetap lewat relasi valid | Bila diberi refresh.run pada relasi | Hanya bila diberi grant tersebut |
| Download snapshot raw | Grant eksplisit untuk data sensitif | Default tidak | Bila diberi snapshot.download |
| Ubah retensi/hapus snapshot/reconcile recovery | Ya | Tidak | Tidak |
| Restore production melalui self-service | Tidak | Tidak | Tidak |
Permission awal: orbit.read, snapshot.read, capture.run, refresh.run, snapshot.download, orbit.manage, relation.manage, access.manage, outpost.manage, retention.manage, snapshot.delete, recovery.manage, audit.read. Backend memeriksa permission pada resource aktual; daftar/filter UI hanya membantu pengalaman pengguna.
Principal memuat ID stabil, jenis user/service/outpost, status aktif, dan auth method. Tidak memakai display name/email sebagai identitas unik. Service token mendapatkan grant eksplisit; token agen tidak pernah menjadi token pengguna.
QA dengan refresh.run pada relasi boleh memicu capture sebagai langkah internal workflow itu, tetapi tidak memperoleh endpoint capture bebas atau download payload. Grant snapshot.download pada orbit berlaku pada snapshot orbit tersebut, termasuk snapshot baru; ini dinyatakan jelas di UI admin. Histori workflow dapat dilihat pemilik dan admin; user lain memerlukan grant scope yang sesuai.
Aturan gate: authenticated + active + aksi diizinkan + resource dalam scope + constraint relasi/identitas terpenuhi. Resource di luar scope dikembalikan konsisten sebagai 404; role tidak berhak pada resource yang terlihat mendapat 403. Semua endpoint lama, endpoint agent, ekspor, dan akses langsung lewat UUID harus tercantum dalam matriks otorisasi.
## 5. Identitas OIDC dan sesi
- Hub menjadi confidential OIDC client; Authorization Code + PKCE S256. Secret dan token IdP hanya di backend.
- Discovery dari issuer terkonfigurasi HTTPS; exact issuer matching, client authentication sesuai metadata/provider yang didukung, redirect URI publik statis. Jangan membentuk callback dari Host/X-Forwarded-* yang tidak tepercaya.
- Validasi state, nonce, PKCE, signature/alg allowlist, iss, aud, azp bila relevan, exp/iat dan clock skew terbatas. Transaksi login singkat, sekali pakai, dan diikat ke browser; JWKS cache bounded dengan refresh terkendali untuk kid baru, tanpa menerima token yang gagal verifikasi.
- Identitas unik (issuer, subject). Email/display name hanya atribut. Tidak auto-link akun berdasarkan email dan tidak auto-admin bagi user pertama yang masuk.
- User baru tanpa grant mendapat halaman belum memiliki akses. Bootstrap admin memakai konfigurasi subject eksplisit/operasi lokal yang diaudit, bukan role dari parameter callback.
- Grup OIDC dipetakan lewat konfigurasi claim yang diizinkan, dengan mapping eksplisit. Direct user grants tersedia. Claim grup hilang/terpotong tidak memperluas hak; jelaskan cara sinkronisasi per IdP.
- Sesi opaque server-side, simpan digest ID sesi di SQLite, cookie __Host-/HttpOnly/Secure. Absolute timeout 8 jam dan idle timeout 30 menit sebagai default usulan; privilege sensitif memakai auth recent, misalnya 15 menit.
- Cookie sesi utama tetap Strict bila memungkinkan. Gunakan cookie korelasi OIDC terpisah SameSite=Lax untuk callback GET; jangan mengendurkan semua cookie karena redirect IdP. Callback POST/form_post belum didukung pada MVP.
- Logout selalu mencabut sesi lokal; RP-initiated logout bila provider mendukung, tidak mengklaim logout global bila tidak tersedia. Back-channel logout diuji bila diaktifkan; minimum ada expiry/re-auth dan revoke sesi oleh admin.
- Perubahan grant/deaktivasi user lokal berlaku pada request berikutnya, termasuk job sebelum apply. Perubahan grup/deaktivasi di IdP disinkronkan pada login/re-auth; tanpa back-channel/SCIM revokasi IdP tidak instan dan dibatasi lifetime sesi. Jangan menjanjikan revokasi langsung dari IdP.
- MFA untuk admin dan akses raw production diwajibkan oleh kebijakan IdP deployment; auth_time/max_age dipakai untuk recent-auth. Interpretasi acr/amr harus spesifik issuer dan diuji, bukan asumsi universal string MFA.
- Kandidat utama OIDC: openidconnect + supported async HTTP client. Kandidat sesi: tower-sessions dengan adapter rusqlite; limiter: governor; kompresi: async-compression. Tidak menulis JWT/JWKS verifier, cookie/session middleware atau algoritma limiter sendiri. Versi final menunggu A00 (MSRV/advisory/trait compatibility). Lihat riset library untuk alternatif dan batas tanggung jawabnya.
Akun darurat lokal: identitas bernama, Argon2id dengan parameter minimum tervalidasi, limiter terpisah, audit dan recent-auth. Tidak ada registrasi/reset password publik pada MVP. Limiter memakai kombinasi sumber tepercaya, backoff akun, dan batas global yang tidak mengunci semua user dengan 10 request; tidak percaya forwarded IP dari klien bebas.
## 6. Model data dan migrasi
Gunakan migrasi aditif bernomor dan transaksi, dengan foreign key, unique constraints, indeks lookup dan status yang tervalidasi. Nama tabel berikut usulan, bukan kewajiban menambah satu tabel untuk setiap konsep.
- users: id, issuer, subject, display_name, active, timestamps; UNIQUE(issuer, subject).
- sessions: token_digest, user_id, csrf digest, created_at, last_seen, expires_at, auth_time, auth method. OIDC login_transactions menyimpan korelasi/PKCE singkat dan konsumsi sekali pakai; token rahasia tidak dicatat ke log.
- access_grants: principal user/group/service, permission/role, scope_type, scope_id, optional expiry, created_by. Mapping grup disimpan eksplisit dan dapat diaudit.
- Orbit metadata: environment production/staging/development, data classification, binding restore_target_id opsional. Restore target tetap membawa identitas database dan outpost yang sudah ada; orbit target tidak wajib menjalankan jadwal backup.
- orbit_relations: id, source_orbit_id, target_orbit_id, active, version, creator. Relasi berarah, tidak otomatis simetris/transitif; cegah sumber=target dan alias identitas database yang sama. Perubahan identitas/tujuan membuat versi baru dan menonaktifkan relasi lama, bukan mengubah job diam-diam.
- refresh_runs: requester_id, relation_id/version, capture_job_id, snapshot_id, restore_job_id, status, timestamps, idempotency key, error code aman. Unique child job links mencegah duplikasi.
- Token Outpost/service: token ID, digest, principal, state, expiry/rotation metadata. Simpan plaintext hanya saat benar-benar perlu menyerahkan token pairing; desain generate-on-claim agar token aktif tidak disimpan mentah. Pairing code disimpan digest, expiry dan konsumsi atomik.
- Upload session wajib memiliki outpost_id dan orbit ownership. Sesi lama tanpa owner ditolak/ditutup, tidak diberi owner hasil tebakan.
- Audit: actor ID, auth method, action, resource, outcome, request/correlation ID, timestamp, detail allowlist; tidak menyimpan payload DB, secret, token atau signed URL.
Migrasi tidak mengubah snapshot lama atau menyimpulkan relasi dari kesamaan application_id/nama. Admin meninjau mapping orbit → target dan grant. Token lama dimigrasi ke digest di tempat lalu plaintext dihapus; rotasi tetap diperlukan karena salinan database/backup lama mungkin memuat token. Shared admin token lama hanya untuk transisi eksplisit dengan batas akhir dan audit, bukan fallback permanen.
## 7. Relasi production → staging
Wizard DevOps memilih orbit production dan orbit staging, mengikat capture profile sumber dan restore target tujuan, memeriksa engine/format/versi yang didukung dan identitas target, lalu memberi grup/user izin refresh pada relasi. Host/DSN/password tidak ditampilkan kepada QA/developer.
Pemeriksaan bukan sekadar label environment: gunakan identitas instance+database yang sudah ada, cek alias sumber/tujuan, Outpost aktif, kredensial terbatas, dan validasi agent sebelum reset. Default self-service menolak target production dan format non-restore-ready. Kesamaan application_id tetap prasyarat kompatibilitas yang ada, bukan pengganti relasi eksplisit.
## 8. Workflow QA
1. QA login, melihat relasi yang diberi grant, sumber production, tujuan staging dan peringatan staging akan ditimpa.
2. QA mengonfirmasi relasi/versi tujuan dan memilih Refresh. POST memakai CSRF dan idempotency key; server menyimpan run dan job capture secara durable.
3. Worker memakai antrean capture yang ada. Capture baru harus menjadi job khusus run, bukan memilih latest snapshot global atau memakai backup lama jika capture gagal.
4. Saat commit capture terverifikasi, tautkan snapshot_id tepat dari capture_job_id, pin snapshot, dan evaluasi ulang user aktif, grant, relasi/versi, expiry request dan kesiapan target.
5. Antrekan restore persis sekali. Konfirmasi run mengikat relasi/versi target sejak awal; tidak menerima target_id pengganti dari browser setelah capture selesai.
6. Agent tujuan memakai lease/fencing, verifikasi checksum dan identitas, buat safety backup dan memperoleh izin apply sebelum perubahan destruktif.
7. UI menunjukkan queued → capturing → snapshot_ready → restoring → completed; kegagalan membedakan capture_failed, blocked/revoked, restore_failed, cancelled, recovery_required. Tampilkan waktu mulai/selesai capture dan identitas snapshot.
Terbaru berarti consistent dump dari job yang diminta; bukan jaminan identik dengan production pada detik restore selesai. Konsistensi mengikuti kemampuan engine/provider; fixture membuktikan transaksi dump dan timestamp, bukan klaim real-time atau konsistensi lintas database.
Satu run aktif per target (termasuk proses capture) dengan constraint/lock durable; request kedua mendapat conflict dan referensi run yang boleh dilihat. Tidak menumpuk antrean restore lama ke staging. Capture sumber diserialkan memakai aturan job saat ini; batas ukuran/waktu dan global concurrency mencegah beban production berlebihan.
Restart memulihkan run dari state SQLite dan hubungan child job, bukan memori/task spawn semata. Cancel sebelum apply membatalkan pekerjaan yang aman; setelah apply tidak mengklaim rollback otomatis. Pencabutan akses sebelum apply memblokir apply; setelah apply dimulai utamakan menyelesaikan pemulihan aman dan audit, bukan mematikan proses database di tengah jalan. Lease hilang setelah reset tetap recovery_required sampai admin reconcile. Snapshot dan safety backup dipin sampai aman dilepas.
## 9. Workflow developer dan kompresi
Developer melihat orbit/snapshot dalam scope. Tombol Download memerlukan snapshot.download dan kebijakan raw-data orbit. Capture baru adalah aksi terpisah; snapshot lama tetap dapat dipilih dengan timestamp jelas.
Gunakan ekspor vault yang ada, kemudian hasilkan arsip unduhan: SQL → .sql.gz; tar filesystem → .tar.gz; PostgreSQL custom dump yang sudah terkompresi dipertahankan sebagai .dump bila metadata menjamin kompresi, selain itu .dump.gz. SQLite → .sqlite.gz. Format/encoding diputuskan dari metadata tervalidasi, bukan ekstensi saja. Jangan mengubah format internal backup/restore hanya untuk download.
Gunakan kompresi gzip streaming atau temporary artifact privat dengan quota/disk admission, batas concurrency, timeout, cleanup sukses/gagal/client disconnect/restart. Jangan menampung seluruh dump di memori atau membuat direktori world-readable. Pin snapshot selama export dan pertahankan lifetime file/direktori sampai body response selesai; evaluasi ulang handler catalog.rs saat ini yang membuat TempDir lokal sebelum stream dikonsumsi.
Endpoint download memakai cookie same-origin atau service token scoped, Cache-Control no-store dan Content-Disposition filename aman. Tidak meneruskan cookie/token ke storage publik, tidak menaruh bearer di query URL, dan tidak membuat tautan publik permanen. Browser memakai native navigation/download, bukan menahan seluruh response sebagai Blob JS. Audit membedakan export requested/ready, stream finished/disconnected; stream selesai bukan bukti file tersimpan di laptop. Berikan format, source/capture timestamp, ukuran dan checksum arsip hasil kompresi bila artifact sudah disiapkan.
MVP mulai dengan download existing snapshot. Jika perlu menunggu ekspor besar, tambahkan job export pendek TTL dengan polling status, bukan HTTP timeout sangat panjang. Kontrak awal harus menetapkan ambang ukuran/waktu berdasarkan benchmark fixture; pilih streaming langsung jika cukup, durable export hanya jika bukti memerlukannya.
## 10. API dan UI yang terdampak
- Pertahankan operator/session sebagai kompatibilitas; tambahkan /auth/oidc/login dan /auth/oidc/callback, identitas /me dan logout lokal. /me mengembalikan identitas/capabilities aman, bukan token IdP.
- Admin APIs: user status/session revoke, role/grant, mapping grup, environment/binding orbit, relation CRUD/version, token rotate/revoke dan audit list.
- Self-service: GET relasi yang boleh digunakan, POST /refresh-runs, GET /refresh-runs/:id, cancel sebelum apply. Client tidak dapat mengirim actor, snapshot hasil capture, atau tujuan arbitrary.
- Semua list/detail snapshot/orbit/job/target difilter scope; download handler tetap memeriksa grant sendiri. Akses raw restore payload hanya agent dan lease yang sesuai.
- UI DevOps: konfigurasi relasi/grant, status agent, audit dan recovery. UI QA: Refresh staging dan progres terpadu. UI developer: pilih snapshot/format/Download dan capture baru bila diizinkan.
- Reuse OperatorGate, OrbitsView, CaptureProfileForm, RestoreTargetForm, DatabaseRestore, JobHistory, SnapshotSheet dan komponen UI rumah. Tambahkan komponen hanya untuk flow relasi dan refresh yang belum ada.
- Perbarui OpenAPI security scheme/requirements, TS types/client, fixture/demo, CLI dan dokumentasi. CLI tetap local HTTP sesuai guard saat ini; jangan mengklaim OIDC CLI/device-flow sudah didukung. Remote automation memakai HTTPS dengan service token scoped melalui client yang mendukungnya.
## 11. Perbaikan seluruh temuan audit
| Temuan | Implementasi | Bukti penerimaan |
| --- | --- | --- |
| Upload lintas Outpost | Owner orbit/session, gate semua jalur legacy, token lifecycle | A tidak dapat init/chunk/seal pada resource B |
| Fallback loopback/proxy | Auth wajib secara default, mode local-development eksplisit dan binding loopback | Proxy lokal tanpa login tetap 401; mode dev tidak boleh bind wildcard |
| RBAC tidak ada | Role + grant resource/relasi + gate per request | Matriks aksi/resource lulus termasuk UUID langsung |
| Limiter global | Rate sumber/backoff akun/batas global, batas concurrency hash, audit deny | Flood satu sumber tidak menghabiskan semua kuota login user sah |
| Token mentah/permanen | Digest, rotate/revoke, expiry policy, migrasi dan re-pair terkontrol | DB baru tidak memuat token aktif mentah; token dicabut ditolak |
| Sesi idle panjang | Idle/absolute timeout, revoke, recent-auth, emergency account | Expired/revoked/old-auth ditolak server |
| Audit tidak lengkap | Structured actor/outcome untuk auth, policy, capture, restore, export, retention | Tidak ada mutasi sensitif tanpa event yang dapat ditelusuri |
| OIDC belum ada | Code+PKCE, token verification, issuer identity, mapping grup | Provider target dan kasus negatif lulus |
## 12. Strategi verifikasi dan standar
Acuan: OWASP ASVS 5.0 (target kontrol relevan setara L2 untuk auth/session/authorization/data handling; bukan klaim sertifikasi), OWASP Authorization/Authentication/Session Management, OIDC Core 1.0 errata 2 dan RFC 9700.
- Unit/property/table tests: permission matrix, scope inheritance snapshot→orbit, unknown permission deny, relasi berarah, environment, token parsing/digests, timeout dan transition state.
- HTTP integration: setiap endpoint anonymous/user/service/outpost, CSRF, direct UUID, metadata redaction, forged actor, invalid target, permission revoked saat job queued/capturing dan sebelum apply.
- OIDC mock provider: signature salah, alg salah, iss/aud/nonce/state salah, callback replay, expired token, JWKS rotation/outage, discovery mismatch, grup hilang dan email sama dengan subject berbeda. Uji browser nyata untuk cookie cross-site callback.
- Database/agent fixture: PostgreSQL dan MySQL production sintetis → capture → staging; compare schema/data, safety snapshot, wrong target, lease lama, disconnect/restart, idempotent retry, race dua permintaan dan retensi bersamaan.
- Export fixture: gzip magic/decompression, checksum konten, file besar, memori bounded, disk penuh, quota exceeded, pembatalan browser dan cleanup restart.
- Deployment fixture: reverse proxy lokal, HTTPS/header trust, no-auth startup, CSP/frame-ancestors/HSTS pada lapisan yang sesuai, no-store untuk data sensitif; jangan membuka CORS luas.
- End-to-end tiga akun DevOps/QA/developer ditambah user tanpa grant. QA refresh tanpa izin download; developer download tanpa izin restore. Akses production sebagai target ditolak.
- Cek dependency advisory/lockfile sebelum release, dokumentasi crate terkini saat memilih/mengintegrasikan library, dan review auth secara khusus.
Per slice jalankan tes fokus. Checkpoint: rtk cargo test --workspace; rtk cargo build --workspace; rtk proxy npm --prefix web test; rtk proxy npm --prefix web run typecheck; rtk proxy npm --prefix web run build. Fixture Restic: rtk cargo test -p tessera-store -- --ignored dengan prasyarat harness tests/mbu/README.md. Uji browser/IdP dan fixture DB adalah gate terpisah, tidak digantikan compile.
## 13. Migrasi, rollout, dan rollback
1. Backup SQLite/config dan inventaris versi tanpa membaca/mencatat rahasia. Uji migrasi pada salinan fixture termasuk orbit legacy, token dan job berjalan.
2. Rilis perbaikan isolasi/fail-closed lebih dahulu; dokumentasikan perubahan mode auth supaya instalasi lokal tidak terkunci tanpa bootstrap admin.
3. Bootstrap admin dan OIDC di staging; petakan grant dan relasi eksplisit. Tidak memberikan akses semua production kepada grup baru secara default.
4. Rehearsal dengan data sintetis, lalu subset aplikasi yang sudah disetujui. Enable self-service per relasi setelah uji capture, restore, safety dan download lulus.
5. Cabut token shared transisi, rotasi agen bila perlu, tinjau audit dan disk/DB load. Production secrets/deploy/destructive restore tetap mengikuti otorisasi operasional terpisah.
6. Rollback operasional: nonaktifkan request baru dan relasi, drain job aman, tahan recovery_required, revoke sesi/token terkait. Jangan downgrade binary lama yang mengabaikan RBAC. Restore DB sebelum migrasi hanya setelah rekonsiliasi job dan kredensial; bukan rollback otomatis yang menghapus audit/job baru.
## 14. Keputusan deployment yang masih dibutuhkan
- IdP/issuer yang dipakai, nama claim grup, grup admin/QA/developer, kemampuan MFA/re-auth/logout. Default desain generic OIDC confidential client; uji satu IdP target sebelum dukungan dinyatakan.
- Aplikasi mana yang mengizinkan raw production di staging dan laptop; siapa pemilik grant dan berapa masa berlakunya. Default tidak ada akses sampai grant dibuat.
- Ukuran dump terbesar, batas concurrency dan window capture yang aman; ukur fixture sebelum menetapkan batas final.
- Versi engine target, provisioning konfigurasi agent/restore target, dan kebutuhan local restore developer (file unduhan saja pada rilis ini).
- Kebijakan retention safety backup, TTL request refresh, audit dan export artifact. Default usulan idle 30m/absolute 8h/recent-auth 15m; refresh queued kedaluwarsa setelah 1h sebelum mulai, artifact sementara maksimal 1h bila mode artifact dipakai. Angka ini harus disesuaikan durasi capture nyata.
## 15. Di luar lingkup rilis
Tidak membuat user/password manager lengkap, multi-tenant, multi-issuer, SCIM, OIDC device flow CLI, arbitrary restore host, local database provisioning, masking engine generik, approval per refresh, atau workflow engine baru. Penambahan hanya bila kebutuhan deployment membuktikannya.
## Referensi
- https://asvs.owasp.org/
- https://openid.net/specs/openid-connect-core-1_0.html
- https://www.rfc-editor.org/rfc/rfc9700.html
- https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html
- https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
- https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
## 16. Keputusan reuse setelah riset library
Gunakan dokumen riset sebagai acuan A00–A25. Ini memperjelas keputusan awal untuk tidak menambah policy/workflow engine tanpa kebutuhan:
- OIDC memakai openidconnect; account/group/grant mapping tetap milik Tessera.
- tower-sessions diprioritaskan untuk lifecycle sesi. Adapter rusqlite, digest storage, concurrent revoke, absolute deadline dan recent-auth harus dibuktikan; stock SQLx store tidak ditambahkan otomatis.
- governor + Tokio Semaphore menggantikan algoritma limiter manual.
- Casbin embedded boleh dipakai bila spike membuktikan total implementasi lebih kecil daripada typed gate + SQL grants. Baseline tetap gate bertipe dengan aksi tetap; tidak membangun policy language generik.
- async-compression membuat file gzip; CompressionLayer bukan pengganti arsip download. flate2 hanya alternatif bila memakai blocking artifact worker.
- rusqlite_migration dipakai bila kompatibel dan mempermudah baseline/migrasi; tidak mengganti ORM/storage semata demi adapter.
- wiremock + Playwright Test + Keycloak fixture untuk pengujian; IdP organisasi tetap pilihan pertama untuk produksi.
- Restic, antrean SQLite/lease, provider DB, UI rumah/React Query, tracing dan utoipa dipakai ulang. Apalis/Temporal/OpenFGA ditunda sampai ada kebutuhan skala/graph lintas layanan.
Tidak ada dependency yang sudah ditambahkan. Tidak ada jaminan semua versi latest kompatibel dengan Axum 0.7, rusqlite 0.31 dan image Rust 1.88. A00 menghasilkan pilihan versi/pin atau keputusan upgrade terpisah sebelum implementasi slice terkait.

View File

@@ -1,374 +0,0 @@
# Tugas auth dan self-service data
Rencana: [auth-self-service-plan.md](auth-self-service-plan.md). Riset library: [auth-self-service-libraries.md](auth-self-service-libraries.md). Status mengikuti bukti di bawah; fitur produk penuh belum selesai. Path hub relatif ke crates/tessera-hub/src kecuali disebutkan. Nama file baru adalah usulan; ikuti struktur aktual saat implementasi. Setiap task ditargetkan S/M (maksimal sekitar lima file utama); pecah lagi jika kontrak/fixture nyata membuat lingkup membesar.
Tes fokus per task; checkpoint menjalankan cargo workspace tests/build dan web test/typecheck/build sebagaimana rencana. Tidak memerlukan deploy atau data production untuk mengerjakan task ini.
## A00 — Compatibility spike dan keputusan dependency
**Dependensi:** —. Dapat dikerjakan independen dari perbaikan akses A01–A03.
**Lingkup:** fixture spike terisolasi; manifest/lockfile percobaan; Dockerfile baseline; dokumen riset library. Tidak mengubah runtime auth sebelum keputusan.
Buktikan openidconnect, tower-sessions + rusqlite adapter, governor dan async-compression terhadap Axum 0.7/Tower 0.5/rusqlite 0.31/Rust 1.88. Bandingkan Casbin dengan typed scoped gate melalui matriks izin yang sama; nilai rusqlite_migration tanpa membawa dua SQLite bindings. Pisahkan eksperimen jika lebih dari lima file utama.
- [ ] Penerimaan: Pilihan versi/features/license/MSRV/advisory dicatat; tidak menambah ORM/layanan kedua tanpa pengurangan biaya nyata; keputusan Casbin/session adapter beserta kode yang digantikan jelas.
- [ ] Verifikasi: Compile fixture terhadap workspace constraints, cek dependency tree/SQLite links dan audit; buktikan session create collision/revoke race, policy deny/revoke dan gzip content. Hapus fixture percobaan yang tidak dipakai secara aman saat implementasi selesai.
**Bukti parsial A00 (11 November 2026):** [fixture dan hasil](../tests/auth-compat/README.md), enam tes executable pada Rust 1.88. Axum 0.7/Tower 0.5 kompatibel dengan tower-sessions 0.15 melalui Extension; satu SQLite binding. Audit baseline: 10 vulnerability + warning Tokio; spike awal 12, setelah perbaikan time/TLS tersisa SQLite/RSA serta warning Tokio. **A00 belum selesai**: remediation baseline, triage RSA, cargo-deny, dan revoke-vs-rotation/user epoch belum tuntas. Tidak ada library auth baru dalam runtime.
## A01 — Inventaris endpoint dan kontrak otorisasi
**Reuse/library:** Reuse utoipa + axum/tower test harness; inventaris policy tetap domain.
**Dependensi:** —.
**Lingkup:** api/{routes,jobs,restore,catalog,session}.rs.
Daftarkan semua route manusia/agen dan aksi, scope, status deny, serta data yang boleh dikembalikan.
- [x] Penerimaan: Semua path router tercantum di `auth-endpoint-contract.md`, termasuk aturan agent/lease dan jalur recovery legacy. Permission scoped masih kontrak untuk A11–A12.
- [x] Verifikasi: `rtk cargo test -p tessera-hub auth_contract` — 2 passed (11 November 2026): inventory seluruh path dibandingkan source router; fixture HTTP seluruh human GET menolak anonymous dan token Outpost. Matriks mutasi/scoped penuh tetap A12.
## A02 — Tutup upload lintas Outpost
**Reuse/library:** Reuse rusqlite transaksi/constraints dan assignment agen; owner check tetap domain.
**Dependensi:** A01.
**Lingkup:** api/routes.rs; db.rs; upload.rs.
Ikat orbit dan upload session ke Outpost, migrasikan sesi lama tanpa owner menjadi tidak dapat digunakan.
- [x] Penerimaan: Owner orbit/session wajib; legacy tanpa owner ditolak. Endpoint admin `PUT /api/v1/orbits/:id/outpost` mengikat legacy ke Outpost aktif; managed assignment tetap capture profile.
- [x] Verifikasi: `rtk cargo test -p tessera-hub legacy_uploads_are_owned` lulus: dua Outpost, unbound orbit, leaked session, retry owner, foreign final chunk/seal, unowned session, foreign Restic commit dan race rebind/commit deterministik. Owner direvalidasi di lock vault sebelum seal/commit.
## A03 — Wajibkan auth dan bootstrap admin
**Reuse/library:** Reuse axum gate/startup config; proxy auth hanya tambahan.
**Dependensi:** A01.
**Lingkup:** admin.rs; main.rs; state.rs; docs/DATABASE-CAPTURE.md; compose.yaml.
Ganti no-auth otomatis dengan mode development eksplisit, siapkan bootstrap admin darurat.
- [x] Penerimaan: Default deny termasuk loopback; startup meminta operator/token atau development eksplisit. Mode dev menolak wildcard/non-loopback di kedua listener; migrasi/bootstrap emergency didokumentasikan.
- [x] Verifikasi: IPv4/IPv6, wildcard, forwarded headers dan HTTP proxy tanpa kredensial lulus. Browser sintetis Chrome DevTools: sign-in → vault kosong → sign-out lulus; console bersih. Playwright gagal launch karena browser binary belum terpasang; bukan hasil lulus Playwright.
### Checkpoint setelah A03
- [x] Tes fokus/regresi: cargo test --workspace 39 passed, 1 ignored sebelum A04; cargo build --workspace lulus. Web test 10 passed, typecheck/build lulus. Tes Restic ignored dijalankan eksplisit: 1 passed.
- [x] Kasus negatif lulus; fixture positif memakai kredensial eksplisit. Tidak melemahkan assertion/validasi.
- [x] Kontrak route dan batas migrasi/dukungan diperbarui; A00 dan OIDC/scoped/self-service tetap terbuka.
## A04 — Struktur principal dan audit
**Reuse/library:** Reuse serde/tracing dan durable audit SQLite; log tidak menggantikan audit.
**Dependensi:** A01.
**Lingkup:** admin.rs; db.rs; api/routes.rs; modul auth/audit baru.
Buat identitas stabil manusia/service/outpost dan event audit structured yang dapat dipakai slice berikutnya.
- [x] Penerimaan: Principal server-derived emergency user/service/Outpost/anonymous; audit typed memuat actor, auth method, action, resource, outcome dan ID. Tabel audit_events aditif mempertahankan audit_log tanpa kolom payload/detail bebas.
- [x] Verifikasi: Tes hub 21 passed setelah A04; reopen/migrasi idempotent, actor login/logout dan redaction, deny resource orbit/session asing. Authentication dibedakan dari authorization setelah review. Coverage semua aksi dan korelasi request penuh tetap A23; user OIDC persisten tetap A07/A09.
## A05 — Simpan digest kredensial dan migrasikan token
**Reuse/library:** Reuse sha2/hmac/rand; subtle sebagai dependency langsung bila diimpor.
**Dependensi:** A02,A04.
**Lingkup:** db.rs; admin.rs; api/routes.rs; agent credentials fixtures.
Migrasikan token aktif ke digest, generate token pairing saat claim, dan konsumsi pairing code secara atomik.
- [ ] Penerimaan: Plaintext token aktif tidak ada di DB baru; token lama yang dimigrasikan tetap dikenali hanya melalui digest; claim replay ditolak.
- [ ] Verifikasi: Tes migrasi/claim konkuren dan inspeksi fixture SQLite dengan token sintetis.
## A06 — Rotasi dan pencabutan token
**Reuse/library:** Reuse primitives dan transaksi token; opaque token, bukan JWT baru.
**Dependensi:** A05.
**Lingkup:** api/token.rs baru; db token module; admin.rs; web/src/api.ts.
Sediakan API admin untuk service/Outpost token lifecycle dan expiry; UI diberikan setelah permission siap.
- [ ] Penerimaan: Token dicabut/expired ditolak pada request berikutnya; rotasi memiliki batas transisi eksplisit dan audit.
- [ ] Verifikasi: Tes token lama/baru, lease agen setelah revoke, dan clock expiry.
## A07 — Sesi individual persisten
**Reuse/library:** Prioritas tower-sessions + adapter rusqlite setelah A00; tanpa SQLx otomatis.
**Dependensi:** A00,A03,A04.
**Lingkup:** admin.rs; api/session.rs; db session module; state.rs.
Persist digest session, user ID, CSRF, idle/absolute expiry dan auth_time; rotate saat login.
- [ ] Penerimaan: Logout/revoke/expiry berlaku server-side; sesi lama tidak di-upgrade menjadi user baru; restart tidak kehilangan kebijakan expiry.
- [ ] Verifikasi: Tes fake clock, session fixation, CSRF, restart dan recent-auth.
## A08 — Limiter login dan akun darurat
**Reuse/library:** governor + Tokio Semaphore + Argon2id existing; tower_governor opsional.
**Dependensi:** A00,A07.
**Lingkup:** admin.rs; api/session.rs; auth tests; docs auth.
Pisahkan rate sumber/backoff akun/global safety dan batasi concurrent password verification.
- [ ] Penerimaan: Flood satu sumber tidak mengunci kuota seluruh login; hash lemah ditolak; failed login diaudit tanpa password.
- [ ] Verifikasi: Tes burst/concurrency dan spoofed forwarded IP; dokumentasi recovery admin.
### Checkpoint setelah A08
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A09 — Login OIDC server-side
**Reuse/library:** openidconnect + supported async HTTP client setelah A00; tanpa verifier buatan sendiri.
**Dependensi:** A00,A07.
**Lingkup:** Cargo.toml/Cargo.lock; auth/oidc.rs baru; api/session.rs; state.rs.
Pilih library berdasar dokumentasi/advisory/MSRV; implementasikan discovery, code+PKCE, browser correlation, callback validation dan unique issuer/subject.
- [ ] Penerimaan: State/nonce/issuer/audience/signature/expiry/replay invalid ditolak; token tidak dikirim ke browser; unknown user tanpa grant.
- [ ] Verifikasi: Mock issuer dengan JWKS rotation/outage; browser nyata cross-site callback.
## A10 — UI login dan lifecycle OIDC
**Reuse/library:** Reuse OperatorGate dan backend session; IdP existing, Keycloak fixture; tanpa SDK token React.
**Dependensi:** A09.
**Lingkup:** web OperatorGate.tsx; web/api.ts; auth/oidc.rs; api/session.rs; docs auth.
Tampilkan SSO, sesi individual, local logout/revoke dan provider logout bila didukung; paparkan keterbatasan revokasi IdP.
- [ ] Penerimaan: SSO masuk/keluar berfungsi; akun emergency terpisah; group missing tidak memperluas akses.
- [ ] Verifikasi: E2E pada IdP target: MFA/re-auth, logout dan user tanpa grant.
## A11 — Grant scoped dan policy gate
**Reuse/library:** Spike Casbin embedded vs typed gate + SQL grants; hasil A00 menentukan; domain safety tetap terpisah.
**Dependensi:** A00,A04,A07.
**Lingkup:** core access model baru; db access module; hub auth policy; policy tests.
Definisikan permission/role, user/group/service grants dan scope orbit/relasi; gunakan gate deny-by-default.
- [ ] Penerimaan: Grant lintas orbit ditolak; refresh tidak memberikan download/capture bebas; admin sensitif mengikuti batas data/environment.
- [ ] Verifikasi: Tes table-driven seluruh matriks aksi/resource, expiry grant dan unknown permission.
## A12 — Terapkan policy pada seluruh API
**Reuse/library:** Reuse axum extractor/middleware dan gate A11; row filtering eksplisit.
**Dependensi:** A11.
**Lingkup:** api/routes.rs; api/jobs.rs; api/restore.rs; api/catalog.rs; api/session.rs.
Ganti gate admin generik dengan policy aksi/resource; filter list dan detail serta pisahkan payload agent.
- [ ] Penerimaan: Direct UUID tidak memintas scope; tidak ada metadata resource lain bocor; token jenis salah ditolak.
- [ ] Verifikasi: Jalankan kontrak A01 dan dua-user HTTP fixtures, termasuk download dan job history.
## A13 — Administrasi akses dan mapping grup
**Reuse/library:** Reuse React Query/komponen rumah + IdP groups; admin grant Tessera tetap lokal.
**Dependensi:** A10,A12.
**Lingkup:** api/access.rs baru; db access module; web/api.ts; UI access baru; OperatorGate.tsx.
DevOps dapat memberi/mencabut grant, menonaktifkan user/sesi dan memetakan grup issuer secara eksplisit.
- [ ] Penerimaan: Perubahan hak berlaku request berikutnya; tidak auto-link email; UI non-admin tidak dapat mengubah grant.
- [ ] Verifikasi: E2E DevOps memberi QA grant, QA memakai akses, DevOps revoke, QA langsung ditolak.
### Checkpoint setelah A13
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A14 — Environment dan binding orbit tujuan
**Reuse/library:** Reuse core models/rusqlite/provider identity; tanpa graph DB baru.
**Dependensi:** A12.
**Lingkup:** core orbit/restore models; db.rs; api/routes.rs; RestoreTargetForm.tsx; web/api.ts.
Tambahkan metadata environment/classification dan binding orbit staging ke restore target terverifikasi.
- [ ] Penerimaan: Orbit target tanpa jadwal capture tetap valid; identity alias source/target ditolak; tidak ada host/secret bebas di UI pengguna.
- [ ] Verifikasi: Tes migrasi additive dan binding target engine/identity salah.
## A15 — Relasi berarah dan grant refresh
**Reuse/library:** Reuse SQLite constraints + selected gate; OpenFGA ditunda.
**Dependensi:** A13,A14.
**Lingkup:** core relation model; db relations; api/relations.rs; web/api.ts.
Simpan relasi source→target aktif berversi, periksa compatibility dan scope, tampilkan relasi yang diizinkan.
- [ ] Penerimaan: Tidak simetris/transitif; same application tanpa relasi tidak cukup; production target ditolak; edit tidak mengganti tujuan job lama.
- [ ] Verifikasi: Tes relasi terbalik, target production, source alias dan versi stale.
## A16 — Wizard DevOps untuk konfigurasi self-service
**Reuse/library:** Reuse form/profile/target rumah dan React Query; tanpa admin framework baru.
**Dependensi:** A15.
**Lingkup:** OrbitsView.tsx; CaptureProfileForm.tsx; RestoreTargetForm.tsx; UI relation baru; web/api.ts.
Satukan pendaftaran sumber/tujuan, relasi dan assignment akses memakai API yang ada.
- [ ] Penerimaan: DevOps menyiapkan production/staging dan grant tanpa konfigurasi tambahan oleh QA; sumber non-ready menunjukkan alasan.
- [ ] Verifikasi: Browser E2E setup dua orbit, agent offline dan incompatible format.
### Checkpoint setelah A16
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A17 — Run refresh durable dan capture baru
**Reuse/library:** Reuse durable SQLite job/lease; Apalis ditunda.
**Dependensi:** A15.
**Lingkup:** core refresh model; db refresh module; api/refresh.rs; db/jobs.rs; api/mod.rs.
POST refresh menyimpan actor/relasi versi/idempotency dan capture child job; satu run aktif per target.
- [ ] Penerimaan: Double submit memberi satu run; capture gagal tidak menggunakan snapshot lama; sumber memakai capture managed saja pada MVP.
- [ ] Verifikasi: Tes transaksi rollback, concurrent requests, capture serialization dan request TTL.
## A18 — Hubungkan snapshot tepat ke restore
**Reuse/library:** Reuse Restic + worker/job existing; Temporal ditunda.
**Dependensi:** A17.
**Lingkup:** db refresh module; db/jobs.rs; db/restore.rs; state.rs; scheduler.rs.
Proses commit snapshot spesifik capture_job_id, pin input dan enqueue satu restore child memakai worker recovery persisten.
- [ ] Penerimaan: Snapshot bukan latest global; restart sebelum/sesudah enqueue tidak membuat restore ganda; retensi tidak menghapus input.
- [ ] Verifikasi: Crash/retry fixture pada setiap transisi dan race retention/delete.
## A19 — Revalidasi sebelum apply dan pemulihan
**Reuse/library:** Reuse restore fencing/safety/provider dan gate; safe cancel tetap domain.
**Dependensi:** A18.
**Lingkup:** api/restore.rs; db/restore.rs; db refresh module; agent restore.rs; policy tests.
Periksa user/grant/relasi saat dequeue dan sebelum apply; hubungkan cancel, safety backup dan recovery_required.
- [ ] Penerimaan: Revoke sebelum apply mencegah reset; cancel setelah apply tidak mengklaim rollback; lease lama tidak dapat apply.
- [ ] Verifikasi: DB fixture revoke saat capture, queued, safety dan applying; disconnect/reset safety failure.
## A20 — UI refresh QA
**Reuse/library:** Reuse DatabaseRestore/JobHistory/React Query; backend sebagai sumber state.
**Dependensi:** A16,A19.
**Lingkup:** DatabaseRestore.tsx; JobHistory.tsx; UI refresh baru; web/api.ts; App.tsx.
Sajikan sumber/tujuan terotorisasi, konfirmasi staging dan progres capture→restore beserta failure/recovery.
- [ ] Penerimaan: QA selesai tanpa DevOps per run; tidak melihat tombol/endpoint download tanpa grant; timestamp snapshot jelas.
- [ ] Verifikasi: Browser E2E QA refresh, retry, cancel dan recovery admin dengan API deny assertion.
### Checkpoint setelah A20
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A21 — Ekspor terkompresi dengan resource bounded
**Reuse/library:** async-compression tokio+gzip setelah A00; flate2 alternatif blocking; jangan pakai CompressionLayer untuk file gzip.
**Dependensi:** A00,A12.
**Lingkup:** api/catalog.rs; store export path; Cargo.toml/Cargo.lock bila diperlukan; export fixtures.
Pakai kompresor yang sudah tersedia/layak, streaming atau private temp artifact; pin snapshot dan cleanup lifetime sampai response selesai.
- [ ] Penerimaan: SQL/tar/SQLite dikompresi; custom dump metadata ditangani benar; tidak menampung seluruh dump di RAM; quota/disk errors aman.
- [ ] Verifikasi: Magic/decompress/content checksum; large-file memory benchmark; disk penuh/disconnect/restart cleanup.
## A22 — Download developer dan audit ekspor
**Reuse/library:** Native browser download + Playwright; tanpa file-saver/Blob seluruh dump.
**Dependensi:** A13,A21.
**Lingkup:** SnapshotSheet.tsx; web/api.ts; api/catalog.rs; audit tests; docs download.
Tampilkan format/ukuran/waktu capture dan native download; raw production grant eksplisit; audit outcome stream.
- [ ] Penerimaan: Developer scoped dapat mengunduh/membuka arsip; QA tanpa download grant ditolak; URL bukan public bearer link.
- [ ] Verifikasi: E2E developer/QA/user asing dan pemeriksaan no-store/filename/cleanup.
## A23 — Lengkapi audit semua aksi sensitif
**Reuse/library:** Reuse audit SQLite + tracing/tower-http request ID; coverage event eksplisit.
**Dependensi:** A06,A12,A19,A22.
**Lingkup:** api/routes.rs; api/jobs.rs; api/catalog.rs; api/access.rs; audit module.
Cakup orbit create, retention, pairing, grant, login deny, capture/restore/export termasuk kegagalan dan actor individual.
- [ ] Penerimaan: Tidak ada mutasi sensitif tanpa event; query audit hanya admin berizin; detail bebas secret/DB payload.
- [ ] Verifikasi: Contract audit tests dari matriks A01; sanitasi log dan failure injection.
### Checkpoint setelah A23
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A24 — Kontrak publik, migrasi dan regresi
**Reuse/library:** Evaluasi rusqlite_migration setelah A00; reuse utoipa, tambah cargo-deny/audit tooling.
**Dependensi:** A20,A22,A23.
**Lingkup:** OpenAPI routes; docs/SPEC.md; docs/DATABASE-CAPTURE.md; demo fixtures; CLI fixtures.
Sinkronkan API/TS/OpenAPI security, demo grant sintetis, dokumentasi token transisi dan kompatibilitas CLI/local.
- [ ] Penerimaan: Migrasi DB lama mempertahankan snapshot/job; legacy unowned ditolak; rollback tidak menggunakan binary yang memintas RBAC.
- [ ] Verifikasi: Build/test workspace+web; fixture migration backward-data compatibility dan CLI regresi.
## A25 — Rehearsal dan rollout terbatas
**Reuse/library:** wiremock + Playwright Test + Keycloak disposable dan harness MBU existing; tanpa dependency runtime IdP wajib.
**Dependensi:** A24.
**Lingkup:** tests/mbu harness; auth e2e fixtures; docs rollout; compose.yaml.
Jalankan IdP/proxy/DB/browser rehearsal, ukur quota/timeouts, pilot relasi yang disetujui dan dokumentasikan bukti.
- [ ] Penerimaan: Dua user story dan seluruh kasus deny lulus; ada runbook emergency/revoke/recovery dan batas dukungan IdP jelas.
- [ ] Verifikasi: PostgreSQL/MySQL fixtures + IdP target; review kontrol ASVS relevan; approval operasional terpisah sebelum deploy/data nyata.
### Checkpoint setelah A25
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## Traceability temuan audit
| Temuan | Task |
| --- | --- |
| Isolasi upload | A01–A02, A05–A06 |
| Fallback loopback | A03 |
| RBAC/individual identity | A04, A07, A09–A16 |
| Login DoS/limiter | A08 |
| Token plaintext/lifecycle | A05–A06 |
| Session timeout/re-auth | A07–A10 |
| Audit tidak lengkap | A04, A23 |
| OIDC compatibility | A09–A10, A25 |
| QA production→staging | A14–A20 |
| Developer compressed download | A21–A22 |

View File

@@ -1,140 +0,0 @@
# Auth Tessera: rencana per milestone
Dibuat 14 November 2026, menggantikan rencana A00–A25 (arsip: `archive/`).
Referensi yang tetap berlaku: [kontrak endpoint](auth-endpoint-contract.md), [riset library](auth-self-service-libraries.md), [spike kompatibilitas](../tests/auth-compat/README.md).
Tujuan: login per orang lewat OIDC dengan sesi persisten, lalu hak akses per scope, lalu workflow self-service. Setiap milestone bisa dirilis sendiri dan punya kriteria selesai yang bisa dibuktikan. Milestone M4 ke atas ditulis kasar dan dipecah ulang saat tiba gilirannya.
Prinsip: pakai library untuk protokol (OIDC, rate limit, gzip), tulis sendiri hanya aturan domain Tessera. Satu hub, satu issuer, SQLite. Tidak ada policy engine, broker, atau workflow engine baru.
## M0 — Fondasi (selesai)
Auth wajib secara default, mode development eksplisit dan loopback saja, upload terikat pemilik Outpost, `Principal` dan `audit_events` bertipe, kontrak endpoint, login operator + CSRF.
Bukti: `cargo test -p tessera-hub` (kontrak, upload ownership, sesi operator).
Catatan: perubahan ini masih uncommitted di working tree. Commit sebelum M1.
## M1 — Baseline dependency (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: workspace siap menerima `openidconnect` tanpa pin yang bentrok.
- rustls 0.23.23 → 0.23.46 (webpki 0.102.8 → 0.103.17), tokio 1.40.0 → 1.54.1 (pin `1.51.6`), rusqlite 0.31.0 → 0.41.1 (libsqlite3-sys 0.28 → 0.39.1).
- Compiler 1.88.0 → **1.89.0** (`rust-toolchain.toml`, `Dockerfile`), karena rusqlite 0.41 butuh 1.89. Tidak ada perubahan source untuk rusqlite/tokio.
- `rustls-pemfile` (unmaintained) dibuang; PEM dibaca lewat `rustls::pki_types::pem` di `mtls.rs` dan agent `http.rs`.
- `deny.toml` ditambahkan (advisories, lisensi permisif eksplisit, bans, sources); semua crate internal `publish = false`.
Bukti: `cargo test --workspace` hijau (jumlah tes sama dengan sebelum upgrade), `cargo audit` 0 vulnerability (sisa 1 warning: `proc-macro-error` unmaintained, transitif), `cargo deny check` ok. Hub booting di salinan DB dev lama (`integrity_check` ok), `/health` dan `/api/v1/orbits` merespons.
Belum terbukti: build image Docker `rust:1.89`, dan tes Restic ignored. Belum ada CI di repo, jadi gate ini baru jalan manual (`cargo audit`, `cargo deny check`).
Sisa catatan: `rsa` 0.9 (RUSTSEC-2023-0071) baru muncul saat `openidconnect` masuk di M3; dikecualikan dengan alasan reachability di sana, bukan sekarang.
## M2 — User dan sesi persisten (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: identitas per orang dan sesi yang bertahan setelah restart.
- Tabel `users` (UNIQUE issuer+subject, `active`, `generation`) dan `sessions` (digest SHA-256 dari ID, user, generation, auth method, credential fingerprint, auth_time, last_seen, expires_at) di `db/sessions.rs`. Store sendiri di rusqlite, bukan `tower-sessions`.
- Validasi sesi satu statement: user aktif, generation cocok, absolute 8 jam, idle 30 menit; geser idle lewat UPDATE-only (tidak bisa menghidupkan baris yang sudah dicabut). Revoke per user menaikkan generation dan menghapus baris dalam satu transaksi. Foreign key SQLite tidak aktif di koneksi ini, jadi tidak diandalkan.
- Akun darurat adalah baris user dengan issuer `local:emergency` (bukan URL, tidak bisa ditabrak issuer OIDC). Sesi password terikat ke fingerprint hash operator: hash dilepas atau diganti saat restart membuat cookie lama mati. Ini menjaga perilaku lama (restart memutus sesi) sekarang sesi persisten.
- CSRF diturunkan dari ID sesi dengan prefix berbeda dari digest penyimpanan, jadi tidak perlu disimpan dan tidak bisa dipakai sebagai kunci.
- `authorize_operator` melakukan satu lookup sesi per request (sebelumnya dua).
- `GET /api/v1/me` (identitas, kind, auth method, nama, capabilities; no-store) masuk kontrak endpoint. `GET /operator/session` kini juga mengembalikan `expires_at`.
Bukti: `cargo test --workspace` hijau (hub 33 tes, naik dari 21: deadline dengan clock injeksi, hanya digest tersimpan, touch setelah revoke, revoke per user lalu login ulang, user nonaktif, restart/reopen DB, hash diganti/dilepas, fixation, `/me`); `cargo audit` 0 vulnerability, `cargo deny` ok. Proses nyata: login, restart dengan hash sama → 200, hash diganti → 401, hash dilepas → cookie tidak dianggap sesi, hash asli lagi → sesi pulih.
Belum ada: endpoint HTTP revoke per user dan nonaktifkan user (fungsi store `revoke_user_sessions` sudah ada dan dites; endpoint admin menunggu M5), pembersihan sesi kedaluwarsa hanya terjadi saat ada login baru, dan limiter login masih in-memory (M4).
## M3 — Login OIDC (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: SSO berfungsi sebagai login utama; akun darurat tetap ada.
- `openidconnect` 4.1 (reqwest + rustls), confidential client, code + PKCE S256, redirect URI statis, redirect HTTP dimatikan, timeout connect 5 detik dan total 15 detik. Konfigurasi `TESSERA_OIDC_*` divalidasi saat startup (https wajib, http hanya loopback + local development, mapping admin wajib). Dokumentasi ada di `docs/DATABASE-CAPTURE.md`.
- Transaksi login satu kali pakai (digest state dan cookie korelasi SameSite=Lax terpisah, TTL 10 menit, maksimal 500 baris). Percobaan apa pun, termasuk dari browser tanpa cookie, menghanguskan transaksi.
- Verifikasi ID token oleh library: signature RS256, iss, aud (audiens lain ditolak), azp, exp, nonce, access-token hash. Metadata dan JWKS di-cache 10 menit; saat IdP mati cache lama tetap dipakai; kegagalan signature memicu satu refresh (dibatasi 60 detik) lalu coba ulang.
- Identitas (issuer, subject) tanpa auto-link email. Admin hanya dari config (subject atau grup di claim terverifikasi; claim hilang atau salah bentuk tidak memberi apa pun). User tanpa grant mendapat sesi tapi `403` di semua API manajemen; `/me`, status sesi, dan logout tetap jalan. Principal audit `oidc:<users.id>`, tidak pernah dari nama IdP.
- Sesi OIDC terikat ke fingerprint config (issuer, client, mapping admin): mengubah mapping atau mematikan OIDC mengakhiri sesi.
- UI: tombol "Sign in with SSO", form password darurat dipisah, halaman "No access yet", pesan error dari kode tetap (`auth_error`).
Bukti: `cargo test --workspace` hijau (hub 51 tes, stabil 5/5 run). Tes end-to-end dengan IdP palsu dan token yang ditandatangani kunci RSA uji: admin lewat subject dan grup, user tanpa grant, claim grup rusak, email sama subject beda, nonce/issuer/audience/azp/expired/signature penyerang/alg none/HS256 salah, replay/cookie salah/state palsu/transaksi kedaluwarsa, rotasi JWKS dan pembatasan refresh, IdP mati (cold dan warm), OIDC nonaktif → 404. `cargo audit` hanya warning `proc-macro-error`; `rsa` dikecualikan dengan alasan tertulis (`deny.toml`, `.cargo/audit.toml`). Rehearsal nyata: Keycloak 26.1 di Docker + hub nyata + browser: login Alice (grup admin) → UI terbuka, `/me` oidc admin; Bob → "No access yet", `/orbits` 403; logout lokal; pesan error callback palsu. Cookie `__Host-` Secure bekerja di `http://localhost`. DB dan log tidak memuat token, secret, atau password.
Belum ada / batas: RP-initiated logout dan back-channel logout (logout hanya mengakhiri sesi Tessera, sesi IdP tetap), re-auth dan `max_age` untuk akses sensitif, ES256/PS256 (hanya RS256), limiter pada `/login` dan `/callback` (M4; yang ada hanya batas 500 transaksi pending), revokasi perubahan grup IdP hanya saat sign-in berikutnya (maksimal 8 jam), uji dengan IdP organisasi target, uji logout/MFA di IdP target.
Catatan operasional: image Keycloak 26.1 tertinggal di Docker lokal (~500 MB), container sudah dihapus.
## M4 — Hardening kredensial (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: tidak ada rahasia aktif yang tersimpan mentah dan endpoint publik tidak bisa dibanjiri.
- Pairing code dan token Outpost hanya tersimpan sebagai digest SHA-256 (`db/credentials.rs`: `pairing_codes`, `outpost_credentials`). Token dibuat saat klaim (256 bit dari OsRng) dan hanya ada di respons klaim. Masa berlaku `TESSERA_OUTPOST_TOKEN_DAYS` (default 365).
- Migrasi di tempat dari `wormhole_tokens`: token aktif tetap berfungsi dan mendapat masa berlaku baru dari waktu migrasi (expiry lama adalah expiry kode, bukan token); kode belum terpakai tetap dengan expiry-nya, token pra-cetak dibuang; tabel lama di-drop dengan `secure_delete`. Tidak ada referensi `wormhole_tokens` di luar migrasi.
- Rotate (`POST /wormhole/outposts/:id/rotate?grace_minutes=`; token lama hidup selama grace, 0 = langsung putus) dan revoke (`.../revoke`), keduanya admin-only dan diaudit. Outpost yang dicabut ditolak pada request berikutnya, termasuk di endpoint yang membawa lease, dan harus di-pair ulang.
- `governor` per sumber untuk login darurat, klaim pairing, dan SSO login/callback; plafon akun dan klaim global lebih longgar; semaphore Argon2 (2 permit) dengan `try_acquire` dan permit dibawa ke dalam `spawn_blocking`. Sumber = alamat peer; `X-Forwarded-For` hanya dari `TESSERA_TRUSTED_PROXIES`, dibaca kanan ke kiri; IPv6 per /64; penolakan diaudit maksimal sekali per menit per sumber.
- Listener mTLS sekarang menyuplai alamat peer ke handler.
- Token admin bersama bisa diberi tanggal akhir (`TESSERA_ADMIN_TOKEN_EXPIRES`); lewat tanggal ditolak (dan tidak jatuh ke mode development anonim); tiap pemakaian tercatat sebagai `legacy-admin-token`.
Bukti: `cargo test --workspace` hijau (hub 70 tes), `cargo audit` hanya `proc-macro-error`, `cargo deny` ok. Tes: tidak ada token/kode mentah di file DB (termasuk `-wal`/`-journal`, dengan sanity check bahwa scan benar-benar membaca file), klaim sekali pakai, expiry/revoke/rotasi dengan clock injeksi, migrasi legacy (token aktif dengan expiry lama tetap jalan, scrub, idempoten), pairing→claim lewat HTTP nyata, revoke → 401 di endpoint upload dan endpoint lease, flood satu sumber tidak menghabiskan kuota sumber lain dan header palsu tidak membantu, audit penolakan sekali per menit, Argon2 terbatas dan permit dilepas, token admin kedaluwarsa, tes lewat listener mTLS sungguhan (gagal 500 bila penyisipan peer dilepas). Proses nyata pada DB bergaya lama dengan token sintetis: migrasi, token lama tetap 200, tidak ada teks mentah di file DB, pairing/rotate/revoke via HTTP, audit sesuai, tidak ada token di DB maupun log.
Belum ada / batas: rotasi oleh agen sendiri (operator yang mengantar token baru; grace window jadi jembatannya), tanggal akhir token admin sengaja tetap opsional (keputusan Sen, 14 November 2026; peringatan saat start bila `TESSERA_ADMIN_TOKEN_EXPIRES` tidak diset, jadi token bisa tetap permanen sampai tanggal itu dipasang), limiter di memori (reset saat restart, tidak dibagi antar proses), tidak ada `Retry-After` di respons 429, endpoint list Outpost belum menampilkan status/expiry kredensial, tidak ada UI untuk rotate/revoke, backup DB lama masih memuat token mentah sehingga rotasi setelah upgrade wajib. Migrasi hanya diuji pada salinan; belum dijalankan pada hub produksi.
## M5 — Hak akses per scope (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: user biasa hanya melihat dan memakai orbit yang diberikan; administrator tetap memegang semuanya.
- Model: permission bertipe (`auth.rs`) dan tabel `access_grants` (user atau grup IdP, permission, global atau satu orbit, expiry, pembuat). Tanpa Casbin. Hanya `orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download` yang dapat diberikan ke non-admin; semua permission lain (kelola orbit/profil/Outpost/retensi, hapus snapshot, restore, akses) hanya dimiliki administrator terkonfigurasi dan tidak dapat didelegasikan. Role `viewer`, `capturer`, `downloader` hanya jalan pintas yang diperluas menjadi permission (selalu termasuk `orbit.read`).
- Satu gate (`api/gate.rs`): `authenticate` (401 atau CSRF 403), resolve resource, lalu `admin_only` / `scoped` / `visible`. Orbit tanpa `orbit.read` = 404, terlihat tapi tanpa izin = 403, daftar tanpa akses sama sekali = 403, route admin-only = 403 tanpa lookup resource. `require_admin*` dihapus agar compiler memaksa tiap handler memilih gate. Grant dibaca dari DB di setiap request (tidak ada cache), jadi cabut grant, expiry, nonaktifkan user, dan "sign out everywhere" berlaku di request berikutnya.
- Filter sebelum LIMIT untuk riwayat capture job (`json_each` di SQL), daftar snapshot/orbit/profil terfilter, grup diambil dari token saat sign-in dan disimpan di sesi (batas 64 grup x 128 karakter).
- Atribusi memakai identitas stabil (`oidc:<users.id>`, `emergency:<nama>`, `legacy-admin-token`), tidak pernah nama dari IdP; pekerjaan baru tidak bisa menyamar sebagai `scheduler`. (Baris lama di DB tetap memuat nama lama.)
- API admin: `/api/v1/access/grants` (GET/POST/DELETE), `/access/users` (GET, PUT aktif/nonaktif, revoke-sessions). Validasi: permission tidak dikenal atau bukan prefix, tidak dapat diberikan, role tidak dikenal, role dan permission bersamaan, user/orbit tidak ada, expiry lampau atau lebih dari 2 tahun, grup terlalu panjang, duplikat 409; admin tidak bisa menonaktifkan diri sendiri atau akun darurat. Semua perubahan diaudit per id.
- UI: tab Access (admin) untuk memberi dan mencabut akses, daftar orang yang sudah sign in; non-admin hanya melihat Vault dan Activity, tombol capture/download/hapus/restore sesuai grant, dan tidak memanggil endpoint admin. `/me` mengembalikan `admin`, `capabilities`, `grants`.
- Kontrak endpoint diperbarui: tiga endpoint restore (`restore-targets` dua rute dan `snapshots/:id/restore-jobs`) dan `restore-jobs` GET kini admin-only (identity database tujuan; lihat plan bagian 7) sampai self-service M6.
Bukti: `cargo test --workspace` hijau (hub 83 tes, 12 tes baru). Matriks dibangkitkan dari file kontrak dengan resource nyata di dua orbit untuk enam jenis pemanggil (anonim, tanpa grant, viewer orbit lain, viewer, capturer, downloader, anggota grup, admin): route baru yang tidak ada resepnya membuat tes gagal, user tanpa grant tidak pernah mendapat 2xx, dan tiga mutasi sengaja (download hanya butuh `orbit.read`, reconcile tanpa gate admin, daftar job tanpa filter) semuanya tertangkap. Rehearsal browser nyata dengan Keycloak 26.1: Bob "No access yet" -> Alice memberi viewer pada `wiki` lewat tab Access -> Bob melihat 1 orbit dan 14 snapshot (admin 12 orbit dan 185), hanya tab Vault dan Activity, semua request 200 tanpa 403/404 dan tanpa `restore-jobs`/`access` -> grant dicabut -> UI Bob kembali ke "No access yet" pada siklus polling berikutnya.
UI Access memakai komponen yang sama dengan form lain (`Select` bertema dan `DatePicker` kustom dengan navigasi keyboard). Pilihan tampilan Window/Radar disimpan per akun (`/api/v1/me/preferences`, tabel `user_preferences`), bukan hanya di browser.
Keputusan Sen (14 November 2026): admin tetap boleh mengunduh semua snapshot tanpa grant eksplisit (rencana awal meminta grant untuk data sensitif; kebijakan data mentah per orbit dipertimbangkan lagi di M6).
Belum ada / batas: principal `service` bergrant (hanya user dan grup; token admin lama = admin), grant atas nama grup berlaku dari token saat sign-in, UI tidak menyembunyikan satu per satu aksi untuk orbit tanpa izin di semua panel (backend tetap menolak), tidak ada pra-otorisasi user yang belum pernah sign in, tidak ada UI per-orbit untuk melihat siapa saja yang punya akses, pencarian vault masih menampilkan konsol admin untuk non-admin (navigasi diabaikan).
## M6 — Self-service data (dipecah 14 November 2026, menunggu konfirmasi urutan)
Desain rinci lama: `archive/auth-self-service-plan.md` bagian 7–9. M6 menyentuh restore ke database sungguhan, jadi dipecah menjadi empat sub-milestone yang masing-masing bisa dirilis dan diuji sendiri.
### M6a — Download terkompresi untuk developer (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: `GET /snapshots/:id/download` mengirim arsip yang memang terkompresi, bukan dump mentah.
- Format ditentukan dari isi file (magic byte) dan metadata, bukan dari nama: SQL polos jadi `.sql.gz`, tar jadi `.tar.gz`, SQLite jadi `.sqlite.gz`, arsip filesystem hub jadi `.tessera-fs.gz`, konten tak dikenal jadi `.dump.gz`; `pg_dump -Fc` tetap `.dump`; gzip/zstd/xz/bzip2/zip tidak dikompresi dua kali (isi menang atas label). Tabel diturunkan dari setiap produsen manifest yang ada (agen, provider hub, restic filesystem, wormhole lama, SQLite lama, demo). Konsumen endpoint ini hanya tautan unduh di UI; agen dan CLI tidak memakainya.
- Header jujur: tanpa `Content-Encoding`, `Content-Length` hanya untuk byte yang dikirim apa adanya, `application/gzip`, `nosniff`, `no-store`; HEAD 405 (tidak menjalankan ekspor).
- Urutan: autentikasi, cari snapshot, cek izin pada orbitnya, baru admission (semaphore, default 2, dan sisa disk 512 MiB) sehingga pemanggil tanpa izin tidak dapat menghabiskan slot. Permit dan direktori ekspor ikut hidup bersama body respons; frame dibatasi 64 KiB.
- Audit `export.requested/ready/finished/disconnected` per snapshot dan principal; direktori `tessera-export-*` dihapus saat selesai, klien putus, dan saat start berikutnya setelah crash (hanya awalan itu, hanya di level atas data dir).
Bukti: `cargo test --workspace` hijau (hub 94 tes). Tes: tiap jenis snapshot dengan hasil dekompresi sama persis dengan byte asli, header, 24 MiB dialirkan dalam frame di bawah 256 KiB, audit dan pembersihan untuk unduhan selesai dan ditinggalkan, batas satu slot (ditolak seketika, slot kembali), disk tidak cukup (507), HEAD, pemanggil tanpa izin tidak memakai slot, sweep hanya menyentuh milik sendiri; tiga mutasi sengaja tertangkap (Content-Length pada gzip, PGDMP dikompres ganda, unduhan ditinggalkan tercatat selesai). Proses nyata dengan producer asli (orbit filesystem via restic): `.tar.gz`, `gunzip -t` ok, hasil ekstrak identik dengan file asli (termasuk 24 MiB acak); curl dibatasi lajunya lalu dibunuh di tengah: direktori ekspor hilang dan tercatat `export.disconnected`; stale dir dibersihkan saat restart tanpa menyentuh folder lain; HEAD 405. `cargo audit`/`deny` tidak berubah (async-compression 0.4.36, rustix 1.1.6, tanpa duplikat baru).
Batas: snapshot yang tersimpan sebagai chunk vault dibaca utuh ke memori saat diekspor (hanya yang berbasis restic dan tahap kompresi yang terbatas); SQL asli dari PostgreSQL/MySQL baru diuji lewat fixture, rehearsal dengan database sungguhan ada di M6d; tidak ada checksum arsip hasil kompresi karena streaming; sisa `.tmp*` dari kode lama tidak disapu.
### M6b — Environment dan relasi production → staging (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: DevOps menyatakan "sumber X boleh menimpa target Y", dan hak memakainya bisa diberikan per relasi.
- Environment (production/staging/development) di orbit sumber dan di restore target (bukan orbit placeholder, supaya staging tidak muncul di galaksi, scheduler, retensi, dan binding Outpost lama). Belum dilabeli = ditolak; target berlabel production ditolak.
- `orbit_relations` berarah (sumber orbit managed ke restore target), berversi (retarget membuat id baru, versi berikutnya, yang lama `replaced`), tidak simetris/transitif, satu relasi aktif per pasangan (indeks unik parsial). Aturan dengan kode penolakan: sumber tidak dikenal atau belum dilabeli, bukan capture profile managed, format tidak restore-ready, target tidak dikenal atau belum dilabeli atau production, aplikasi target berbeda, engine berbeda, target cocok dengan database yang di-capture sebagai production/belum diklasifikasi (dibaca dari `source_identity` snapshot semua orbit; backup staging/development milik target sendiri tidak dihitung), Outpost tidak aktif, duplikat. Fakta yang ada di DB diperiksa ulang di dalam transaksi; sumber tanpa snapshot ditandai `verified=false` agar M6c memeriksa ulang sebelum apply.
- Relasi mati di transaksi yang sama saat target di-relabel production atau Outpost dicabut, dan `usable` dihitung ulang saat dibaca (kredensial kedaluwarsa); diaudit.
- Hak `refresh.run` per id relasi di tabel sendiri `relation_grants` (user atau grup, expiry), tanpa global dan tanpa ikut ke versi baru (fail-safe); `refresh.run` bukan permission `access_grants` sehingga `scoped` dan `visible` tidak pernah menerimanya; gerbang relasi sendiri (`gate::relation`, `visible_relations`).
- API (admin, `relation.manage`): `/orbits/:id/environment`, `/restore-targets/:id/environment`, `/relations` (GET untuk wizard dengan identity, POST), `/relations/:id` (PUT retarget, DELETE), `/relations/:id/access` (+ `/:grant`). Orang dengan grant relasi hanya melihat `GET /refresh-relations`: nama dan environment, tanpa identity, host, Outpost, atau application id. `POST /restore-jobs` admin tidak diubah.
- UI: konsol Relations (admin) dengan `Select` yang sama: label environment, form hubungkan sumber ke target (hanya target yang cocok ditawarkan), retarget, akhiri, dan siapa yang boleh refresh.
Bukti: `cargo test --workspace` hijau (hub 106 tes; 12 tes baru: 9 store, 5 HTTP termasuk matriks yang diperluas dengan jenis `RelationList`, fixture relasi di dua orbit, dan pemanggil yang hanya punya grant relasi). Tes: setiap aturan punya penolakannya sendiri, arah, versi, grant tidak ikut retarget, relabel production dan revoke Outpost mematikan relasi seketika, kredensial kedaluwarsa membuatnya tidak usable, database production berlabel staging tertangkap lewat snapshot, grant per user dan grup dengan expiry, tampilan refresher tanpa identity/host. Empat mutasi sengaja tertangkap (daftar refresher menampilkan semua, retarget tanpa gerbang admin, target production diterima, relabel tidak mematikan relasi). Rehearsal browser dengan hub asli (data sintetis): label environment lewat Select, hanya sumber yang siap dan target yang cocok ditawarkan, relasi dibuat (version 1, "not yet compared"), grup diberi akses, retarget menjadi version 2 dengan akses kosong, relabel target production mengakhiri relasi dan UI menampilkan pemberitahuan.
Catatan untuk M6d: pengguna yang hanya punya grant relasi belum dianggap `authorized` oleh status sesi dan vault UI memanggil `/orbits` dan `/snapshots` saat load (403); UI QA harus menangani itu (hitung grant relasi atau wajibkan viewer pada orbit sumber).
Belum ada / batas: relasi belum menjalankan apa pun (M6c); sumber yang di-capture tidak di-cek terhadap target yang sama bila snapshot-nya belum ada (ditandai belum dibandingkan); pendaftaran restore target masih lewat Orbits console dan memerlukan Outpost aktif; ekstra: form login tanpa SSO tidak lagi menampilkan label "Details" dan memakai gaya field yang sama.
### M6c — Refresh run durable (backend) (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: satu permintaan "refresh staging" menjalankan capture baru lalu restore snapshot hasil capture itu, tanpa persetujuan DevOps per eksekusi.
- `refresh_runs` (di SQLite, bertahan setelah restart): `capturing`, `restoring`, lalu `completed`, `capture_failed`, `restore_failed`, `blocked` (dengan alasan), `expired`, `cancelled`, `recovery_required`, `reconciled`. Satu run aktif per target (indeks unik parsial), kunci idempotensi per pemohon, plafon run serentak (`TESSERA_REFRESH_MAX_ACTIVE`), TTL sampai mulai menimpa (`TESSERA_REFRESH_TTL_MINUTES`, default 120 menit; setelah apply dimulai tidak pernah dipotong).
- Run dan capture job dibuat dalam satu transaksi; run mengikuti `capture_job_id`-nya sendiri (id snapshot sama dengan id job), bukan "snapshot terbaru", sehingga capture gagal tidak pernah memakai snapshot lama. Restore di-enqueue dan dikaitkan dalam satu transaksi dengan penjaga `restore_job_id IS NULL`; setiap langkah aman diulang setelah crash. Snapshot dipin sejak run dimulai lewat `snapshot_in_restore` (dipakai prune retensi dan hapus manual).
- Pemeriksaan ulang sebelum menimpa: `authorize_apply` memeriksa dalam transaksi yang sama dengan perpindahan ke `applying` bahwa relasi masih aktif dan usable, pemohon masih user aktif, grant yang mengotorisasi masih ada dan belum kedaluwarsa, TTL belum lewat, dan target bukan database sumber. Bila tidak, restore dibatalkan, run `blocked`, agen mendapat 409 (agen tidak menimpa apa pun tanpa 2xx; dicek di `tessera-agent`). Restore yang diantrekan admin langsung (`POST /restore-jobs`) tidak punya run dan berperilaku persis seperti sebelumnya (ada tesnya). Sesudah apply dimulai, run diselesaikan, bukan dibatalkan.
- Driver (`refresh.rs`) hanya melihat DB setiap 3 detik; pembacaan manifest snapshot dilakukan di luar kunci DB, lalu transaksi memvalidasi ulang sebelum meng-enqueue restore. Alasan penolakan sebelum restore: relasi berakhir atau tidak usable, user dinonaktifkan, akses dicabut, kedaluwarsa, target cocok dengan database production yang di-capture, target ditolak oleh pemeriksaan restore.
- API: `POST /refresh-runs` (relation_id + konfirmasi `REFRESH <sumber> TO <target> v<versi>` + kunci idempotensi; 404 bagi yang bukan pemegang grant; 409 `stale_confirmation`, `run_active` dengan id hanya bagi yang boleh melihatnya, `source_unavailable`, `relation_unusable`), `GET /refresh-runs`, `GET /refresh-runs/:id`, `DELETE /refresh-runs/:id` (pemohon atau admin, sebelum apply). Non-admin tidak melihat id snapshot, pemohon, atau identity database. Audit `refresh.*` per run.
Bukti: `cargo test --workspace` hijau. 13 tes refresh yang menjalankan agen lewat endpoint Outpost sungguhan (claim, report, payload dengan manifest dan hint asli, claim restore, safety, apply): alur penuh dengan snapshot milik run (bukan yang lama), double submit satu run, dua kunci pada satu target satu run dan satu 409, capture gagal tidak memakai snapshot lama, pencabutan (grant dihapus, user dinonaktifkan, relasi di-retarget, target di-relabel production, Outpost dicabut) pada tiap tahap (saat capture, setelah capture sebelum restore diantrekan, restore diantrekan, setelah safety backup sebelum apply) selalu berakhir `blocked` dengan restore dibatalkan dan apply ditolak 409, setelah apply dimulai tidak ada yang membatalkan, restore admin tidak tersentuh, pin dari awal (hapus ditolak, prune melewatkannya) dan dilepas saat selesai, TTL, konfirmasi basi dan plafon, visibilitas dan pembatalan, kepemilikan langkah yang diulang, target = sumber atau cocok dengan production. Matriks akses diperluas dengan jenis `RunRow` dan run fixture. Mutasi sengaja tertangkap: guard apply dihapus, pin dihapus, sinkronisasi mengabaikan hilangnya otorisasi, tanpa kedaluwarsa, semua orang bisa membaca run, pemegang grant bisa membatalkan run orang lain. Proses nyata (hub sungguhan, data sintetis, agen disimulasikan dengan curl ke endpoint Outpost): loop driver menggerakkan run ke `restoring` sendiri dengan restore memakai snapshot milik run, run bertahan setelah hub dimatikan dan dinyalakan lagi, relabel target menjadi production membuat run `blocked` dan restore `cancelled`.
Belum ada / batas: UI QA (M6d); sumber yang dibuat lewat API memakai jalur commit Restic (payload langsung ditolak 409), jadi rehearsal dengan agen, Restic, dan PostgreSQL asli ada di M6d; untuk grant grup, hub hanya memeriksa bahwa grant masih ada, bukan bahwa orang itu masih anggota grup (dicatat di dokumentasi); admin yang diturunkan lewat konfigurasi tidak menghentikan run yang sudah dimulai; pemanggilan gate relasi saat memulai run bersifat berlapis (pencarian grant memberi 404 yang sama), jadi mutasi yang menghapusnya hanya menghilangkan satu baris audit.
### M6d — UI refresh QA dan rehearsal nyata
Hasil: QA menekan "Refresh staging" dan melihat progres; developer mengunduh `.gz`.
- UI QA (relasi yang boleh dipakai, peringatan staging akan ditimpa, konfirmasi, progres, error yang dibedakan) dan tampilan developer.
- Rehearsal nyata: PostgreSQL production sintetis dan staging di Docker, agen nyata, capture → restore, bandingkan skema dan data, revoke di tengah run, retry, unduh `.gz` dan muat ulang.
Selesai bila: e2e browser untuk QA dan developer dengan assertion API deny, dan hasilnya dicatat di sini.
Hasil (selesai, belum di-commit):
- Backend: orang yang hanya punya grant relasi (tanpa `orbit.read`) kini `authorized` (bisa masuk aplikasi) dan `/me.refresh_relations` memuat relasinya; semua endpoint vault tetap 403. Tes baru `someone_who_may_only_refresh_gets_into_the_app_but_sees_nothing_else`. Hub 120 tes hijau, web 75 tes, typecheck dan build bersih.
- UI: konsol "Refresh" (`components/refresh/RefreshView.tsx`): kartu per relasi, peringatan staging ditimpa + kotak centang sebelum tombol aktif, kunci idempotensi per percobaan, progres dari fase capture/restore, "data per" waktu snapshot, tombol batal (nonaktif saat menimpa), pesan terpisah untuk capture_failed / restore_failed / recovery_required / blocked (dengan alasan) / expired / cancelled. Item rail "Refresh" untuk admin dan pemegang grant; yang hanya boleh refresh mendapat layar tunggal tanpa memuat query vault.
- Rehearsal nyata (data sintetis; PostgreSQL 14.25 prod + staging di Docker, hub dan agen nyata, jalur payload langsung karena `rest-server` tidak ada): refresh admin selesai; skema dan data staging identik dengan prod (dump tanpa baris `\restrict` cocok); staging yang berisi tabel dan baris asing kembali persis seperti prod. Relasi dihapus di tengah run -> `blocked: relation_ended`, staging tidak berubah (baris sentinel tetap). Relasi baru + run ulang -> selesai, sentinel hilang, baris baru prod muncul.
- Browser nyata (Keycloak 26.1, Vite -> hub): `qa` "No access yet" -> admin memberi grant relasi -> layar Refresh saja; centang + Overwrite -> progres -> selesai, staging terisi data prod terbaru; request jaringan hanya `refresh-relations`/`refresh-runs`, tanpa 403. Dari sesi QA: orbits/snapshots/capture-jobs/restore-jobs/relations/access (users, grants)/capture-profiles 403; POST restore-jobs 403; POST relations (body valid) 403; refresh dengan konfirmasi salah 409, tanpa CSRF 403, relasi tak dikenal 404; respons relasi hanya id, versi, nama, environment, usable. Grant dicabut -> UI kembali ke "No access yet" pada poll berikutnya. `dev` (viewer 1 orbit): 1 orbit, 7 snapshot, hanya tab Vault dan Activity; refresh, relasi, restore-jobs, access semuanya 403.
- Unduhan: dump PostgreSQL custom diunduh sebagai `.dump` apa adanya (sudah terkompresi, `PGDMP`, `pg_restore --list` valid); bungkus gzip hanya untuk SQL polos, sesuai desain M6a. Jadi "unduh .gz" berlaku untuk SQL, bukan untuk format custom.
- Belum diverifikasi: tampilan admin (item rail Refresh) di browser nyata; Restic via `rest-server` TLS (agen wajib `rest:https://`, tidak ada di mesin ini); `cargo deny`/`cargo audit` tidak terpasang di shell ini (tidak ada perubahan dependensi di M6d, hasil M6c tetap berlaku). 422 untuk body kosong pada POST non-admin hanyalah urutan parse sebelum gate; dengan body valid 403.
Di luar M6: approval per refresh, masking data, restore lokal developer, multi-hub. Kebijakan data mentah: izin eksplisit adalah grant `snapshot.download` itu sendiri (UI memberi peringatan); tidak ada flag klasifikasi tambahan kecuali Sen meminta.
## M7 — Rilis
Migrasi pada salinan DB nyata, rehearsal dengan IdP target, dokumentasi bootstrap admin dan rollback, review keamanan khusus auth.
## Di luar lingkup
Multi-tenant, multi-issuer, SCIM, device flow untuk CLI, manajemen password publik, policy engine generik, approval per refresh.
## Urutan dan dependensi
M0 → M1 → M2 → M3 → M4 → M5 → M6 → M7. M4 tidak bergantung pada M3 dan boleh dikerjakan paralel setelah M2.

View File

@@ -1,137 +0,0 @@
# Pilihan library dan tool untuk auth/self-service Tessera
Riset: 11 November 2026. Rekomendasi awal kini dilengkapi spike terisolasi dengan manifest/lockfile dan enam tes: [hasil A00](../tests/auth-compat/README.md). Tidak ada dependency auth/layanan baru pada runtime. A00 belum diterima karena audit dan verifikasi tersisa. Versi/features/MSRV/license serta temuan RustSec nyata dicatat di hasil tersebut. Rencana per milestone: [auth-plan.md](auth-plan.md) (rencana A00–A25 lama ada di archive/; label A-nomor di dokumen ini merujuk ke sana).
## Keputusan singkat
1. Pakai **openidconnect** untuk OIDC, bersama HTTP client yang didukung; jangan membuat OAuth/JWT/JWKS verifier sendiri.
2. Prioritaskan **tower-sessions** untuk sesi/cookie/rotasi. Tetap perlu storage adapter rusqlite dan aturan absolute timeout/revocation Tessera. Adopsi setelah compatibility spike, bukan menyalin API latest ke Axum 0.7.
3. Pakai **governor** untuk algoritma rate-limit, Tokio Semaphore untuk concurrency. tower_governor opsional bila versi middleware cocok.
4. Pakai **async-compression** untuk gzip asynchronous. flate2 alternatif jika pipeline akhirnya berupa synchronous artifact worker. Pilih satu jalur, bukan keduanya tanpa kebutuhan.
5. Evaluasi **Casbin embedded** untuk evaluasi permission, tetapi jangan mengganti model domain dengan policy string. Untuk scope tetap/sederhana, typed permission + query rusqlite yang ada tetap baseline terkecil. Tidak ada keputusan final Casbin sebelum tes policy/revocation.
6. Gunakan ulang **Restic, antrean/lease SQLite, provider DB, React Query, komponen UI, tracing dan utoipa** yang sudah ada.
7. Test tooling: **wiremock**, **Playwright Test**, dan **Keycloak sebagai IdP fixture**. Reuse IdP organisasi untuk deployment bila sudah ada; Keycloak bukan dependency produksi wajib.
8. **rusqlite_migration** layak untuk migrasi bernomor bila cocok versi SQLite binding. **cargo-deny/cargo-audit** untuk gate supply chain. Tidak mengganti rusqlite dengan ORM semata-mata demi satu adapter.
## Kondisi repo yang menentukan pilihan
- Cargo workspace: axum 0.7, tower 0.5, tower-http 0.6, rusqlite =0.31.0 bundled, tokio =1.40.0, argon2 =0.5.3, utoipa 4.2; image build Rust 1.88 (Dockerfile).
- Frontend: React 19, TanStack React Query 5, Vite 6, TypeScript 5.6. Komponen dan API client rumah sudah tersedia.
- Cargo.lock memuat subtle sebagai dependency transitif; openidconnect, reqwest, governor, tower-sessions, async-compression, flate2, wiremock belum ditemukan dalam lock saat riset.
- Restore provider sudah memakai executable gzip untuk membaca sebagian arsip; itu tidak otomatis berarti executable tersebut tersedia di seluruh instalasi hub/native.
- Tidak ada satu paket yang menggantikan seluruh auth/RBAC/restore. Library mengurangi kode protokol, algoritma dan transport; keputusan izin terhadap database production tetap milik aplikasi.
## Matriks setiap task
| Task | Library/tool yang dipakai atau dievaluasi | Keputusan dan pekerjaan Tessera yang tersisa |
| --- | --- | --- |
| A01 kontrak endpoint | utoipa + axum/tower::ServiceExt yang sudah ada [S15] | Reuse untuk kontrak/OpenAPI dan tes request; tetap tulis matriks aksi/resource, bukan menebak permission dari HTTP method. |
| A02 isolasi Outpost | rusqlite transactions/FK/unique constraints + identitas agent yang ada | Reuse. Tidak ada crate RBAC yang otomatis mengetahui pemilik orbit/upload. Simpan owner dan periksa di boundary init/chunk/seal. |
| A03 fail-closed/bootstrap | axum middleware dan deployment HTTPS yang ada | Reuse gate/startup config. Auth proxy hanya tambahan; jangan menggantikan backend authorization dengan trusted header tanpa trust boundary eksplisit. |
| A04 principal/audit | serde + tracing + SQLite audit [S14] | Reuse. tracing untuk diagnostics; audit durable perlu insert transaksi dan actor/resource/outcome yang didesain aplikasi. |
| A05 digest token | RustCrypto sha2/hmac + rand yang sudah ada; subtle direct [S7] | Reuse primitives. CSPRNG untuk token high-entropy, digest untuk lookup dan constant-time comparison untuk secret relevan. Tidak perlu JWT untuk token opaque. |
| A06 lifecycle token | primitives A05 + tabel/transaksi SQLite | Domain code kecil untuk rotate/revoke/expiry dan audit. Vault/IdP tidak otomatis mencabut token Outpost lokal. |
| A07 sesi | tower-sessions, custom rusqlite SessionStore [S2] | Kandidat utama; library mengelola lifecycle sesi. Adapter menyimpan digest ID dan record aman; absolute deadline, recent-auth, per-user revoke tetap aturan lokal. |
| A08 limiter/emergency | governor + Tokio Semaphore; Argon2id existing [S4,S7,S13] | Pakai algoritma standar. Key tepercaya, backoff akun, quota global, TTL cleanup dan audit tetap dikonfigurasi; state limiter lokal hanya cocok satu hub. |
| A09 OIDC | openidconnect + supported async HTTP client/reqwest [S1] | Rekomendasi adopsi. Discovery, PKCE dan ID-token verification dari library; transaksi callback/state, JWKS refresh strategy dan account mapping tetap integrasi aplikasi. |
| A10 login/logout UI | tower-sessions + redirect server + IdP existing/Keycloak fixture [S2,S9] | Reuse OperatorGate. Tidak perlu SDK OIDC React karena code flow dan token di backend. Logout lokal wajib; global/logout callback mengikuti dukungan IdP. |
| A11 RBAC scoped | Casbin embedded kandidat; typed gate + rusqlite baseline [S3] | Spike keduanya dengan matriks yang sama. Casbin dipilih bila mengurangi kode keseluruhan; cek relasi/environment/lease di domain tetap wajib. |
| A12 enforcement semua API | axum extractor/middleware + selected A11 gate | Reuse. Framework tidak memfilter row/list otomatis; per-resource scope dan safe output tetap di handler/query. |
| A13 admin grant/grup | selected A11 + IdP groups; React Query existing | UI mengelola grant Tessera, bukan membangun user directory atau password manager. Grup diverifikasi issuer dan mapping eksplisit. |
| A14 environment/target | core models + rusqlite + provider identity checks yang ada | Reuse dan perluas data model. Tidak perlu graph DB/ORM untuk binding orbit → restore target. |
| A15 relasi berarah | SQLite FK/unique + selected gate A11 | Domain code. OpenFGA alternatif ketika graph izin lintas banyak aplikasi benar-benar diperlukan, bukan untuk satu tabel relasi [S10]. |
| A16 wizard DevOps | komponen UI rumah + React Query existing | Reuse form/profile/target; jangan menambah admin framework/form framework hanya untuk wizard ini. |
| A17 run durable | existing job tables/transactions + idempotency constraint | Reuse. Apalis dapat mengelola background job tetapi tidak mengganti assignment agen/lease/domain state yang sudah ada [S11]. |
| A18 capture→restore | existing queue/worker + Restic snapshot spesifik [S12] | Reuse. Pin snapshot dan link child jobs secara transaksi; Temporal ditunda karena migrasi orchestration/service tambahan belum memberi manfaat [S11]. |
| A19 revoke/safety/recovery | existing restore lease/fencing/provider + gate A11 | Reuse. Library auth tidak dapat menjamin safe cancel setelah reset DB; state machine recovery tetap milik Tessera. |
| A20 UI QA | DatabaseRestore/JobHistory + React Query existing | Reuse polling/status; tidak perlu workflow designer atau state-machine UI library. Backend adalah sumber state persisten. |
| A21 kompresi | async-compression(tokio,gzip) + ReaderStream + tempfile existing [S5] | Adopsi gzip adapter. flate2 alternatif artifact blocking worker; jangan menggunakan HTTP CompressionLayer sebagai pengganti file .gz [S5,S6]. |
| A22 download developer | browser native download + existing API/catalog; Playwright [S8] | Tanpa file-saver/Blob buffer besar. Grant, pin, quota, lifetime temp dan audit tetap server-side. |
| A23 audit lengkap | tracing + audit SQLite yang ada; request IDs tower-http [S6,S14] | Reuse. Log observability bukan pengganti audit transaksi; redaksi dan event coverage harus diuji. |
| A24 migrasi/kontrak | rusqlite_migration kandidat; utoipa existing; cargo-deny/audit [S15,S16,S17] | Adopsi migration helper jika kompatibel dan lebih kecil dari runner lokal; jangan upgrade DB binding/ORM besar tanpa manfaat terukur. |
| A25 rehearsal/rollout | wiremock + Playwright Test + Keycloak fixture + harness MBU [S8,S9,S18] | Dev tools, bukan runtime wajib. Test IdP nyata, proxy, PostgreSQL/MySQL, revoke dan download; tidak menggantikan rollout rehearsal dengan unit test. |
## OIDC: openidconnect, bukan auth protokol buatan sendiri
Dokumentasinya menyediakan discovery, code flow dengan PKCE, typed token dan validator ID token. Pakai async client dan nonaktifkan HTTP redirect untuk discovery/token/JWKS request. Rekomendasi: openidconnect menjadi satu-satunya lapisan protokol OIDC; jangan menambahkan jsonwebtoken verifier paralel untuk token yang sama. [S1]
Tetap perlu: issuer config, callback URL statis, browser correlation sekali pakai, membership/grant, error redaction, kebijakan algorithm/claims, cache/refresh JWKS dan outage behavior. Dukungan fitur library tidak membuktikan flow aplikasi aman; uji misuse/replay.
Context7 resolve untuk openidconnect tidak menemukan paket yang relevan pada sesi ini; dokumentasi crate resmi dipakai sebagai fallback. Nomor versi di docs latest bukan pin implementasi.
## Sesi: tower-sessions dan biaya adapter
tower-sessions menawarkan SessionStore, expiry, cookie dan rotasi sesi. Gunakan implementasi create yang collision-safe. Prioritas integrasi: custom adapter terhadap koneksi/database rusqlite yang sudah ada; jangan menambah SQLx dan pool kedua hanya agar dapat memakai stock SQLite store. Adapter wajib diuji untuk concurrent request vs revoke agar sesi yang dihapus tidak hidup kembali. [S2]
Idle dan absolute timeout tidak otomatis menjadi satu kebijakan hanya dengan satu expiry option. Absolute auth deadline, auth_time dan status user tetap diperiksa di gate. Digest ID di key adapter tidak boleh dibatalkan dengan menserialisasi raw ID ke kolom record lain.
axum-login bukan OIDC provider/client dan tidak menyelesaikan scope resource. Changelog menyatakan 0.17 pindah ke Axum 0.8; tower-sessions 0.14 pindah ke axum-core 0.5. Karena repo Axum 0.7, jangan pin versi lama hanya karena bisa compile tanpa menilai security fixes. Spike membandingkan compatible maintained release/backport dengan upgrade Axum terpisah. [S2,S19]
## RBAC: Casbin vs scoped gate kecil
Casbin menyediakan evaluator RBAC dengan domain. Itu berguna bila tim memerlukan inheritance/custom roles/policy model yang berubah; enforcer embedded tidak memerlukan service OpenFGA. Namun casbin-rs tidak membundel SQL adapter di core; source-of-truth SQLite, reload/invalidation dan safe concurrent policy update tetap harus dirancang. [S3]
**Keputusan usulan saat ini:** pertahankan typed permission + SQL grants sebagai baseline untuk daftar aksi tetap dan relasi eksplisit. Jalankan spike Casbin sebelum implementasi A11; adopsi bila total kode evaluator+adapter+query filter+tests lebih kecil dan revokasi tetap konsisten. Tidak membuat engine policy generik sendiri.
Kriteria spike: seluruh matriks QA/developer/admin/service/outpost lulus, no-grant deny, relasi terbalik deny, filter daftar konsisten, revoke berlaku request berikutnya dan sebelum apply, tidak ada cache grant stale setelah mutation gagal. Resource label production dan safety identity tetap domain guard yang tidak dapat dibypass policy role admin.
OpenFGA cocok sebagai kandidat evolusi bila authorization menjadi graph bersama lintas layanan; menambah service/source-of-truth izin pada satu-hub MVP belum proporsional. Keputusan ini adalah penilaian kecocokan terhadap arsitektur Tessera, bukan kekurangan kemampuan OpenFGA. [S10]
## Limiter, CSRF, dan token
governor menghindari algoritma limiter buatan sendiri; tower_governor menyediakan integrasi request key. Jangan memakai SmartIpKeyExtractor secara buta di endpoint publik: proxy tepercaya harus menormalisasi sumber IP. Tokios semaphore membatasi operasi hash/export aktif; bukan pengganti durable per-target lock. [S4,S13]
Argon2id yang terpasang tetap digunakan untuk password. Token random high-entropy memakai digest sha2/hmac yang sudah ada; validasi equality memakai subtle yang ditambahkan sebagai dependency langsung jika diimpor. Tidak mengandalkan crate transitif tanpa deklarasi. CSRF synchronizer token dan OIDC state adalah dua kontrol terpisah; gunakan random generator dan constant-time primitive standar, bukan suite auth tambahan untuk beberapa baris glue. [S7]
## Job/capture/restore: gunakan yang sudah berjalan
Restic tetap untuk snapshot/export; provider pg_dump/pg_restore/mysql dan job/lease/fencing yang ada tetap dipakai. Tambahkan durable parent refresh run, bukan scheduler paralel. Apalis dan Temporal adalah alternatif nyata, tetapi migrasi akan menduplikasi atau mengganti queue, retry dan recovery yang sudah teruji. Evaluasi ulang hanya jika muncul distributed workers lintas hub, branching orchestration besar, atau operasi queue lokal menjadi beban nyata. [S11,S12]
Library umum tidak membuktikan restore aman. Verifikasi database identity, safety snapshot, retensi pin, idempotency dan pemeriksaan ulang grant sebelum apply tetap domain Tessera.
## Download: file terkompresi harus benar-benar sebuah arsip
Rekomendasi async-compression dengan fitur tokio dan gzip saja, membungkus reader lalu ReaderStream existing. Batasi concurrency CPU/disk; async I/O tidak menjamin kerja kompresi bebas beban CPU. flate2 cocok bila hasil dibuat oleh worker blocking lebih dahulu. [S5]
CompressionLayer tower-http mengompresi representasi HTTP dan bisa didekompresi oleh client; itu bukan kontrak attachment .sql.gz yang tersimpan sebagai gzip. Payload arsip, ekstensi, content type dan checksum harus selaras. Jangan menggandakan kompresi format yang sudah compressed tanpa alasan. [S6]
Tidak perlu download SDK frontend. Native download + cookie same-origin dan Playwright download assertion mencukupi. Cleanup stream/temp dan metadata filesize tetap diuji; bila ukuran gzip belum diketahui jangan mengirim Content-Length hasil uncompressed. [S8]
## Migrasi dan verifikasi dependency
rusqlite_migration memakai PRAGMA user_version untuk urutan migrasi. Cocok secara konsep, tetapi versinya erat dengan rusqlite dan MSRV; baseline schema existing harus ditandai dengan benar dan tidak boleh ada dua runner yang menguasai user_version. Jika memaksa upgrade bindings besar, tetap gunakan transaksi rusqlite dengan runner minimal yang sudah diaudit. [S16]
Sebelum dependency final dipilih:
- Catat versi, license, MSRV dan tanggal/advisory dari sumber resmi; verifikasi pada image Rust 1.88 yang dipakai repo atau buat task upgrade compiler tersendiri.
- cargo tree untuk memastikan tidak ada incompatible duplicate http/axum-core/tower traits atau dua libsqlite3-sys dengan links konflik. Compile workspace, bukan contoh hello-world saja.
- cargo-deny untuk licenses/sources/bans/advisories dan cargo-audit untuk RustSec. Hasil tanpa advisory bukan bukti kode aman. npm audit untuk dependency frontend/test yang baru. [S17]
- Feature minimal, lockfile committed saat implementasi, uji boundary dan bandingkan kode/infrastruktur yang benar-benar dihapus. Tidak memilih versi latest otomatis.
## Pengujian yang dipakai
wiremock untuk discovery/JWKS/token/error fixtures; response token harus menggunakan kunci test terkontrol agar invalid signature/nonce/issuer/replay benar-benar diuji. Mock HTTP bukan sertifikasi OIDC. Keycloak disposable membuktikan integrasi IdP lengkap dan Playwright membuktikan browser callback/cookie/native download; harness PostgreSQL/MySQL/Restic MBU dipakai ulang. [S8,S9,S18]
Tidak menambah Testcontainers, proptest atau framework UI baru sebelum harness yang ada terbukti tidak cukup. Testcontainers dapat dipertimbangkan terpisah bila lifecycle fixture shell menjadi sumber kegagalan; bukan prasyarat rilis ini.
## Sumber primer
- S1: [openidconnect crate](https://docs.rs/openidconnect/latest/openidconnect/).
- S2: [tower-sessions](https://github.com/maxcountryman/tower-sessions), [changelog](https://github.com/maxcountryman/tower-sessions/blob/main/CHANGELOG.md); juga di-query melalui Context7 /maxcountryman/tower-sessions.
- S3: [casbin-rs](https://github.com/apache/casbin-rs), [RBAC domains](https://casbin.apache.org/docs/rbac-with-domains/); juga di-query melalui Context7 /apache/casbin-rs.
- S4: [governor](https://docs.rs/governor/latest/governor/), [tower_governor](https://docs.rs/tower_governor/latest/tower_governor/).
- S5: [async-compression](https://docs.rs/async-compression/latest/async_compression/), [flate2](https://docs.rs/flate2/latest/flate2/).
- S6: [tower-http](https://docs.rs/tower-http/latest/tower_http/).
- S7: [subtle](https://docs.rs/subtle/latest/subtle/), [Argon2](https://docs.rs/argon2/latest/argon2/).
- S8: [Playwright downloads](https://playwright.dev/docs/downloads), [assertions](https://playwright.dev/docs/test-assertions).
- S9: [Keycloak OIDC endpoints](https://www.keycloak.org/securing-apps/oidc-layers).
- S10: [OpenFGA modeling](https://openfga.dev/docs/modeling/getting-started).
- S11: [Apalis](https://docs.rs/apalis/latest/apalis/), [Temporal architecture overview](https://docs.temporal.io/evaluate/understanding-temporal).
- S12: [Restic restore/export](https://restic.readthedocs.io/en/stable/050_restore.html).
- S13: [Tokio Semaphore](https://docs.rs/tokio/latest/tokio/sync/struct.Semaphore.html).
- S14: [tracing](https://docs.rs/tracing/latest/tracing/).
- S15: [utoipa](https://docs.rs/utoipa/latest/utoipa/).
- S16: [rusqlite_migration](https://docs.rs/rusqlite_migration/latest/rusqlite_migration/), [SQLite PRAGMA](https://www.sqlite.org/pragma.html#pragma_user_version).
- S17: [cargo-deny](https://embarkstudios.github.io/cargo-deny/), [RustSec/cargo-audit](https://rustsec.org/).
- S18: [wiremock Rust](https://docs.rs/wiremock/latest/wiremock/).
- S19: [axum-login changelog](https://github.com/maxcountryman/axum-login/blob/main/CHANGELOG.md).

View File

@@ -1,47 +0,0 @@
# Rencana upgrade Tessera dan agent untuk MBU
## Tujuan
Satu alur operator untuk backup dan restore database, dengan profil bertipe untuk variasi engine, jalur jaringan, dan kebijakan restore. Penerimaan mengacu pada inventaris dan kasus asli di [peta paritas MBU](../docs/MBU-BACKUP-PARITY.md). Implementasi dimulai dengan fixture terisolasi dan diakhiri dengan uji paralel sebelum peralihan produksi.
## Kontrak yang diusulkan
| Bagian | Keputusan |
| --- | --- |
| Profil aplikasi | ID aplikasi dan orbit stabil. Hub menyimpan pemetaan agent, profil, target yang diizinkan, jadwal, serta kebijakan retensi. Agent menyimpan konfigurasi koneksi dan referensi rahasia. Profil bertipe memisahkan engine, cara koneksi, format dump, dan mode restore. Manifest membawa metadata teknis yang aman. |
| Koneksi | PostgreSQL mendukung koneksi langsung dan tunnel SSH, dengan TLS eksplisit sesuai profil serta identitas server yang tetap diverifikasi ketika profil mewajibkannya. MySQL mendukung koneksi lokal/langsung dan eksekusi lewat SSH. Agent ditempatkan dekat database jika jalur jaringan mengizinkan. SSH memakai host key terdaftar dan identitas khusus. |
| Job | Hub mengantrekan job manual dan terjadwal di SQLite. Agent menarik job yang ditugaskan lewat koneksi keluar dan melaporkan fase, heartbeat, hasil, dan log yang disanitasi. Job memakai ID stabil, lease dengan identitas percobaan, dan slot jadwal unik. Job satu aplikasi diserialkan dan aplikasi lain bisa berjalan paralel. |
| Data backup | Gunakan ulang transfer Restic Wormhole dan katalog Tessera. Publikasikan restore point setelah dump selesai, artefak valid, dan penyimpanan terkonfirmasi. Simpan ukuran, waktu sumber, engine, format dan asal artefak. Bersihkan staging privat setelah kondisi terminal. Simpan salinan off-host di S3 dengan verifikasi pemulihan independen. |
| Restore | Hanya agent yang ditugaskan ke target terdaftar yang boleh menerima payload restore. Konfirmasi mengikat snapshot dan target. Validasi akses, format, integritas, identitas target, dan kapasitas sebelum perubahan. Target terkunci sampai hasil diketahui. Simpan dan verifikasi backup pengaman sebelum reset. Laporkan gangguan setelah reset sebagai pemulihan diperlukan sampai operator merekonsiliasi atau menggunakan backup pengaman. |
| Akses | Pisahkan identitas browser operator, token API/CLI, dan identitas agent. Scope upload dan klaim job per outpost dan tugas, serta scope baca payload restore ke job yang disetujui. Sesi browser membutuhkan proteksi CSRF untuk mutasi dan audit actor. Respons dan log mengecualikan kredensial. |
| Migrasi | Gunakan prefix/repository Tessera terpisah dari arsip lama selama uji paralel. Impor dari akses baca saja memakai identitas objek yang stabil serta simpan waktu sumber. Riwayat lama dapat dipertahankan sebagai arsip baca saja jika ID dan log dapat ditelusuri. |
Profil standar yang diuji mencakup PostgreSQL dengan TLS, PostgreSQL lewat tunnel, MySQL langsung dan SSH, PostgreSQL dengan reset schema atau recreate database, post-restore SQL yang disediakan lokal, dan aplikasi capture-only. Transformasi dump lama dibatasi ke kasus kompatibilitas yang dibuktikan pada fixture. Perintah bebas dari hub berada di luar kontrak. Capture, jalur transfer dan provider yang sudah ada tetap memiliki uji regresi.
## Dependensi dan urutan
1. **Identitas dan job capture pertama** — T01–T05. Tutup paparan rahasia, bangun antrean manual dan klaim yang terikat agent, lalu buktikan PostgreSQL dari hub sampai snapshot.
2. **Variasi capture dan penjadwalan** — T06–T11. Validasi placement dan jalur SSH pada MAS/FTA dan Boiler sedini mungkin. Jadwal dan histori bergantung pada jalur job yang telah berjalan.
3. **Katalog dan restore aman** — T12–T19. Verifikasi penyimpanan off-host dan retensi, kemudian akses payload per job, safety backup, PostgreSQL dan MySQL, serta penanganan gangguan.
4. **Alur browser dan pengambilalihan** — T20–T24. Sajikan alur yang sudah teruji, rekonsiliasi arsip, jalankan uji paralel, lalu tinjau peralihan.
Pekerjaan profil koneksi bisa dikerjakan independen setelah capture PostgreSQL langsung lulus. Pekerjaan restore menunggu kontrak akses payload dan safety backup. Daftar langkah, file perkiraan, dan checkpoint ada di [daftar tugas](todo.md).
## Risiko dan mitigasi
| Risiko | Mitigasi |
| --- | --- |
| Restore menimpa sumber atau target yang salah | Daftarkan target dengan identitas yang diverifikasi oleh agent, kredensial terbatas untuk target, tolak sumber/alias, dan ikat konfirmasi ke snapshot dan target. Simulasikan target salah serta safety backup gagal. |
| Lease putus setelah reset atau commit | Fencing mencegah laporan percobaan lama mengubah hasil. Job restore yang telah diberi izin masuk fase destruktif ditahan untuk rekonsiliasi jika hasil tidak diketahui. Commit capture bisa diulang berdasarkan ID job tanpa membuat restore point kedua. |
| Retensi menghapus snapshot yang masih diperlukan | Pin snapshot input dan backup pengaman sampai job dan pemulihan selesai. Terapkan kebijakan per orbit setelah capture sukses, dengan perlindungan minimal satu arsip pada mode umur. |
| Restore lintas versi sukses sebagian | Uji PostgreSQL dan MySQL dengan versi sumber/target MBU, izin realistis, owner/ACL, extension, view, DEFINER, routine, dan event. Filter hanya pola yang telah diverifikasi, lalu cocokkan schema dan data. |
| Rahasia bocor atau agent menyasar orbit lain | Uji token salah, lease kadaluarsa, redaksi log/JSON, izin staging, pemisahan repository, dan autentikasi perangkat. Tinjau penyimpanan kredensial lama sebelum paparan hub ke pengguna tambahan. |
| Backup gagal saat host mati atau repo rusak | Terapkan batas waktu, catat fase kegagalan, dan buktikan restore dari salinan off-host ketika hub/repo utama tidak tersedia. |
| Peralihan kehilangan histori atau backup terbaru | Inventaris ulang saat migrasi, rekonsiliasi identitas objek, ukuran, dan hitungan per aplikasi. Pertahankan layanan lama sebagai rollback sampai uji paralel dan restore lulus. |
## Hal yang perlu dikonfirmasi dari deployment
- Lokasi agent yang diizinkan, jalur jaringan nyata, dan versi client/server untuk `odoo_mas`, `odoo_fta`, dan `boiler`. Gunakan Teleport untuk inventaris, lalu fixture dengan topologi serupa untuk uji gagal.
- Endpoint dan izin S3 untuk salinan Tessera, batas bandwidth/ruang staging, serta periode uji paralel. Default untuk fixture adalah data sintetis, prefix terpisah, dan backup harian pukul 02.00 WIB.
- Kepemilikan tiga timer retensi host dan integrasi di luar katalog web. Evaluasi sebelum peralihan domain agar job eksternal tetap bisa berjalan.
- Uji produksi dan peralihan mengikuti persetujuan operasional atas target, window, dan rollback. Restore verifikasi memakai target sementara yang telah disetujui.

View File

@@ -1,12 +0,0 @@
# Rilis publik (ditahan)
Status: repo siap rilis, belum dirilis. Rilis hanya setelah paritas backup-center terbukti di environment MBU (sesi `tessera-mbu-swap`) dan Sen memberi go.
Sudah: rustfmt + `clippy -D warnings` bersih; README dan CHANGELOG diperbarui; SECURITY.md; CI (`.github/workflows/ci.yml`: fmt, clippy, test, cargo-deny/audit, web); kontrak endpoint dipindah ke `docs/`; `scripts/export-public.sh` membuat tree satu-commit tanpa `tasks/`, `tests/mbu`, dokumen MBU, dan memeriksa referensi privat. Tree hasil ekspor sudah dibuktikan ter-build dan lulus tes sendiri (hub 120, web 75).
Belum / keputusan Sen:
- Riwayat git (40 commit, memuat dokumen MBU dan email penulis) tidak ikut: repo publik dimulai dari tree ekspor sebagai satu commit.
- `cargo-deny` dan `cargo-audit` tidak terpasang di mesin ini; dijalankan oleh CI. `rsa` RUSTSEC-2023-0071 dikecualikan dengan alasan tertulis.
- M7: migrasi pada salinan DB nyata, rehearsal IdP target, dokumentasi bootstrap admin dan rollback, review keamanan khusus auth.
- Biner agent Linux dan image agent belum dipaketkan (Dockerfile hanya hub).
- Nama repo, kontak keamanan, dan versi final (0.1.0) ditentukan saat rilis.

View File

@@ -1,30 +0,0 @@
# Restore di dalam Vault (dibangun)
Keputusan Sen: tidak ada menu baru. Halaman Refresh dihapus; di detail snapshot tombol "Export file on hub" diganti
"Restore", modal restore mendapat selector restore point, lalu hitung mundur dan stepper.
## Alur
1. Klik orbit. 2. Capture bila ingin yang terbaru, atau klik snapshot yang ada. 3. Detail snapshot: tombol Restore
(nonaktif dengan teks "No restore point" bila admin belum membuat relasi). 4. Modal: selector Development/Staging bila
keduanya ada. 5. Begin restore -> hitung mundur 10 detik (Abort tidak mengirim apa pun) -> stepper Checking, Safety copy,
Applying, Completed (Abort masih bisa sampai Applying).
## Yang dibangun
- Izin: tanpa skema baru. Melihat snapshot dan menekan Capture memakai grant orbit yang sudah ada (viewer + capture.run);
Restore memakai grant relasi `refresh.run` yang sudah ada. Pemegang hanya grant relasi tidak lagi punya layar sendiri.
- `POST /api/v1/refresh-runs` menerima `snapshot_id`: restore snapshot yang sudah ada milik orbit sumber relasi (bukan
safety, bukan orbit lain), memakai mesin run yang sama (idempotensi, satu run per target, batal sampai applying,
otorisasi ulang sebelum menimpa). Tanpa `snapshot_id` perilaku lama (capture baru) tetap ada sebagai API.
- `GET /api/v1/refresh-relations` memuat `source_orbit_id`; `GET /api/v1/snapshots` memuat `kind` (capture|safety); UI
menyembunyikan safety.
- Admin: modal yang sama, plus "Other registered target..." (jalur lama dengan ketik konfirmasi).
- Dihapus dari UI: halaman Refresh, layar khusus pemegang refresh, "Export file on hub".
## Belum dikerjakan
- Endpoint `POST /api/v1/reconstitute` (export ke berkas hub) masih ada sebagai API admin: CLI dan fixture `tests/mbu`
masih memakainya. Hapus (beserta folder exports) sebagai keputusan terpisah sebelum rilis publik.
- "Restore ke dua target sekaligus" dilakukan sebagai dua restore berurutan oleh orang yang sama (modal tetap terbuka
setelah selesai: "Restore again" / ganti restore point). Belum ada tombol "keduanya" sekali klik.

View File

@@ -1,36 +0,0 @@
# Rencana implementasi pencarian Tessera
## Pengalaman pengguna
Tombol **Search** dan `⌘K` / `Ctrl+K` membuka kolom pencarian di tengah bagian atas layar, dengan fokus langsung ke input. Panel ringkas menampilkan pintasan layar saat kolom kosong. Saat pengguna mengetik, panel menyesuaikan tinggi dan menampilkan hasil yang dikelompokkan sebagai **Navigation**, **Orbits**, dan **Snapshots**. Tombol panah memindahkan sorotan, `Enter` membuka hasil, dan `Esc` menutup pencarian. Setiap hasil juga bisa dipilih dengan klik atau sentuhan.
Pola hasil yang muncul saat mengetik dan navigasi papan ketik mengikuti [Spotlight di Mac](https://support.apple.com/en-gb/guide/mac-help/-mchlp1008/mac) dan [pintasan Spotlight](https://support.apple.com/en-gb/guide/mac-help/mh26783/26/mac/26). Gunakan `⌘K` / `Ctrl+K` karena `⌘Space` digunakan Spotlight macOS.
## Keputusan desain
- Gunakan warna gelap dan aksen amber Tessera, kaca tipis pada panel, ikon garis, serta font mono untuk pintasan dan metadata. Tempatkan pemicu di sisi kanan topbar dan pertahankan aksesnya saat topbar beralih ke Big Screen. Di layar sempit, gunakan pemicu ikon berlabel aksesibel dan batasi tinggi daftar terhadap viewport dinamis agar hasil dapat digulir.
- Gunakan `uiSpring` untuk buka/tutup dan `gentleSpring` untuk perubahan tinggi, dengan posisi atas panel tetap. Pertahankan identitas panel dan nilai animasinya ketika target berubah. Perubahan tinggi mengikuti isi dan batas viewport. Saat keluar, panel langsung melepas area klik dan fokus. Mode reduced motion menerapkan target secara langsung, termasuk saat preferensi berubah di tengah animasi. Ikuti [panduan animasi Tessera](../docs/UI.md#animation-guideline).
- Gunakan metadata navigasi yang sama dengan HUDRail dan data orbit/snapshot yang sudah diambil oleh `App`. Cari nama, ID, provider orbit, dan tanggal snapshot yang ditampilkan. Cocokkan tanpa membedakan kapitalisasi, urutkan kecocokan persis lalu awalan lalu substring dalam tiap kelompok, dan batasi tampilan ke delapan hasil dengan akses yang tetap tersedia untuk setiap kategori yang cocok. Untuk kecocokan snapshot setara, tampilkan yang terbaru dulu. Gunakan ID stabil agar polling tidak memindahkan pilihan aktif jika hasilnya masih tersedia.
- Gunakan handler yang sudah ada untuk membuka layar, memilih orbit di Vault, dan membuka Snapshot detail. Outposts dan Restore muncul sebagai tujuan navigasi. Pencarian tahap awal mencakup metadata ringkasan orbit dan snapshot, dengan status jika salah satu sumber masih dimuat atau gagal. Pemilihan hasil membuka tujuan tanpa menjalankan operasi backup atau restore.
- Buat dialog berlabel dengan latar inert dan fokus Tab yang tetap di dalam dialog. Gunakan combobox/listbox dengan `aria-activedescendant`, status hasil, dan tombol tutup. Kembalikan fokus ke pemicu saat dibatalkan atau arahkan ke tujuan saat hasil dibuka. Abaikan tombol navigasi pencarian selama komposisi IME. [Pola combobox WAI-ARIA](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) · [Pola dialog modal WAI-ARIA](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/)
## Urutan pekerjaan
1. Buka pencarian dan navigasi ke layar yang sudah ada.
2. Temukan dan buka orbit atau snapshot dari data yang sudah tersedia.
3. Selesaikan transisi panel dan verifikasi interaksi di browser.
Kriteria penerimaan, dependensi, dan checkpoint ada di [daftar tugas](search-todo.md).
## Risiko dan mitigasi
| Risiko | Mitigasi |
| --- | --- |
| Escape menutup pencarian dan HUDPanel atau Big Screen sekaligus | Tangani Escape saat pencarian aktif sebelum listener yang ada. Cegah pengulangan tombol ikut menutup lapisan di bawahnya. Uji dari kedua mode. |
| Fokus hilang saat hasil membuka panel atau orbit yang sebelumnya inert | Pindahkan fokus setelah tujuan aktif. Gunakan register atau kontrol Vault yang terlihat di Big Screen, dan heading panel saat membuka snapshot atau konsol. |
| Polling menghapus atau menggeser hasil | Simpan pilihan berdasarkan ID. Gunakan hasil pertama jika pilihan hilang dan abaikan Enter bila daftar kosong. |
| Animasi meloncat saat query berubah cepat atau panel dibuka kembali | Retarget panel yang sama. Uji pembalikan sebelum transisi selesai, resize, dan perubahan preferensi reduced motion saat aplikasi berjalan. |
## Asumsi untuk ditinjau
Pencarian berlaku di seluruh UI, memakai label berbahasa Inggris sesuai antarmuka saat ini, dan memakai data yang sudah tersedia di klien. Tinjau cakupan ini dan urutan pekerjaan sebelum implementasi.

View File

@@ -1,71 +0,0 @@
# Daftar tugas pencarian Tessera
## Tugas 1 — Buka pencarian dan pilih tujuan navigasi
Hubungkan komponen pencarian global ke `App`, dengan entri navigasi yang memakai label dan tujuan yang sama dengan HUDRail.
**Kriteria penerimaan**
- [x] Search dan `⌘K` / `Ctrl+K` membuka panel dari Vault, konsol samping, dan Big Screen. Input langsung menerima fokus.
- [x] Query kosong menampilkan tujuan navigasi. Mengetik menyaringnya, panah atas/bawah memindahkan pilihan, dan Enter, klik, atau sentuhan membuka tujuan yang benar.
- [x] Tab tetap di dalam dialog. Escape, tombol tutup, dan klik di luar mengembalikan fokus. Escape pertama hanya menutup pencarian dan menahan Escape tidak menutup lapisan berikutnya.
**Verifikasi**
- [x] Jalankan `npm run typecheck` dari `web/`. Uji pembukaan, perpindahan fokus, pembatalan, dan pemilihan tujuan di Vault, HUDPanel, serta Big Screen dengan papan ketik dan pointer.
**Dependensi** — Tidak ada.
**Perkiraan lingkup** — M, 4 berkas. `web/src/App.tsx`, `web/src/components/hud/HUDRail.tsx`, `web/src/components/hud/VaultSearch.tsx`, `web/src/index.css`.
## Tugas 2 — Temukan orbit dan snapshot
Tambahkan hasil dari data orbit dan snapshot yang dipakai Vault. Kaitkan pilihan ke alur inspeksi yang sudah tersedia.
**Kriteria penerimaan**
- [x] Hasil muncul saat mengetik, dikelompokkan berdasarkan tipe, dan mengikuti urutan kecocokan di rencana. Nama duplikat bisa dibedakan dengan metadata. Query kosong, tanpa hasil, dan sumber yang belum tersedia punya tampilan yang berbeda.
- [x] Memilih orbit membuka Vault dengan orbit terpilih, termasuk orbit di luar 55 slot awal. Memilih snapshot membuka detail yang benar, termasuk ringkasan dari hub lama tanpa `orbit_id`.
- [x] Papan ketik tetap berfungsi setelah polling memperbarui atau menghapus hasil. Enter tanpa hasil dan selama komposisi IME tidak mengaktifkan tujuan.
**Verifikasi**
- [x] Jalankan `npm run typecheck` dan `npm test` dari `web/`. Tambahkan uji matcher terfokus untuk prioritas, nama duplikat, hasil lintas kategori, dan batas jumlah. Uji pilihan orbit dan snapshot di browser dengan fixture.
**Dependensi** — Tugas 1.
**Perkiraan lingkup** — M, maksimal 5 berkas. `web/src/App.tsx`, `web/src/components/hud/VaultSearch.tsx`, `web/src/lib/vaultSearch.ts`, `web/scripts/search.test.mjs`, `web/package.json`.
## Checkpoint — Pencarian dapat digunakan
- [x] Typecheck, tes web, dan build lulus. Pengguna bisa membuka ketiga jenis hasil dari awal sampai akhir.
- [x] Review cakupan dan perilaku pencarian sebelum menyelesaikan animasi.
## Tugas 3 — Selesaikan animasi dan tata letak
Gunakan spring Tessera untuk transisi panel, serta dokumentasikan pintasan dan cakupan hasil pada panduan UI.
**Kriteria penerimaan**
- [x] Panel masuk dan keluar pada lintasan yang sama. Tinggi daftar menyesuaikan hasil dari posisi visual saat ini, sementara input tetap pada posisi dan fokusnya. Buka kembali sebelum panel selesai menutup tanpa lompatan atau penguncian input.
- [x] Reduced motion meniadakan perjalanan animasi. Di layar sempit dan saat papan ketik virtual terbuka, input dan tombol tutup tetap terjangkau serta daftar dapat digulir tanpa overflow horizontal.
- [x] Saat penutupan dimulai, panel keluar dari urutan fokus dan melepas area klik. Sorotan papan ketik terbaca dan pilihan aktif diumumkan melalui semantik combobox.
**Verifikasi**
- [x] Jalankan `npm run typecheck`, `npm test`, dan `npm run build` dari `web/`. Uji buka-tutup-buka, pengetikan cepat, perubahan preferensi reduced motion, viewport sempit, dan fokus di browser. Periksa nama dialog, combobox, daftar, dan pilihan aktif melalui accessibility tree.
**Dependensi** — Tugas 2.
**Perkiraan lingkup** — M, 3 berkas. `web/src/components/hud/VaultSearch.tsx`, `web/src/index.css`, `docs/UI.md`.
## Checkpoint — Siap ditinjau
- [x] Kriteria seluruh tugas lulus, hasil verifikasi browser tercatat, dan perubahan pada berkas yang sedang dikerjakan pengguna tetap terjaga.
## Hasil verifikasi — 10 November 2026
- `npm run typecheck`, `npm test` (10 tes), `npm run build`, dan `git diff --check` lulus.
- Fixture Chromium dengan 62 orbit menguji kedua pintasan, fokus dan Tab, pembatalan, Escape yang ditahan, orbit di luar 55 slot awal, snapshot tanpa `orbit_id`, polling, IME, dan ketiga jenis tujuan. Fixture mencatat nol permintaan tulis.
- Chromium memverifikasi buka-tutup-buka, pengetikan cepat, perubahan reduced motion, serta nama dialog, combobox, listbox, dan opsi aktif melalui accessibility tree.
- Emulasi sentuhan pada viewport 320 × 240 memverifikasi input, tombol tutup, daftar yang dapat digulir, dan tap pada hasil. Ukuran tersebut menyimulasikan ruang saat keyboard virtual terbuka.

View File

@@ -1,472 +0,0 @@
# Daftar tugas upgrade Tessera dan agent untuk MBU
Lihat [rencana implementasi](plan.md) dan [inventaris paritas](../docs/MBU-BACKUP-PARITY.md). Path pendek `api/`, `db.rs`, `admin.rs`, `state.rs`, dan `scheduler.rs` mengacu pada `crates/tessera-hub/src/`. Nama file baru bersifat perkiraan. Harness fixture PostgreSQL, MySQL, SSH, dan S3 diperluas pada tugas pertama yang memerlukan masing-masing fixture.
## Bukti implementasi
- Fixture lokal dan browser dicatat di [harness MBU](../tests/mbu/README.md). Checklist bertanda selesai merujuk pada pengujian terisolasi.
- T06 menunggu akun OS Teleport yang diizinkan untuk konfirmasi versi dan placement. Inventaris resource dan matriks fixture sudah dicatat.
- T23 telah direkonsiliasi dengan PostgreSQL, MySQL, dan histori SQLite sintetis. Persetujuan dan pengujian sampel arsip MBU asli masih terbuka.
- T24 mencatat hasil rehearsal 10 aplikasi dan drill pemulihan lokal di [runbook cutover](../docs/MBU-CUTOVER.md). Bukti uji paralel, rekonsiliasi delta, drill routing di staging MBU, dan persetujuan operator masih terbuka.
Pada setiap checkpoint, jalankan `rtk cargo test --workspace`, `rtk cargo test -p tessera-store -- --ignored` dengan Restic di PATH, dan `rtk cargo build --workspace`. Untuk perubahan UI, tambahkan `rtk proxy npm --prefix web test`, `rtk proxy npm --prefix web run typecheck`, `rtk proxy npm --prefix web run build`, serta verifikasi browser pada alur yang berubah.
## T01 — Redaksi konfigurasi orbit
Pisahkan representasi internal orbit dari respons publik API dan skema OpenAPI.
**Kriteria penerimaan**
- [x] GET dan POST orbit tidak mengembalikan DSN, password, token, atau referensi rahasia internal.
- [x] Orbit lama tetap dapat dijalankan. Uji kontrak memeriksa respons dengan kredensial sintetis dan alur UI/CLI yang membaca orbit.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub` dan `rtk cargo build --workspace`.
**Dependensi** — Tidak ada.
**Perkiraan lingkup** — M. `api/routes.rs, db.rs`, `web/src/api.ts`, `crates/tessera-cli/src/main.rs`.
## T02 — Antrekan capture manual
Tambahkan job capture persisten yang bisa dibuat dan dibaca operator dengan ID aplikasi dan status.
**Kriteria penerimaan**
- [x] API menyimpan job dan actor. Profil atau outpost tak terdaftar ditolak.
- [x] Restart hub mempertahankan job queued. Migrasi membuka salinan SQLite lama tanpa kehilangan orbit.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub` dan `rtk cargo build --workspace`.
**Dependensi** — Tidak ada.
**Perkiraan lingkup** — M. `api/mod.rs, api/jobs.rs, db.rs`, `crates/tessera-core/src/job.rs`.
## T03 — Klaim job oleh agent
Bangun polling keluar dari agent dengan assignment, lease, heartbeat, dan laporan fase.
**Kriteria penerimaan**
- [x] Token outpost lain dan lease usang tidak bisa klaim atau menulis hasil. Satu aplikasi menjalankan satu job dan dua aplikasi dapat berjalan paralel.
- [x] Lease capture kedaluwarsa dapat dicoba ulang. Uji dua agent dan restart hub di tengah job.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent` dan `rtk cargo build --workspace`.
- [x] Dua agent fixture berlomba untuk job yang sama. Hanya assignment dan lease aktif yang diterima.
**Dependensi** — T02.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs`, `crates/tessera-core/src/job.rs`, `crates/tessera-agent/src/{main,jobs}.rs`.
### Checkpoint setelah T03
- [x] Hub menerima job manual dengan assignment dan lease yang teruji.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T04 — Buat dump PostgreSQL di agent
Pakai ulang provider PostgreSQL untuk profil lokal bertipe dengan rahasia, kebijakan TLS, timeout, dan file staging privat.
**Kriteria penerimaan**
- [x] Fixture PostgreSQL dengan TLS menghasilkan dump yang bisa dibaca dan berisi data yang diharapkan. TLS yang salah dan dump parsial menghasilkan job gagal.
- [x] Rahasia sintetis tidak muncul di argumen proses, respons, atau log. File sementara dibersihkan setelah gagal.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T03.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/postgres.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`.
## T05 — Publikasikan snapshot database
Hubungkan hasil capture ke upload Restic Wormhole dan katalog berisi metadata engine/format serta ID job.
**Kriteria penerimaan**
- [x] Job manual menghasilkan satu restore point yang bisa diekspor dan dipulihkan di PostgreSQL sementara.
- [x] Putuskan koneksi setelah upload dan setelah commit. Retry mengembalikan snapshot yang sama. Upload parsial dan commit dari outpost lain tidak terpublikasi.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent -p tessera-store` dan `rtk cargo build --workspace`.
- [x] PostgreSQL sementara → agent → Restic → ekspor → restore ke database kedua. Bandingkan skema dan isi.
**Dependensi** — T04.
**Perkiraan lingkup** — M. `api/routes.rs, api/jobs.rs`, `crates/tessera-agent/src/{jobs,main}.rs`, `crates/tessera-store/src/vault.rs`.
### Checkpoint setelah T05
- [x] PostgreSQL langsung menghasilkan satu snapshot meski commit diulang.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T06 — Petakan placement agent MBU
Inventaris read-only dari Teleport untuk pilihan lokasi agent dan buat fixture topologi yang dapat diulang.
**Kriteria penerimaan**
- [ ] Catat jalur direct atau SSH yang tersedia, versi engine dan client, serta kebutuhan izin untuk MAS, FTA, dan Boiler tanpa mencatat rahasia.
- [x] Fixture dapat memodelkan jalur yang tersedia dan jalur yang sengaja terputus.
**Verifikasi**
- [ ] Cocokkan inventaris Teleport dengan matriks fixture dan catat keputusan placement.
**Dependensi** — T05.
**Perkiraan lingkup** — S. `docs/MBU-BACKUP-PARITY.md`, `tests/mbu/README.md`.
## T07 — Capture PostgreSQL lewat bastion
Tambahkan transport tunnel bertipe dengan host key pinning dan port lokal yang terisolasi.
**Kriteria penerimaan**
- [x] Fixture MAS dan FTA menghasilkan snapshot melalui bastion. Host key salah, timeout, dan kehilangan tunnel menggagalkan job serta membersihkan proses.
- [x] Aplikasi capture-only seperti FTA tetap bisa backup tanpa target restore.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T05, T06.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{postgres,ssh}.rs`, `crates/tessera-agent/src/{profiles,jobs}.rs`.
## T08 — Capture MySQL langsung
Tambahkan adapter dump MySQL bertipe, kredensial lokal, dan integrasi metadata snapshot yang sama.
**Kriteria penerimaan**
- [x] Dump fixture berisi view, routine, dan event. Error engine menggagalkan job dan tidak memublikasikan snapshot.
- [x] Uji dump MySQL dengan data utf8mb4 dan kredensial fixture yang tidak muncul di log.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T05, T06.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{lib,mysql}.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`.
### Checkpoint setelah T08
- [x] Bastion PostgreSQL dan MySQL langsung lulus dengan data fixture.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T09 — Capture MySQL lewat SSH
Jalankan dump melalui SSH yang dipin untuk topologi Boiler dan alirkan hasil ke staging agent.
**Kriteria penerimaan**
- [x] Topologi Boiler menghasilkan snapshot yang dapat diekspor. Host key berubah atau proses remote gagal tidak menghasilkan snapshot.
- [x] Jalur lokal dan remote menghasilkan metadata engine/format yang bisa dibaca dengan kontrak yang sama.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
- [x] Gunakan fixture MySQL di balik SSH dengan host key benar dan salah. Validasi output serta status terminal.
**Dependensi** — T07, T08.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{mysql,ssh}.rs`, `crates/tessera-agent/src/{profiles,jobs}.rs`.
## T10 — Jadwalkan job capture
Hub membuat job dengan slot jadwal persisten dan zona waktu per profil.
**Kriteria penerimaan**
- [x] Jadwal 02.00 Asia/Jakarta membuat satu job per slot yang jatuh tempo. Restart atau tick ganda tidak membuat duplikat.
- [x] Agent offline mempertahankan job queued. Uji dengan jam fixture untuk jadwal terlewat dan dua aplikasi yang jatuh tempo bersamaan.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub` dan `rtk cargo build --workspace`.
**Dependensi** — T05.
**Perkiraan lingkup** — M. `scheduler.rs, db.rs, api/jobs.rs`, `crates/tessera-core/src/job.rs`.
## T11 — Sajikan histori dan log job
Sediakan riwayat status dan log fase melalui API operator dengan redaksi dan batas ukuran.
**Kriteria penerimaan**
- [x] Filter aplikasi dan status stabil setelah restart. Job gagal menampilkan fase dan penyebab operasional yang tersanitasi.
- [x] Payload berisi rahasia sintetis, token, dan karakter kontrol tidak bocor ke daftar, detail, atau audit.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T03, T05.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs`, `crates/tessera-agent/src/jobs.rs`.
### Checkpoint setelah T11
- [x] Tiga jalur capture MBU dapat dijadwalkan dan ditelusuri.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T12 — Pulihkan dari salinan S3
Tambahkan jalur penyimpanan off-host yang dapat diverifikasi dengan pemulihan independen.
**Kriteria penerimaan**
- [x] Snapshot agent tersalin ke lokasi S3 terisolasi dan dapat dipulihkan saat repo utama tidak tersedia.
- [x] Gagal menulis salinan terlihat di status. Retry tidak menduplikasi entri katalog dan kredensial S3 tidak bocor.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-store -p tessera-hub` dan `rtk cargo build --workspace`.
- [x] Putuskan akses repo utama dan pulihkan snapshot hanya dari salinan off-host.
**Dependensi** — T05.
**Perkiraan lingkup** — M. `crates/tessera-store/src/{restic,vault}.rs`, `crates/tessera-hub/src/{state,main}.rs`, `compose.yaml`.
## T13 — Kelola lifecycle arsip
Terapkan retensi berdasarkan umur dan jumlah, serta unduh dan hapus terotorisasi di katalog.
**Kriteria penerimaan**
- [x] Kebijakan 14 hari menyisakan minimal satu per aplikasi. Fallback simpan lima dan retensi GFS lulus uji.
- [x] Unduh mengirim artefak yang benar, penghapusan diaudit, dan snapshot yang masih dipakai job tidak dapat dihapus.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-core -p tessera-store -p tessera-hub` dan `rtk cargo build --workspace`.
**Dependensi** — T05, T12.
**Perkiraan lingkup** — M. `crates/tessera-core/src/decay.rs`, `crates/tessera-store/src/vault.rs`, `api/routes.rs, api/jobs.rs, state.rs`.
### Checkpoint setelah T13
- [x] Katalog lulus pemulihan off-host dan retensi per aplikasi.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T14 — Antrekan restore terotorisasi
Daftarkan target per aplikasi dan buat job restore yang mengikat konfirmasi ke snapshot, target, dan agent.
**Kriteria penerimaan**
- [x] Target asing, capture-only, mismatch engine, dan konfirmasi salah ditolak sebelum lease.
- [x] Snapshot dipin secara persisten selama job. Scope token restore hanya berlaku untuk agent dan job itu.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-core` dan `rtk cargo build --workspace`.
**Dependensi** — T03, T13.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs, api/mod.rs`, `crates/tessera-core/src/{job,reconstitute}.rs`.
## T15 — Kirim payload restore ke target
Beri agent jalur baca terbatas untuk mengambil dan memverifikasi artefak snapshot ke staging privat.
**Kriteria penerimaan**
- [x] Agent yang ditugaskan bisa membaca snapshot yang dipilih. Token capture, snapshot lain, dan lease kedaluwarsa ditolak.
- [x] Artefak rusak atau staging penuh gagal sebelum target tersentuh. Uji dengan checksum yang sengaja salah.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent -p tessera-store` dan `rtk cargo build --workspace`.
**Dependensi** — T14.
**Perkiraan lingkup** — M. `api/jobs.rs`, `crates/tessera-store/src/vault.rs`, `crates/tessera-agent/src/{jobs,http}.rs`.
## T16 — Verifikasi backup pengaman
Agent memverifikasi identitas target dan menyimpan dump pengaman sebelum fase destruktif diizinkan.
**Kriteria penerimaan**
- [x] Verifikasi target menolak endpoint sumber, alias, dan target yang berubah sejak didaftarkan. Job paralel ke target yang sama menunggu.
- [x] Kegagalan backup atau commit pengaman membuat data target tetap utuh. Snapshot pengaman tercatat, dapat dibaca, dan dipin sebelum reset.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent` dan `rtk cargo build --workspace`.
- [x] Paksa penyimpanan safety backup gagal dan bandingkan data target sebelum serta sesudah job.
**Dependensi** — T15.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`, `crates/tessera-core/src/job.rs`.
### Checkpoint setelah T16
- [x] Restore request, akses artefak, dan safety backup lulus uji negatif.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T17 — Pulihkan PostgreSQL ke target
Tambahkan apply PostgreSQL untuk custom dump dan SQL polos terkompresi dengan reset schema atau recreate database serta SQL pascarestore lokal.
**Kriteria penerimaan**
- [x] Fixture LTI/Manbu, Daily Checklist, dan MAS memverifikasi isi, schema, reset, dan post-restore SQL pada target sementara.
- [x] Uji owner/ACL, transaction_timeout, dan pg_stat_statements dengan fixture lintas versi. Error di luar aturan kompatibilitas tetap terlihat.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T07, T16.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{lib,postgres,postgres_restore}.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`.
## T18 — Pulihkan MySQL ke target
Tambahkan apply MySQL untuk target lokal atau SSH dengan aturan kompatibilitas per profil.
**Kriteria penerimaan**
- [x] Fixture Boiler staging memverifikasi schema, isi, view, DEFINER, routine, dan event setelah restore.
- [x] Uji dengan izin target terbatas dan kegagalan apply yang dilaporkan bersama ID backup pengaman.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T09, T16.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{mysql,mysql_restore,ssh}.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`.
## T19 — Tangani restore yang terputus
Jadikan transisi ke fase destruktif dan status pemulihan persisten, dengan jalur rekonsiliasi atau restore safety snapshot.
**Kriteria penerimaan**
- [x] Putus koneksi atau restart setelah izin reset menahan target dalam status pemulihan diperlukan. Percobaan lama tidak boleh mulai apply kedua.
- [x] Operator dapat memulihkan dari snapshot pengaman, memverifikasi data target, lalu melepas lock dengan jejak audit.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent` dan `rtk cargo build --workspace`.
- [x] Putuskan koneksi tepat setelah reset, restart hub, lalu pulihkan target dari safety snapshot.
**Dependensi** — T17, T18.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs`, `crates/tessera-core/src/job.rs`, `crates/tessera-agent/src/jobs.rs`.
### Checkpoint setelah T19
- [x] PostgreSQL dan MySQL dipulihkan ke target sementara dan dapat pulih setelah gangguan.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T20 — Masuk ke dashboard sebagai operator
Tambahkan sesi browser ke dashboard dan audit actor dengan proteksi CSRF, tetap dukung token API/CLI.
**Kriteria penerimaan**
- [x] Login/logout, kedaluwarsa sesi, proteksi CSRF, dan identitas audit teruji di browser. Token admin tidak disimpan di browser.
- [x] Hub bertoken tetap menerima CLI yang sah. Browser tanpa sesi tidak bisa membaca atau menjalankan operasi sensitif.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub` dan `rtk cargo build --workspace`, ditambah tes/build web dan uji browser.
**Dependensi** — T01.
**Perkiraan lingkup** — M. `admin.rs, api/mod.rs, api/session.rs`, `web/src/App.tsx, web/src/api.ts`.
## T21 — Jalankan backup dari dashboard
Tampilkan aplikasi, snapshot, status dan log job, serta tindakan backup, unduh, dan hapus dari UI.
**Kriteria penerimaan**
- [x] Di browser, pilih aplikasi, jalankan backup, lihat fase/log, unduh artefak yang benar, lalu hapus fixture dengan konfirmasi.
- [x] Filter histori, kondisi kosong, job gagal, dan backup pada aplikasi tanpa target bisa diuji dari UI.
**Verifikasi**
- [x] Jalankan tes dan build web, lalu uji kriteria di browser dengan fixture.
**Dependensi** — T11, T13, T20.
**Perkiraan lingkup** — M. `web/src/{api.ts,App.tsx,components/orbits/OrbitsView.tsx,components/vault/SnapshotSheet.tsx,components/orbits/JobHistory.tsx}`.
## T22 — Jalankan restore dari dashboard
Hubungkan wizard ke target yang diizinkan, konfirmasi, status safety backup, dan hasil pemulihan.
**Kriteria penerimaan**
- [x] Browser dapat memilih snapshot dan target, mengonfirmasi, memantau job, dan melihat ID backup pengaman jika apply gagal.
- [x] Restore ditolak untuk aplikasi capture-only. Jalur ekspor filesystem yang lama tetap berfungsi.
**Verifikasi**
- [x] Jalankan tes dan build web, lalu uji kriteria di browser dengan fixture.
**Dependensi** — T19, T20.
**Perkiraan lingkup** — M. `web/src/api.ts`, `web/src/components/reconstitute/ReconstituteWizard.tsx`, `web/src/components/vault/SnapshotSheet.tsx`, `docs/UI.md`.
### Checkpoint setelah T22
- [x] Operator bisa masuk, backup, dan restore melalui browser.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T23 — Rekonsiliasi arsip layanan lama
Tambahkan impor read-only objek SQL lama dan pertahankan akses ke histori operasional yang terkait.
**Kriteria penerimaan**
- [x] Inventaris per aplikasi merekonsiliasi identitas, tanggal, ukuran, dan hitungan. Pengulangan impor tidak membuat duplikat dan histori lama dapat ditelusuri.
- [ ] Sampel arsip PostgreSQL dan MySQL yang disetujui berhasil dipulihkan pada target sementara. Uji retensi tidak menghapus objek dari sumber.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-cli -p tessera-store` dan `rtk cargo build --workspace`.
**Dependensi** — T12, T13, T19.
**Perkiraan lingkup** — M. `crates/tessera-cli/src/{main,legacy_import}.rs`, `crates/tessera-store/src/vault.rs`, `tests/mbu/README.md`.
## T24 — Buktikan kesiapan peralihan
Jalankan matriks 10 aplikasi secara paralel, dokumentasikan pemulihan off-host dan runbook peralihan/rollback.
**Kriteria penerimaan**
- [ ] Backup manual dan jadwal MBU, pemulihan target sementara, serta skenario failure lulus. Ukur freshness, durasi, ukuran dan kemampuan pemulihan off-host.
- [ ] Rekonsiliasi delta sejak impor dan pastikan kepemilikan job di luar katalog. Operator meninjau hasil, window peralihan, dan kriteria rollback sebelum penggantian domain.
**Verifikasi**
- [ ] Jalankan verifikasi checkpoint dan simpan hasil matriks staging serta uji pemulihan.
- [ ] Jalankan runbook di staging, catat bukti per aplikasi dan hasil drill rollback.
**Dependensi** — T10, T19, T21, T22, T23.
**Perkiraan lingkup** — S. `docs/MBU-BACKUP-PARITY.md`, `docs/MBU-CUTOVER.md`, `tests/mbu/README.md`.
### Checkpoint setelah T24
- [ ] Arsip lama terekonsiliasi dan bukti uji paralel siap ditinjau.
- [ ] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.

View File

@@ -1,4 +1,4 @@
# MBU backup fixtures # Backup fixtures
Use a clean development host with Restic, PostgreSQL client/server tools, MySQL client tools, OpenSSL, OpenSSH, Docker, AWS CLI, Node.js and Python 3.9+. The SSH fixture uses a temporary loopback `sshd` and generated keys. Some Linux hosts require the distro's SSH privilege separation directory to exist before a non-root fixture can start. Use a clean development host with Restic, PostgreSQL client/server tools, MySQL client tools, OpenSSL, OpenSSH, Docker, AWS CLI, Node.js and Python 3.9+. The SSH fixture uses a temporary loopback `sshd` and generated keys. Some Linux hosts require the distro's SSH privilege separation directory to exist before a non-root fixture can start.
@@ -7,14 +7,14 @@ rtk proxy npm --prefix web run build
rtk cargo build --workspace rtk cargo build --workspace
rtk cargo test --workspace rtk cargo test --workspace
rtk cargo test -p tessera-store -- --ignored rtk cargo test -p tessera-store -- --ignored
rtk proxy python3 tests/mbu/restic-orbits.py rtk proxy python3 tests/fixtures/restic-orbits.py
rtk proxy python3 tests/mbu/capture-postgres.py rtk proxy python3 tests/fixtures/capture-postgres.py
rtk proxy python3 tests/mbu/capture-mysql.py rtk proxy python3 tests/fixtures/capture-mysql.py
rtk proxy python3 tests/mbu/restore-postgres.py rtk proxy python3 tests/fixtures/restore-postgres.py
rtk proxy python3 tests/mbu/offsite.py rtk proxy python3 tests/fixtures/offsite.py
rtk proxy python3 tests/mbu/browser.py rtk proxy python3 tests/fixtures/browser.py
rtk proxy python3 tests/mbu/legacy-import.py rtk proxy python3 tests/fixtures/legacy-import.py
rtk proxy python3 tests/mbu/matrix.py rtk proxy python3 tests/fixtures/matrix.py
``` ```
- Restic orbits requires `rest-server` and `htpasswd` on PATH. It checks the four source/access combinations with a TLS Rest Server, re-runs after small changes, and verifies filesystem and PostgreSQL restores. Add `--mysql` to include MySQL capture and restore through both access modes. - Restic orbits requires `rest-server` and `htpasswd` on PATH. It checks the four source/access combinations with a TLS Rest Server, re-runs after small changes, and verifies filesystem and PostgreSQL restores. Add `--mysql` to include MySQL capture and restore through both access modes.
@@ -27,11 +27,13 @@ rtk proxy python3 tests/mbu/matrix.py
- The legacy import fixture reads compressed SQL archives from S3, restores synthetic samples, and verifies history access and idempotency after local GC. - The legacy import fixture reads compressed SQL archives from S3, restores synthetic samples, and verifies history access and idempotency after local GC.
- The matrix pairs three outposts, runs ten application profiles against isolated databases, exercises a scheduler tick for 02.00 WIB, and checks manual capture, scheduled capture, registered restore targets, and S3 copies. Its JSON output records durations, freshness, size and restore results. - The matrix pairs three outposts, runs ten application profiles against isolated databases, exercises a scheduler tick for 02.00 WIB, and checks manual capture, scheduled capture, registered restore targets, and S3 copies. Its JSON output records durations, freshness, size and restore results.
## Placement inventory and fixture mapping ## Fixture mapping
Read-only Teleport inventory on 10 November 2026 showed `odoo-clone`, `production-FTA`, `fta-prod`, `broiler-production`, `broiler-staging` and `mbu-backup-jumphost`. Database inventory reported the Broiler resource `mbu-production` with the MySQL protocol. MAS and FTA had no matching database resource in the approved inventory. The returned metadata had no server-version labels. The approved Machine ID could list resources, but the attempted `devops` OS login returned `unknown user devops` on `odoo-clone`, `production-FTA`, `broiler-production`, and `mbu-backup-jumphost`. Verification of deployed client/server versions, routes and privileges requires an authorized existing OS login on the applicable nodes.
| Case | Fixture | Placement to validate | | Case | Fixture | Placement to validate |
| --- | --- | --- | | --- | --- | --- |
| MAS and FTA | PostgreSQL TLS behind a loopback SSH bastion, wrong host key case | Run near the database if there is direct access. Otherwise use a pinned SSH forward to the database and validate the PostgreSQL server hostname. | | Direct PostgreSQL | TLS to a loopback server, mismatched hostname case | Run the agent where it can reach the database with the same TLS policy. |
| Boiler | MySQL behind a pinned SSH login, wrong host key and engine-error cases | Use the matched MySQL client on the SSH host and a private client options file. | | PostgreSQL behind a bastion | TLS through a loopback SSH bastion, wrong host key case | Run near the database if there is direct access. Otherwise use a pinned SSH forward to the database and validate the PostgreSQL server hostname. |
| MySQL behind SSH | Pinned SSH login, wrong host key and engine-error cases | Use the matched MySQL client on the SSH host and a private client options file. |
| Capture-only application | Profile without a restore target | Backups work; a restore request is refused until a target is registered. |
Verify deployed client and server versions, routes and privileges on the real hosts before relying on a placement.

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

@@ -12,10 +12,10 @@ import sqlite3
from fixture import bastion, command, mysql_container, pair, postgres, s3_container, start_agent, start_hub, wait_until from fixture import bastion, command, mysql_container, pair, postgres, s3_container, start_agent, start_hub, wait_until
POSTGRES = [ POSTGRES = [
"lti", "presensi", "sso", "helpdesk", "manbu", "daily_checklist", "direct_a", "direct_b", "direct_c", "direct_d", "direct_e", "post_sql_app",
"odoo_mas", "odoo_fta", "dashboard_management", "bastion_recreate", "bastion_capture_only", "capture_only_b",
] ]
CAPTURE_ONLY = {"odoo_fta", "dashboard_management"} CAPTURE_ONLY = {"bastion_capture_only", "capture_only_b"}
def main(): def main():
@@ -45,21 +45,21 @@ def main():
pg_id = pg_sql("postgres", "SELECT system_identifier FROM pg_control_system()") pg_id = pg_sql("postgres", "SELECT system_identifier FROM pg_control_system()")
mysql_id = mysql_sql("fixture", "SELECT LOWER(@@server_uuid)") mysql_id = mysql_sql("fixture", "SELECT LOWER(@@server_uuid)")
mysql_sql("fixture", "CREATE DATABASE boiler_staging; CREATE TABLE sample(value VARCHAR(40));" mysql_sql("fixture", "CREATE DATABASE mysql_staging; CREATE TABLE sample(value VARCHAR(40));"
"INSERT INTO sample VALUES ('boiler'); CREATE VIEW sample_view AS SELECT value FROM sample") "INSERT INTO sample VALUES ('mysql_app'); CREATE VIEW sample_view AS SELECT value FROM sample")
mysql_sql("boiler_staging", "CREATE TABLE sample(value VARCHAR(40)); INSERT INTO sample VALUES ('previous')") mysql_sql("mysql_staging", "CREATE TABLE sample(value VARCHAR(40)); INSERT INTO sample VALUES ('previous')")
groups = {kind: {"agent": pair(api, f"fixture-{kind}"), "profiles": {}} groups = {kind: {"agent": pair(api, f"fixture-{kind}"), "profiles": {}}
for kind in ("direct", "bastion", "mysql")} for kind in ("direct", "bastion", "mysql")}
applications = {} applications = {}
for app in POSTGRES + ["boiler"]: for app in POSTGRES + ["mysql_app"]:
mysql_app = app == "boiler" mysql_app = app == "mysql_app"
group = groups["mysql" if mysql_app else "bastion" if app in ("odoo_mas", "odoo_fta") else "direct"] group = groups["mysql" if mysql_app else "bastion" if app in ("bastion_recreate", "bastion_capture_only") else "direct"]
node = group["agent"]["outpost_id"] node = group["agent"]["outpost_id"]
orbit = api("orbits", {"name": app, "provider": "wormhole", "provider_config": {}}) orbit = api("orbits", {"name": app, "provider": "wormhole", "provider_config": {}})
app_id = str(uuid4()) app_id = str(uuid4())
engine = "mysql" if mysql_app else "postgres" engine = "mysql" if mysql_app else "postgres"
format = "mysql_sql" if mysql_app else "postgres_sql" if app == "daily_checklist" else "postgres_custom" format = "mysql_sql" if mysql_app else "postgres_sql" if app == "post_sql_app" else "postgres_custom"
api("capture-profiles", {"application_id": app_id, "orbit_id": orbit["id"], "outpost_id": node, api("capture-profiles", {"application_id": app_id, "orbit_id": orbit["id"], "outpost_id": node,
"format": format, "schedule": {"hour": 2, "timezone": "Asia/Jakarta"}}, expected=201) "format": format, "schedule": {"hour": 2, "timezone": "Asia/Jakarta"}}, expected=201)
target_db = app + "_staging" target_db = app + "_staging"
@@ -71,12 +71,12 @@ def main():
pg_sql(app, "CREATE SCHEMA fixture; CREATE TABLE fixture.sample(value text);" pg_sql(app, "CREATE SCHEMA fixture; CREATE TABLE fixture.sample(value text);"
f"INSERT INTO fixture.sample VALUES ('{app}')") f"INSERT INTO fixture.sample VALUES ('{app}')")
source = connection(app) source = connection(app)
if app in ("odoo_mas", "odoo_fta"): if app in ("bastion_recreate", "bastion_capture_only"):
source["bastion"] = pinned source["bastion"] = pinned
mode = {"reset": "recreate_database"} if app == "odoo_mas" else {"reset": "schema", "schema": "fixture"} mode = {"reset": "recreate_database"} if app == "bastion_recreate" else {"reset": "schema", "schema": "fixture"}
target = {"engine": engine, "connection": {**source, "database": target_db}, "mode": mode} target = {"engine": engine, "connection": {**source, "database": target_db}, "mode": mode}
if app == "daily_checklist": if app == "post_sql_app":
post = root / "checklist.sql" post = root / "post_restore.sql"
post.write_text("INSERT INTO fixture.sample VALUES ('post-restore');") post.write_text("INSERT INTO fixture.sample VALUES ('post-restore');")
target["post_restore_sql"] = str(post) target["post_restore_sql"] = str(post)
@@ -141,14 +141,14 @@ def main():
for app, result in results.items(): for app, result in results.items():
_, _, _, database = applications[app] _, _, _, database = applications[app]
assert result["safety_snapshot_id"] assert result["safety_snapshot_id"]
if app == "boiler": if app == "mysql_app":
assert mysql_sql(database, "SELECT value FROM sample_view") == app assert mysql_sql(database, "SELECT value FROM sample_view") == app
else: else:
expected = app + "\npost-restore" if app == "daily_checklist" else app expected = app + "\npost-restore" if app == "post_sql_app" else app
assert pg_sql(database, "SELECT value FROM fixture.sample ORDER BY value") == expected assert pg_sql(database, "SELECT value FROM fixture.sample ORDER BY value") == expected
stats[app]["restore"] = "verified" stats[app]["restore"] = "verified"
archive = applications["lti"][2] archive = applications["direct_a"][2]
expected = api(f"snapshots/{archive}/download", raw=True) expected = api(f"snapshots/{archive}/download", raw=True)
primary = root / "hub" / "vault" / "restic" primary = root / "hub" / "vault" / "restic"
primary.rename(primary.with_name("restic-offline")) primary.rename(primary.with_name("restic-offline"))

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

@@ -29,9 +29,9 @@ test("a run that stopped says at which stage and why it counts as failed or mere
}); });
test("what the person is told never contains the database's own words", () => { test("what the person is told never contains the database's own words", () => {
const done = outcomeOf(run("completed"), { target: "Development", orbit: "broiler", when: "Nov 15, 11:57 AM" }); const done = outcomeOf(run("completed"), { target: "Development", orbit: "ledger", when: "Nov 15, 11:57 AM" });
assert.equal(done.tone, "good"); assert.equal(done.tone, "good");
assert.match(done.detail, /Development now holds broiler as of Nov 15, 11:57 AM/); assert.match(done.detail, /Development now holds ledger as of Nov 15, 11:57 AM/);
assert.match(outcomeOf(run("restore_failed", "apply_failed"), { target: "Development" }).detail, /ask an administrator/i); assert.match(outcomeOf(run("restore_failed", "apply_failed"), { target: "Development" }).detail, /ask an administrator/i);
assert.match(outcomeOf(run("recovery_required"), { target: "Staging" }).title, /interrupted/i); assert.match(outcomeOf(run("recovery_required"), { target: "Staging" }).title, /interrupted/i);
assert.match(outcomeOf(run("blocked", null, "access_revoked"), { target: "Staging" }).detail, /access to this restore was removed/); assert.match(outcomeOf(run("blocked", null, "access_revoked"), { target: "Staging" }).detail, /access to this restore was removed/);
@@ -39,6 +39,14 @@ test("what the person is told never contains the database's own words", () => {
assert.equal(outcomeOf(run("restoring", "safety"), { target: "Staging" }).tone, "busy"); assert.equal(outcomeOf(run("restoring", "safety"), { target: "Staging" }).tone, "busy");
}); });
test("an undo is worded as putting the target back, and its own safety copy keeps it undoable", () => {
const done = outcomeOf({ ...run("completed"), undo: true }, { target: "Staging", orbit: "ledger", when: "Nov 15, 11:57 AM" });
assert.equal(done.tone, "good");
assert.match(done.title, /Staging was rolled back/);
assert.match(done.detail, /holds what it held before that restore/);
assert.match(outcomeOf({ ...run("restore_failed", "apply_failed"), undo: true }, { target: "Staging" }).title, /undo failed/i);
});
test("restore points are named by environment, and by target only when two share one", () => { test("restore points are named by environment, and by target only when two share one", () => {
const rel = (id, env, name) => ({ id, target_environment: env, target_name: name, usable: true }); const rel = (id, env, name) => ({ id, target_environment: env, target_name: name, usable: true });
assert.deepEqual( assert.deepEqual(
@@ -51,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

@@ -135,6 +135,18 @@ export type RefreshRelation = {
target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null; target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null;
}; };
export type RefreshRun = { export type RefreshRun = {
/** Put a target back from the safety copy of an earlier restore. */
undo?: boolean;
/** A completed restore that can still be undone (the newest of its target, safety copy still there). */
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;
@@ -143,13 +155,13 @@ export type RefreshRun = {
export const fetchRefreshRelations = () => api<RefreshRelation[]>("/api/v1/refresh-relations"); export const fetchRefreshRelations = () => api<RefreshRelation[]>("/api/v1/refresh-relations");
export const fetchRefreshRuns = () => api<RefreshRun[]>("/api/v1/refresh-runs"); export const fetchRefreshRuns = () => api<RefreshRun[]>("/api/v1/refresh-runs");
/** Restore `snapshot_id` onto the relation's target (or, without one, capture first and restore that). */ /** Restore `snapshot_id` onto the relation's target (or, without one, capture first and restore that). */
export const startRefresh = (relation: RefreshRelation, idempotency_key: string, snapshot_id?: string) => export const startRefresh = (relation: RefreshRelation, idempotency_key: string, pick: { snapshot_id?: string; undo_of?: string } = {}) =>
api<RefreshRun>("/api/v1/refresh-runs", json("POST", { api<RefreshRun>("/api/v1/refresh-runs", json("POST", {
relation_id: relation.id, relation_id: relation.id,
// exactly what the person was shown, so a relation changed in the meantime is refused // exactly what the person was shown, so a relation changed in the meantime is refused
confirmation: `REFRESH ${relation.source_name} TO ${relation.target_name} v${relation.version}`, confirmation: `REFRESH ${relation.source_name} TO ${relation.target_name} v${relation.version}`,
idempotency_key, idempotency_key,
...(snapshot_id ? { snapshot_id } : {}), ...(pick.undo_of ? { undo_of: pick.undo_of } : pick.snapshot_id ? { snapshot_id: pick.snapshot_id } : {}),
})); }));
export const fetchRefreshRun = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`); export const fetchRefreshRun = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`);
export const cancelRefresh = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`, { method: "DELETE" }); export const cancelRefresh = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`, { method: "DELETE" });

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

@@ -61,7 +61,7 @@ export function RelationsView() {
// Several applications can have a target called "dev": the application is what tells them apart. // Several applications can have a target called "dev": the application is what tells them apart.
const appName = (t: TargetSetup) => data.orbits.find((o) => o.application_id === t.application_id)?.name ?? "Unknown application"; const appName = (t: TargetSetup) => data.orbits.find((o) => o.application_id === t.application_id)?.name ?? "Unknown application";
// a name that already mentions the application (e.g. "presensi · dev") is not prefixed twice // a name that already mentions the application (e.g. "billing · dev") is not prefixed twice
const targetLabel = (t: TargetSetup) => (t.name.toLowerCase().includes(appName(t).toLowerCase()) ? t.name : `${appName(t)} · ${t.name}`); const targetLabel = (t: TargetSetup) => (t.name.toLowerCase().includes(appName(t).toLowerCase()) ? t.name : `${appName(t)} · ${t.name}`);
const sources = data.orbits.filter((o) => o.ready); const sources = data.orbits.filter((o) => o.ready);
const chosen = data.orbits.find((o) => o.id === source); const chosen = data.orbits.find((o) => o.id === source);

View File

@@ -1,9 +1,9 @@
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { motion } from "motion/react"; import { motion } from "motion/react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { cancelRefresh, fetchRefreshRun, 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";
@@ -17,6 +17,7 @@ const REFUSALS: Record<string, string> = {
relation_unusable: "This restore point cannot be used right now. Ask an administrator.", relation_unusable: "This restore point cannot be used right now. Ask an administrator.",
too_many_runs: "Too many restores are running at once. Try again in a few minutes.", too_many_runs: "Too many restores are running at once. Try again in a few minutes.",
snapshot_unusable: "This backup cannot be restored to that database.", snapshot_unusable: "This backup cannot be restored to that database.",
nothing_to_undo: "There is nothing to undo any more: something was restored after it, or its safety copy was removed.",
source_unavailable: "The source cannot be reached right now.", source_unavailable: "The source cannot be reached right now.",
}; };
@@ -27,21 +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 restore (or undo) being put back. Its presence is the
// 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()));
@@ -66,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, 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.");
@@ -77,31 +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]); }, [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); // 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());
};
// The newest restore on the chosen restore point, if it can still be undone.
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 beginUndo = (of: RefreshRun) => {
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>
@@ -110,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}
@@ -128,15 +171,29 @@ 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); 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 && !undoRun && phase === "idle" && !runId && (
<div className="restore-undo">
<p>
{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>
)}
{admin && database && phase === "idle" && !runId && ( {admin && database && phase === "idle" && !runId && (
<button type="button" className="footer-link self-start" onClick={() => setOther(true)}>Other registered target…</button> <button type="button" className="footer-link self-start" onClick={() => setOther(true)}>Other registered target…</button>
)} )}
@@ -144,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">
@@ -155,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">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" && (
@@ -182,7 +239,10 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
<div role="status" className={`restore-outcome ${outcome.tone}`}> <div role="status" className={`restore-outcome ${outcome.tone}`}>
<p>{outcome.title}</p> <p>{outcome.title}</p>
<p>{outcome.detail}</p> <p>{outcome.detail}</p>
<Button onClick={again}>{outcome.tone === "good" ? "Restore again" : "Try again"}</Button> <div className="flex flex-wrap gap-2">
{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" ? "Done" : "Try again"}</Button>
</div>
</div> </div>
)} )}
{run.isError && <p role="alert" className="text-sm text-orbit-amber">Reconnecting to the restore…</p>} {run.isError && <p role="alert" className="text-sm text-orbit-amber">Reconnecting to the restore…</p>}

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; }
@@ -1219,3 +1222,6 @@ button.act-row[data-group="needs"]:hover { background: #20161a; }
.restore-outcome.good p:first-child { color: var(--color-orbit-green, #8fd0b0); } .restore-outcome.good p:first-child { color: var(--color-orbit-green, #8fd0b0); }
.restore-outcome.bad { border-color: #6b2f26; } .restore-outcome.bad { border-color: #6b2f26; }
.restore-outcome.bad p:first-child { color: var(--color-orbit-red); } .restore-outcome.bad p:first-child { color: var(--color-orbit-red); }
.restore-undo { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; padding: 12px; border: 1px dashed var(--line); border-radius: 12px; }
.restore-undo p { margin: 0; font-size: 13px; line-height: 1.5; color: var(--quiet); }

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 }; 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) {
@@ -52,6 +65,17 @@ export function outcomeOf(
names: { target: string; orbit?: string; when?: string }, names: { target: string; orbit?: string; when?: string },
): Outcome { ): Outcome {
const { target } = names; const { target } = names;
if (run.undo) {
switch (run.status) {
case "completed":
case "reconciled":
return { tone: "good", title: `${target} was rolled back`, detail: `${target} holds what it held before that restore. A safety copy of the state you undid was kept, so this can be undone too.` };
case "restore_failed":
return { tone: "bad", title: "The undo failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` };
default:
break; // the other outcomes read the same for an undo
}
}
switch (run.status) { switch (run.status) {
case "completed": case "completed":
case "reconciled": case "reconciled":
@@ -65,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();