Compare commits

..

37 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
54 changed files with 3560 additions and 863 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
on: [push, pull_request]
permissions:
contents: read
jobs:
rust:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- 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@1.89.0
- uses: dtolnay/rust-toolchain@d92bbbb03544f480ed5c7ba4b54020e4ed2c4f65 # 1.89.0
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: cargo fmt --all -- --check
- run: cargo clippy --workspace --all-targets -- -D warnings
@@ -19,15 +21,15 @@ jobs:
supply-chain:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: EmbarkStudios/cargo-deny-action@v2
- run: cargo install cargo-audit --locked && cargo audit
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2
- run: cargo install cargo-audit --version 0.23.0 --locked && cargo audit
web:
runs-on: ubuntu-latest
defaults: { run: { working-directory: web } }
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- 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
- 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
.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/
/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
## 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
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.
- Refresh console for QA and a refresh-only access mode.
- 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"
dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
"clap",
"hex",

View File

@@ -14,7 +14,7 @@ members = [
version = "0.1.0"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = ["Senkensha"]
authors = ["The Tessera contributors"]
[workspace.dependencies]
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
COPY web/package.json web/package-lock.json* ./
RUN npm ci
COPY web/ ./
RUN npm run build
FROM rust:1.89-bookworm AS rust
FROM rust:1.89-bookworm@sha256:948f9b08a66e7fe01b03a98ef1c7568292e07ec2e4fe90d88c07bb14563c84ff AS rust
WORKDIR /build
COPY Cargo.toml Cargo.lock* ./
COPY crates ./crates
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 mysql:8.4 AS mysql-client
FROM restic/restic:0.19.1@sha256:136600b6ff6843d61d355f7f71f460a166429f35de6fd11b568fece3c9a4d510 AS restic
FROM mysql:8.4@sha256:a81d043930e51745522bd5c430961cf8286f0a23f0a9a2a6e0108f7ea71b0902 AS mysql-client
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates postgresql-client libstdc++6 && rm -rf /var/lib/apt/lists/*
COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/
FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc
# Bookworm ships pg_dump 15, which refuses to dump a newer server. Install a
# 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=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_DATA_DIR=/data
EXPOSE 8787
VOLUME ["/data"]
USER tessera
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD ["/usr/local/bin/tessera-healthcheck"]
ENTRYPOINT ["tessera-hub"]

View File

@@ -16,10 +16,10 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./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
(`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
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,
@@ -32,7 +32,25 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
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
@@ -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).
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.
@@ -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.
- 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`.
- 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
Report vulnerabilities privately to the maintainers (use the repository's private security advisory feature, or the
contact listed on the project page). Do not open a public issue for a vulnerability. Expect an acknowledgement within a
few days.
## Reporting a vulnerability
Supported: the latest release. Tessera holds encrypted backups: keep `TESSERA_VAULT_PASSPHRASE` and the `vault`
directory together, serve the hub over HTTPS outside loopback, and set `TESSERA_TRUSTED_PROXIES` only for proxies you
operate. Hardening notes and the auth design are in `docs/DATABASE-CAPTURE.md` and `docs/auth-endpoint-contract.md`.
Please report vulnerabilities privately. Use GitHub private vulnerability reporting: open the repository's **Security**
tab and choose **Report a vulnerability**. Do not open a public issue or pull request for a vulnerability.
<!-- 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_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE}
TESSERA_ADMIN_TOKEN:
TESSERA_ADMIN_TOKEN_EXPIRES:
TESSERA_OPERATOR_PASSWORD_HASH:
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_PASSWORD_FILE:
AWS_ACCESS_KEY_ID:
AWS_SECRET_ACCESS_KEY:
AWS_SESSION_TOKEN:
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
volumes:
- tessera-data:/data
read_only: true
tmpfs:
- /tmp:size=256m,mode=1777
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
restart: unless-stopped
healthcheck:
test: ["CMD", "/usr/local/bin/tessera-healthcheck"]
interval: 30s
timeout: 5s
retries: 3
start_period: 20s
volumes:
tessera-data:

View File

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

View File

@@ -46,8 +46,15 @@ pub(super) enum Source {
Mysql(MysqlSource),
}
impl Source {
pub(super) async fn identity(&self) -> Result<DatabaseIdentity> {
/// The local backup source, as far as the restore guard cares: which database it is.
#[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 {
Self::Postgres(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.targets,
profile.timeout_seconds,
Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS),
)
.await?;
if !restored && (profile.source.is_some() || !profile.paths.is_empty()) {

View File

@@ -1,12 +1,21 @@
use crate::{
http,
jobs::{digest_file, Hub, Source},
jobs::{digest_file, BackupSource, Hub},
};
use anyhow::{ensure, Context, Result};
use async_trait::async_trait;
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::{
job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS},
job::CaptureFormat,
restore::{DatabaseIdentity, RestoreLease, RestoreProgress},
};
use tessera_providers::{MysqlRestore, PostgresRestore};
@@ -19,7 +28,108 @@ pub(super) enum Target {
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> {
match self {
Self::Postgres(target) => target.connection.identity().await,
@@ -59,16 +169,17 @@ impl Target {
}
}
pub(super) async fn poll(
hub: &Arc<Hub>,
pub(super) async fn poll<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &H,
application: Uuid,
source: Option<&Source>,
targets: &HashMap<Uuid, Target>,
source: Option<&S>,
targets: &HashMap<Uuid, T>,
timeout_seconds: u64,
heartbeat: Duration,
) -> Result<bool> {
for (target_id, target) in targets {
let reply = hub
.post(
.send(
format!("restore-targets/{target_id}/claim"),
serde_json::Value::Null,
None,
@@ -81,20 +192,32 @@ pub(super) async fn poll(
lease.job.target.id == *target_id && lease.job.target.application_id == application,
"hub returned an unexpected restore target"
);
let permit_taken = AtomicBool::new(false);
let work = run(
hub,
&lease,
target,
source,
Duration::from_secs(timeout_seconds),
&permit_taken,
);
tokio::pin!(work);
loop {
tokio::select! {
biased;
result = &mut work => return result.map(|()| true),
_ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => {
report(hub, &lease, RestoreProgress::Heartbeat).await?;
_ = tokio::time::sleep(heartbeat) => {
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)
}
async fn run(
hub: &Arc<Hub>,
async fn run<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &H,
lease: &RestoreLease,
target: &Target,
source: Option<&Source>,
target: &T,
source: Option<&S>,
timeout: Duration,
permit_taken: &AtomicBool,
) -> Result<()> {
report(hub, lease, RestoreProgress::Checking).await?;
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
})
.await;
@@ -159,15 +283,7 @@ async fn run(
target.identity().await? == identity,
"target changed during safety capture"
);
hub.upload(
format!("restore/{}/safety", lease.job.id),
stage,
timeout,
"x-tessera-restore-token",
lease.token,
None,
)
.await?;
hub.upload_safety(lease, stage, timeout).await?;
Ok::<_, anyhow::Error>(())
})
.await;
@@ -176,8 +292,10 @@ async fn run(
return Ok(());
}
// The permit is single-use. A lost response leaves the target locked for reconciliation.
hub.post(
// The permit is single-use. A lost response leaves the target locked for reconciliation. Mark it
// 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),
serde_json::Value::Null,
Some(lease.token),
@@ -198,13 +316,13 @@ fn why<T>(result: Result<Result<T>, tokio::time::error::Elapsed>) -> String {
}
}
async fn report_failed(
hub: &Arc<Hub>,
async fn report_failed<H: RestoreHub>(
hub: &H,
lease: &RestoreLease,
progress: RestoreProgress,
reason: String,
) -> Result<()> {
hub.post_with_reason(
hub.send_with_reason(
format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?,
lease.token,
@@ -214,8 +332,12 @@ async fn report_failed(
Ok(())
}
async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> {
hub.post(
async fn report<H: RestoreHub>(
hub: &H,
lease: &RestoreLease,
progress: RestoreProgress,
) -> Result<()> {
hub.send(
format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?,
Some(lease.token),
@@ -224,28 +346,5 @@ async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress)
Ok(())
}
async fn download(hub: &Arc<Hub>, lease: &RestoreLease, timeout: Duration) -> Result<File> {
let hub = hub.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?
}
#[cfg(test)]
mod tests;

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

View File

@@ -16,6 +16,9 @@ impl AdminGate {
.ok()
.map(|value| value.trim().to_string())
.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() {
Ok("1" | "true") => true,
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> {
if let Some(value) = headers
.get("x-tessera-admin-token")
@@ -152,6 +171,13 @@ mod tests {
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]
fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() {
let gate = AdminGate {
@@ -266,8 +292,6 @@ pub struct BrowserSession {
pub id: uuid::Uuid,
pub csrf: String,
pub actor: String,
/// Read by per-user revoke and the OIDC login path (M3/M5).
#[allow(dead_code)]
pub user_id: String,
pub auth_method: String,
/// 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 {
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
.unwrap();
if let Some(gate) = exports {

View File

@@ -33,10 +33,12 @@ fn every_registered_path_has_an_authorization_contract() {
#[tokio::test]
async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
let dir = tempfile::tempdir().unwrap();
let mut state =
crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault")
.await
.unwrap();
let mut state = crate::state::HubState::bootstrap(
dir.path().to_str().unwrap(),
"synthetic-vault-passphrase",
)
.await
.unwrap();
state.sessions = crate::admin::SessionGate::fixture(state.db.clone());
state.admin.token = Some("synthetic-admin".into());
let outpost = uuid::Uuid::new_v4();
@@ -44,6 +46,8 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
.db
.insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture");
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("| /")) {
let fields: Vec<_> = row.split('|').map(str::trim).collect();
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");
for token in [None, Some("synthetic-outpost")] {
let mut request = Request::builder()
.uri(&path)
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()));
source += 1;
let mut request =
Request::builder()
.uri(&path)
.extension(ConnectInfo(SocketAddr::from((
[10, 0, (source >> 8) as u8, source as u8],
9000,
))));
if let Some(token) = token {
request = request
.header(header::AUTHORIZATION, format!("Bearer {token}"))
@@ -76,10 +85,12 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
#[tokio::test]
async fn local_proxy_never_enables_auth_when_credentials_are_absent() {
let dir = tempfile::tempdir().unwrap();
let mut state =
crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault")
.await
.unwrap();
let mut state = crate::state::HubState::bootstrap(
dir.path().to_str().unwrap(),
"synthetic-vault-passphrase",
)
.await
.unwrap();
state.admin = crate::admin::AdminGate {
token: None,
local_development: false,

View File

@@ -22,7 +22,7 @@ struct Harness {
async fn harness_with(configure: impl FnOnce(&mut HubState)) -> Harness {
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
.unwrap();
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));
}
// ---- 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 {
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
.unwrap();
state.admin.token = Some(ADMIN.into());

View File

@@ -266,10 +266,11 @@ async fn job(
async fn claim(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(application): Path<Uuid>,
) -> Result<Json<Option<CaptureLease>>, StatusCode> {
let outpost = outpost(&state, &headers)?;
let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let mut lease = state
.db
.claim_capture(outpost, application, now())
@@ -288,11 +289,12 @@ async fn claim(
async fn report(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Result<Json<CaptureReport>, JsonRejection>,
) -> 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)?;
if !state
.db
@@ -306,11 +308,12 @@ async fn report(
async fn upload(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Body,
) -> 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")?)
.map_err(|_| StatusCode::BAD_REQUEST)?;
let job = state
@@ -401,11 +404,12 @@ async fn upload(
async fn commit_restic(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(commit): Json<ResticCaptureCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, &headers)?;
let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let job = state
.db
.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)
}
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};
let result = authenticate_outpost(state, headers);
let (actor, resource, outcome) = match result {
Ok(id) => (
Principal::Outpost(id),
AuditResource::Outpost(id),
AuditOutcome::Allowed,
),
Err(_) => (
Principal::Anonymous,
AuditResource::Api,
AuditOutcome::Denied,
),
};
state
.db
.audit_event(
&actor,
AuditAction::Authentication,
resource,
outcome,
Uuid::new_v4(),
)
.map_err(internal)?;
match result {
Ok(id) => {
state
.db
.audit_event(
&Principal::Outpost(id),
AuditAction::Authentication,
AuditResource::Outpost(id),
AuditOutcome::Allowed,
Uuid::new_v4(),
)
.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
}

View File

@@ -248,7 +248,7 @@ fn config(idp: &Idp) -> OidcConfig {
async fn harness_with(min_refresh: Duration) -> Harness {
let idp = Idp::start().await;
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
.unwrap();
let config = config(&idp);
@@ -788,7 +788,7 @@ async fn an_idp_outage_degrades_to_fixed_errors_and_never_a_session() {
#[tokio::test]
async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() {
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
.unwrap();
let app = crate::api::router(state);

View File

@@ -115,13 +115,35 @@ async fn undo_views(
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 });
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)? {
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) });
views.insert(
run.id.clone(),
Undo {
state: "available",
kept_until: Some(kept),
},
);
}
}
Ok(views)
@@ -329,7 +351,9 @@ async fn start(
actor.subject.user_id.as_deref(),
&authorized_by,
&body.idempotency_key,
chosen.as_ref().map(|(snapshot, of)| (*snapshot, of.as_deref())),
chosen
.as_ref()
.map(|(snapshot, of)| (*snapshot, of.as_deref())),
state.refresh.ttl_secs,
state.refresh.max_active,
now(),

View File

@@ -44,7 +44,7 @@ struct Lab {
async fn lab_with(configure: impl FnOnce(&mut HubState)) -> Lab {
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
.unwrap();
state.admin.token = Some(ADMIN.into());
@@ -2380,9 +2380,14 @@ async fn only_someone_who_may_use_the_relation_can_undo_through_it() {
impl Lab {
async fn run_view(&self, run: &str) -> Value {
self.send(&self.admin(), "GET", &format!("/api/v1/refresh-runs/{run}"), None)
.await
.1
self.send(
&self.admin(),
"GET",
&format!("/api/v1/refresh-runs/{run}"),
None,
)
.await
.1
}
fn safety_of(&self, run: &str) -> Uuid {
@@ -2396,9 +2401,14 @@ impl Lab {
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.capture(&Lab::production_identity(), false)
.await
.unwrap();
self.tick().await;
let (job, token) = self.restore_until_ready().await.expect("a restore job is waiting");
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(
@@ -2420,28 +2430,60 @@ 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}");
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!(
(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();
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_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();
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();
let states: Vec<_> = list
.as_array()
.unwrap()
.iter()
.map(|r| r["undo_state"].clone())
.collect();
assert_eq!(states, vec![json!("expired"), json!("expired")], "{list}");
}
@@ -2451,23 +2493,40 @@ async fn a_restore_whose_apply_failed_is_rolled_back_from_its_safety_copy() {
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}");
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}");
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"));
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");
assert_eq!(
lab.run_view(&run).await["undo_state"],
"superseded",
"it is not offered twice"
);
}
#[tokio::test]
@@ -2476,14 +2535,25 @@ async fn an_apply_that_lost_its_agent_waits_for_an_administrator_before_it_can_b
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])
.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}");
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());
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);

View File

@@ -370,10 +370,11 @@ async fn reconcile(
async fn claim(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(target): Path<Uuid>,
) -> Result<Json<Option<RestoreLease>>, StatusCode> {
let outpost = outpost(&state, &headers)?;
let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
state
.db
.claim_restore(outpost, target, now())
@@ -381,8 +382,12 @@ async fn claim(
.map_err(internal)
}
fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCode> {
let outpost = outpost(state, headers)?;
fn auth(
state: &HubState,
peer: Option<ConnectInfo<SocketAddr>>,
headers: &HeaderMap,
) -> Result<(Uuid, Uuid), StatusCode> {
let outpost = outpost(state, peer.map(|ConnectInfo(addr)| addr), headers)?;
let token =
header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?;
Ok((
@@ -393,10 +398,11 @@ fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCod
async fn payload(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> {
let (outpost, token) = auth(&state, &headers)?;
let (outpost, token) = auth(&state, peer, &headers)?;
let (job, artifact, _) = state
.db
.restore_access(outpost, id, token, now())
@@ -435,11 +441,12 @@ async fn payload(
async fn report(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Result<Json<RestoreProgress>, JsonRejection>,
) -> 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)?;
// 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.
@@ -462,11 +469,12 @@ async fn report(
async fn safety(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> {
let (outpost, token) = auth(&state, &headers)?;
let (outpost, token) = auth(&state, peer, &headers)?;
let (job, _, safety_id) = state
.db
.restore_access(outpost, id, token, now())
@@ -538,10 +546,11 @@ async fn safety(
async fn apply(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?;
let (outpost, token) = auth(&state, peer, &headers)?;
if !state
.db
.authorize_apply(outpost, id, token, now())

View File

@@ -251,7 +251,6 @@ struct ReconstituteStartResponse {
pub(super) struct OperatorActor {
/// Display only. Never record this as "who did it": an IdP can call a user anything.
pub(super) name: String,
pub(super) browser: bool,
pub(super) principal: Principal,
pub(super) subject: Subject,
pub(super) request_id: Uuid,
@@ -289,16 +288,21 @@ pub(super) fn authenticate(
.unwrap_or(Principal::Anonymous);
let result = authenticate_inner(state, peer, headers, mutation, request_id, session);
if result.is_err() {
state
.db
.audit_event(
// One denial row per source per minute: an unauthenticated flood must not
// grow the audit table, and a failed audit write must not turn the 401/403
// 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,
AuditAction::Authentication,
AuditResource::Api,
AuditOutcome::Denied,
request_id,
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
) {
tracing::error!(%error, "could not record a denied authentication");
}
}
}
result
}
@@ -313,7 +317,6 @@ fn authenticate_inner(
) -> Result<OperatorActor, StatusCode> {
let configured_admin = |name: &str, principal: Principal| OperatorActor {
name: name.into(),
browser: false,
principal,
subject: Subject {
user_id: None,
@@ -322,11 +325,21 @@ fn authenticate_inner(
},
request_id,
};
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
return Ok(configured_admin(
"api-token",
Principal::Service("legacy-admin-token"),
));
if state.admin.token.is_some() {
if state.admin.authorize(peer, headers).is_ok() {
return Ok(configured_admin(
"api-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 mutation {
@@ -336,7 +349,6 @@ fn authenticate_inner(
principal: session.principal(),
subject: session.subject(),
name: session.actor,
browser: true,
request_id,
});
}
@@ -407,14 +419,73 @@ pub fn router(state: HubState) -> Router {
.merge(super::relations::routes())
.merge(super::refresh::routes())
.merge(super::restore::routes())
.route("/api-doc/openapi.json", get(openapi_document))
.with_state(state);
let api = api.route(
"/api-doc/openapi.json",
get(|| async { Json(ApiDoc::openapi()) }),
);
let hsts = matches!(std::env::var("TESSERA_HSTS").as_deref(), Ok("1" | "true"));
api.fallback(spa_fallback)
.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")))]
@@ -750,12 +821,13 @@ async fn start_reconstitute(
headers: HeaderMap,
Json(req): Json<ReconstituteRequest>,
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let destination = if actor.browser {
browser_export_path(&state, &req.target_path)?
} else {
req.target_path.clone().into()
};
admin_write(&state, peer, &headers)?;
// Every caller, browser or API token, may only name a file inside the hub's exports directory,
// and never one that already exists.
let destination = browser_export_path(&state, &req.target_path)?;
if destination.symlink_metadata().is_ok() {
return Err(StatusCode::CONFLICT);
}
let vault = state.vault.read().await;
if vault
.get_snapshot(req.snapshot_id)
@@ -785,6 +857,7 @@ async fn start_reconstitute(
let mut map = state_bg.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&session_id) {
if s.state == ReconstituteState::Aborted {
evict_reconstitute_later(&state_bg, session_id);
return;
}
s.seconds_remaining = remaining;
@@ -798,6 +871,7 @@ async fn start_reconstitute(
return;
};
if s.state == ReconstituteState::Aborted {
evict_reconstitute_later(&state_bg, session_id);
return;
}
s.state = ReconstituteState::Restoring;
@@ -816,6 +890,7 @@ async fn start_reconstitute(
.db
.audit("reconstitute.done", &format!("session={session_id}"))
.await;
evict_reconstitute_later(&state_bg, session_id);
});
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(
state: &HubState,
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)))]
async fn wormhole_upload_init(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: axum::http::HeaderMap,
Json(body): Json<UploadInit>,
) -> 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)?;
reject_managed_orbit(&state, body.orbit_id)?;
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)))]
async fn wormhole_upload_chunk(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: axum::http::HeaderMap,
Json(body): Json<UploadChunk>,
) -> 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
.db
.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)))]
async fn wormhole_restic_commit(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Json(body): Json<ResticCommit>,
) -> 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)?;
if body.snapshot_id.len() != 64 || !body.snapshot_id.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(StatusCode::BAD_REQUEST);
@@ -1469,18 +1560,33 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse {
path = "index.html".into();
}
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 (
StatusCode::OK,
[(header::CONTENT_TYPE, ct)],
[
(header::CONTENT_TYPE, content_type(&path)),
(header::CACHE_CONTROL, cache),
],
file.contents(),
)
.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") {
return (
StatusCode::OK,
[(header::CONTENT_TYPE, "text/html")],
[
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
(header::CACHE_CONTROL, "no-cache"),
],
index.contents(),
)
.into_response();
@@ -1489,14 +1595,22 @@ async fn spa_fallback(uri: Uri) -> impl IntoResponse {
}
fn content_type(path: &str) -> &'static str {
if path.ends_with(".js") {
"application/javascript"
} else if path.ends_with(".css") {
"text/css"
} else if path.ends_with(".svg") {
"image/svg+xml"
} else {
"text/html"
let extension = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
match extension.as_str() {
"html" => "text/html; charset=utf-8",
"js" | "mjs" => "text/javascript; charset=utf-8",
"css" => "text/css; charset=utf-8",
"svg" => "image/svg+xml",
"png" => "image/png",
"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,12 +1621,291 @@ mod tests {
use axum::http::Request;
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]
async fn legacy_uploads_are_owned_by_the_assigned_outpost() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault")
.await
.unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.accept_plain_upload = true;
state.admin.token = Some("synthetic-admin".into());
let a = Uuid::new_v4();
@@ -1693,6 +2086,7 @@ mod tests {
);
let mut commit = Box::pin(wormhole_restic_commit(
State(state.clone()),
None,
owner_headers,
Json(ResticCommit {
orbit_id: orbit,
@@ -1721,7 +2115,7 @@ mod tests {
#[tokio::test]
async fn orbit_creation_validates_cron_and_direct_run_preserves_wormhole_status() {
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
.unwrap();
state.admin.token = Some("fixture-admin".into());
@@ -1787,7 +2181,7 @@ mod tests {
#[tokio::test]
async fn new_orbits_validate_source_access_and_keep_provider_internal() {
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
.unwrap();
state.admin.token = Some("fixture-admin".into());
@@ -1843,7 +2237,7 @@ mod tests {
#[tokio::test]
async fn orbit_responses_and_schema_hide_provider_config() {
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
.unwrap();
state.admin.token = Some("fixture-admin".into());

View File

@@ -369,9 +369,10 @@ mod tests {
#[tokio::test]
async fn operator_session_requires_csrf_and_expires_without_disabling_cli() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
.await
.unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase")
.await
.unwrap();
state.sessions = SessionGate::fixture(state.db.clone());
state.admin.token = Some("fixture-api-token".into());
let app = crate::api::router(state.clone());
@@ -507,9 +508,10 @@ mod tests {
#[tokio::test]
async fn me_reports_the_caller_and_rejects_anonymous() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
.await
.unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase")
.await
.unwrap();
state.sessions = SessionGate::fixture(state.db.clone());
let app = crate::api::router(state);
let peer = || ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap());

View File

@@ -51,12 +51,56 @@ impl Db {
)?;
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)]
mod tests {
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]
async fn structured_audit_survives_reopen_and_preserves_legacy_events() {
let dir = tempfile::tempdir().unwrap();

View File

@@ -114,7 +114,10 @@ pub struct UndoInfo {
/// 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") {
if !matches!(
run.status.as_str(),
"completed" | "reconciled" | "recovery_required"
) {
return Ok(None);
}
let Some(job) = &run.restore_job_id else {
@@ -189,7 +192,10 @@ impl Db {
/// 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>> {
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 {

View File

@@ -10,7 +10,10 @@ use axum::body::Bytes;
use futures_core::Stream;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
use std::task::{Context, Poll};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use uuid::Uuid;
@@ -170,6 +173,26 @@ pub struct ExportGate {
permits: Arc<Semaphore>,
/// Free space that must remain after the export has been written.
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 {
@@ -184,6 +207,7 @@ impl ExportGate {
Self {
permits: Arc::new(Semaphore::new(concurrency)),
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.
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<OwnedSemaphorePermit, Refused> {
/// Admit one export of about `size` bytes into `dir`. The slot and the bytes are held for as long as the
/// 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
.permits
.clone()
.try_acquire_owned()
.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) {
// `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),
_ => Ok(permit),
// Bytes already written by running exports are no longer free and are counted again in `earlier`; being
// 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.
pub struct Guarded<S> {
inner: Pin<Box<S>>,
_permit: OwnedSemaphorePermit,
_permit: Admission,
_dir: tempfile::TempDir,
db: Db,
principal: Principal,
@@ -261,7 +299,7 @@ pub struct Guarded<S> {
impl<S> Guarded<S> {
pub fn new(
inner: S,
permit: OwnedSemaphorePermit,
permit: Admission,
dir: tempfile::TempDir,
db: Db,
principal: Principal,
@@ -330,14 +368,14 @@ mod tests {
#[test]
fn a_download_is_named_after_the_application_the_time_and_the_engine() {
let name = download_name(
"lti",
"app",
taken(),
Some("Asia/Jakarta"),
Some("Europe/Berlin"),
Some("postgres"),
id(),
"dump",
);
assert_eq!(name, "lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump");
assert_eq!(name, "app_2026-11-14T2030+0100_postgres_a1b2c3d4.dump");
let name = download_name("ledger", taken(), None, Some("mysql"), id(), "sql.gz");
assert_eq!(name, "ledger_2026-11-14T1930Z_mysql_a1b2c3d4.sql.gz");
// no engine (a folder snapshot): the part is left out
@@ -350,7 +388,7 @@ mod tests {
#[test]
fn an_unknown_time_zone_falls_back_to_utc() {
let name = download_name(
"lti",
"app",
taken(),
Some("Mars/Olympus"),
Some("postgres"),
@@ -363,8 +401,8 @@ mod tests {
#[test]
fn two_snapshots_in_the_same_minute_get_different_names() {
let other = Uuid::parse_str("ffffffff-0000-4000-8000-000000000000").unwrap();
let a = download_name("lti", taken(), None, Some("postgres"), id(), "dump");
let b = download_name("lti", taken(), None, Some("postgres"), other, "dump");
let a = download_name("app", taken(), None, Some("postgres"), id(), "dump");
let b = download_name("app", taken(), None, Some("postgres"), other, "dump");
assert_ne!(a, b);
}
@@ -404,11 +442,11 @@ mod tests {
#[test]
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!(
header,
"attachment; filename=\"lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump\"; \
filename*=UTF-8''lti_2026-11-15T0230%2B0700_postgres_a1b2c3d4.dump"
"attachment; filename=\"app_2026-11-14T2030+0100_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"
);
}
#[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_callback_source: Keyed,
audit_denial: Keyed,
admin_token_failure: Keyed,
pub argon2: Arc<Semaphore>,
trusted_proxies: Vec<IpAddr>,
calls: AtomicU64,
@@ -75,6 +76,7 @@ impl Limits {
oidc_callback_source: RateLimiter::keyed(config.oidc_callback_source),
// one audit row per source per minute, so a flood cannot fill the audit table
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)),
trusted_proxies,
calls: AtomicU64::new(0),
@@ -131,6 +133,7 @@ impl Limits {
self.oidc_login_source.retain_recent();
self.oidc_callback_source.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()
}
/// 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.
pub fn audit_denial(&self, source: IpAddr) -> bool {
self.audit_denial.check_key(&source).is_ok()

View File

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

View File

@@ -75,7 +75,16 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
mtls.listen
);
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 app = app.clone();
tokio::spawn(async move {
@@ -191,7 +200,7 @@ mod tests {
};
let mut state = crate::state::HubState::bootstrap(
dir.path().join("hub").to_str().unwrap(),
"synthetic-vault",
"synthetic-vault-passphrase",
)
.await
.unwrap();

View File

@@ -32,6 +32,51 @@ pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
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> {
if expression.split_whitespace().count() == 5 {
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 {
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]
fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() {
let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap();

View File

@@ -409,7 +409,8 @@ mod tests {
#[test]
fn pg_dump_keeps_the_url_out_of_argv() {
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");
let args = dump_args("custom").unwrap();
let pgpass = write_pgpass(&target, false).unwrap();

View File

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

View File

@@ -43,6 +43,9 @@ struct OutpostRepository {
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 {
pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
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"
);
}
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();
fs::create_dir_all(root.join("data"))?;
fs::create_dir_all(root.join("snapshots"))?;
@@ -81,6 +88,16 @@ impl Vault {
anyhow::bail!("vault not initialized");
}
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 key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = Self::load_index(&root)?;
@@ -655,7 +672,8 @@ impl Vault {
}
let len = temp.as_file().metadata()?.len();
temp.as_file().sync_all()?;
temp.persist(dest)?;
// never replace a file that is already there
temp.persist_noclobber(dest)?;
Ok(len)
}
@@ -829,7 +847,7 @@ mod tests {
rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes);
let file = source.join("large.bin");
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 {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
@@ -882,7 +900,7 @@ mod tests {
#[test]
fn init_snap_list_restore() {
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 {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
@@ -905,7 +923,7 @@ mod tests {
#[test]
fn dry_run_writes_nothing() {
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 {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
@@ -922,7 +940,7 @@ mod tests {
#[test]
fn orbit_decay_keeps_other_orbits_recoverable() {
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 other_id = Uuid::new_v4();
let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap();
@@ -959,7 +977,7 @@ mod tests {
#[test]
fn new_snapshots_are_encrypted_and_legacy_json_still_reads() {
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 = StoredSnapshot {
id: legacy_id,
@@ -1018,6 +1036,15 @@ mod tests {
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]
fn init_rejects_published_dev_passphrase() {
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
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
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
```
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
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
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
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.

View File

@@ -139,8 +139,8 @@ Tone: short sentences, metaphor in headings, facts in telemetry panels.
## 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.
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.
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:** 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.
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.

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.
- **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.
- 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

View File

@@ -1,89 +1,103 @@
# Kontrak otorisasi HTTP
# HTTP authorization contract
Inventaris A01, 11 November 2026. Gate saat ini masih admin global; kolom
permission/scope adalah kontrak yang harus diterapkan A11–A12, bukan klaim RBAC
sudah tersedia. A02 menutup isolasi upload legacy; A03 menghapus fallback loopback.
This is the authorization contract for every HTTP route the hub registers. The
`access_tests` suite generates its authorization matrix from the table below, and
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.
Mutasi cookie memerlukan CSRF. Anonymous/token salah: 401; resource di luar scope:
404; aksi tanpa permission pada resource terlihat: 403. Parsing request invalid
dapat menghasilkan 400/415/422 sebelum gate, tetapi tidak boleh mengakses data.
Outpost = token aktif, assignment owner dan lease/fence bila berlaku; bukan token
admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
A human is an active user session or a service token with a grant; an Outpost
token is rejected on human routes. Cookie-authenticated mutations require a CSRF
token. An anonymous caller or a wrong token gets 401. Request parsing errors may
answer 400, 415 or 422 before the gate, but never expose data. An Outpost is an
active token with an owner assignment and, where it applies, a lease or fence; it
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 |
| /api-doc/openapi.json | GET | public | — | — | schema tanpa config/secret |
| /api/v1/operator/session | GET | public | — | current session | status, actor, CSRF sesi sendiri; no-store |
| /api/v1/operator/session | DELETE | human | session.self | current session | tidak ada; CSRF wajib |
| /health | GET | public | — | — | static liveness |
| /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 and CSRF token of the caller's own session; no-store |
| /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/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/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 | 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/:id | DELETE | human | access.manage | admin | tidak ada; berlaku pada request berikutnya; diaudit |
| /api/v1/access/users | GET | human | access.manage | admin | daftar user (tanpa kredensial); 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/revoke-sessions | POST | human | access.manage | admin | tidak ada; semua sesi user berakhir |
| /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/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/environment | PUT | human | orbit.manage | admin | tidak ada; menandai sumber (production/staging/development); diaudit |
| /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/environment | PUT | human | relation.manage | admin | relasi aktif ke target yang diberi label production berakhir seketika; diaudit |
| /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/:id | PUT,DELETE | human | relation.manage | admin | PUT = versi baru (id baru, grant tidak ikut); DELETE menonaktifkan; diaudit |
| /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/:grant | DELETE | human | relation.manage | admin | berlaku pada request berikutnya; diaudit |
| /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-runs | GET,POST | human | refresh.run | relasi yang di-grant | POST: relation_id + konfirmasi `REFRESH <sumber> TO <target> v<versi>` + kunci idempotensi; `undo_of` opsional (id run restore terbaru pada targetnya yang selesai, direkonsiliasi, atau gagal saat apply): kembalikan target dari safety copy restore itu (422 `nothing_to_undo`; safety hanya diterima untuk target asalnya); `snapshot_id` opsional: restore snapshot yang sudah ada milik orbit sumber relasi itu (bukan safety, bukan orbit lain; 422 `snapshot_unusable`), tanpa itu run mengambil capture baru; tidak memilih target; 404 bila bukan pemegang grant; GET: run milik sendiri atau relasi yang di-grant (admin: semua), tanpa snapshot id dan pemohon untuk non-admin |
| /api/v1/refresh-runs/: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/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin |
| /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/orbits | GET | human | orbit.read | orbit | metadata tanpa provider_config |
| /api/v1/orbits | POST | human | orbit.manage | admin | metadata aman |
| /api/v1/orbits/:id/retention | PUT | human | retention.manage | orbit | tidak ada |
| /api/v1/orbits/:id/run | POST | human | capture.run | orbit | job/status aman |
| /api/v1/orbits/:id/outpost | PUT | human | outpost.manage | orbit | assignment eksplisit legacy; managed lewat capture profile |
| /api/v1/reconstitute | POST | human | recovery.manage | snapshot→orbit | sesi restore administratif, bukan self-service |
| /api/v1/reconstitute/:id | GET,DELETE | human | recovery.manage | restore session→snapshot→orbit | status aman; cancel sebelum apply |
| /api/v1/wormhole/outposts | GET | human | outpost.manage | admin | nama/status; tanpa token |
| /api/v1/wormhole/pairing | POST | human | outpost.manage | admin | code berumur pendek |
| /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/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/revoke | POST | human | outpost.manage | Outpost | tidak ada; semua kredensial ditolak pada request berikutnya; audit |
| /api/v1/wormhole/upload/init | POST | outpost | upload.assigned | orbit owner | session ID milik owner |
| /api/v1/wormhole/upload/chunk | POST | outpost | upload.assigned | session owner + orbit owner | tidak ada |
| /api/v1/wormhole/restic/commit | POST | outpost | upload.assigned | orbit owner + repository owner | snapshot ID owner |
| /api/v1/capture-profiles | GET | human | orbit.read | profile→orbit | profile terfilter; tanpa DSN |
| /api/v1/capture-profiles | POST | human | orbit.manage | orbit | profile aman |
| /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/jobs | POST | human | capture.run | profile→orbit | job aman |
| /api/v1/capture-jobs | GET | human | orbit.read | job→orbit | histori terfilter |
| /api/v1/capture-jobs/:id | GET | human | orbit.read | job→orbit | status aman |
| /api/v1/capture-jobs/:id/events | GET | human | orbit.read | job→orbit | phase/timestamp tanpa log DB |
| /api/v1/wormhole/capture/:application/claim | POST | outpost | capture.assigned | profile owner | lease milik owner |
| /api/v1/wormhole/capture/:id/report | POST | outpost | capture.assigned | job owner + lease | tidak ada |
| /api/v1/wormhole/capture/:id/payload | POST | outpost | capture.assigned | job owner + lease | tidak ada |
| /api/v1/wormhole/capture/:id/restic | POST | outpost | capture.assigned | job owner + lease + repository | commit owner |
| /api/v1/restore-targets | POST | human | orbit.manage | target→orbit | identity terverifikasi admin; tanpa kredensial |
| /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/snapshots/:id/restore-targets | GET | human | recovery.manage | admin | identity target hanya untuk admin sampai self-service M6; tanpa kredensial |
| /api/v1/restore-jobs | GET,POST | human | recovery.manage | admin | restore administratif dan daftar terbaru; refresh.run lewat relasi terpisah (M6) |
| /api/v1/snapshots/:id/restore-jobs | GET | human | recovery.manage | admin | histori restore memuat target dan aktor; admin saja sampai M6 |
| /api/v1/restore-jobs/:id | GET,DELETE | human | recovery.manage | job→snapshot + target | status aman; cancel sebelum apply |
| /api/v1/restore-jobs/:id/reconcile | POST | human | recovery.manage | job→target | status recovery admin |
| /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: 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 | nothing; effective on the next request; audited |
| /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 | 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 | nothing; all of the user's sessions end |
| /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 | 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 | nothing; labels the source (production, staging or development); audited |
| /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 | active relations to a target labelled production end immediately; audited |
| /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 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 | `refresh.run` grants per relation (user or group, expiry); audited |
| /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 | 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 | 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, 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 | opaque cookie and CSRF token; rate limited, no-store |
| /api/v1/snapshots | GET | human | snapshot.read | orbit | filtered, safe metadata |
| /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 | 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 without provider_config |
| /api/v1/orbits | POST | human | orbit.manage | admin | safe metadata |
| /api/v1/orbits/:id/retention | PUT | human | retention.manage | orbit | nothing |
| /api/v1/orbits/:id/run | POST | human | capture.run | orbit | safe job and status |
| /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 | administrative restore session, not self-service |
| /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 | names and status; no tokens |
| /api/v1/wormhole/pairing | POST | human | outpost.manage | admin | short-lived code |
| /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 | 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 | nothing; every credential is rejected from the next request; audited |
| /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 | nothing |
| /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 | filtered profiles; no DSN |
| /api/v1/capture-profiles | POST | human | orbit.manage | orbit | safe profile |
| /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 | safe job |
| /api/v1/capture-jobs | GET | human | orbit.read | job→orbit | filtered history |
| /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 | phases and timestamps, no database logs |
| /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 | nothing |
| /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 of the owner |
| /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 | target identity (instance, database) for admins only; no credentials |
| /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 | 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 | restore history with target and actor; admin only |
| /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 | administrative recovery status |
| /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/report | POST | outpost | restore.assigned | job owner + lease/fence | tidak ada |
| /api/v1/wormhole/restore/:id/safety | POST | outpost | restore.assigned | job owner + lease/fence | safety snapshot owner |
| /api/v1/wormhole/restore/:id/apply | POST | outpost | restore.assigned | job owner + lease/fence | izin apply setelah revalidasi |
| /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 | nothing |
| /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 | permission to apply, after revalidation |
SPA/assets publik berisi UI statis, bukan data vault. GET juga menerima HEAD sesuai
Axum, dengan gate sama. Aksi refresh internal tidak memberikan capture.run bebas
atau snapshot.download. Recovery legacy tetap jalur admin dan tidak menjadi jalan
pintas refresh self-service.
The SPA and its assets are public and contain only the static UI, not vault data.
GET routes also answer HEAD, as Axum does, behind the same gate. Internal refresh
actions never grant free-standing `capture.run` or `snapshot.download`. Legacy
recovery stays an administrator path and is not a shortcut around self-service
refresh.

View File

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

View File

@@ -89,8 +89,8 @@ def main():
assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result
continue
assert result["status"] == "completed", (name, result)
target = root / f"{name}.sql"
session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": str(target)})
target = root / "hub" / "exports" / f"{name}.sql"
session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": target.name})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
sql = target.read_text()
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
snapshots = api("snapshots")
assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]}
dump = root / "backup.dump"
session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": str(dump)})
dump = root / "hub" / "exports" / "backup.dump"
session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": dump.name})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump)
restored = command("psql", *pg, "-d", "target_db", "-Atc",
@@ -174,7 +174,7 @@ def main():
})
assert "provider_config" not in legacy
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"))
for log in (hub_log, agent_log):
log.seek(0)

View File

@@ -49,7 +49,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False
hub_port = port()
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_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}"
log = cleanup.enter_context((root / "hub.log").open("w+"))
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):
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:
headers["X-Tessera-Upload-Token"] = token
headers.update(extra or {})

View File

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

View File

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

View File

@@ -2,7 +2,7 @@
<html lang="en">
<head>
<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>
</head>
<body class="bg-space-950 text-star-100 overflow-hidden">

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();