From 1a00a134348b6d38691b001f152d5e98ca018ca2 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 11:28:31 +0100 Subject: [PATCH] [docs] Legatus: CLAUDE.md, design (docs/01), protocol v1 (docs/02), README, MPL-2.0 licence, pre-commit hook --- .gitattributes | 1 + .githooks/pre-commit | 175 ++++++++++++++++ .githooks/test-pre-commit.sh | 255 ++++++++++++++++++++++++ .gitignore | 9 + CLAUDE.md | 42 ++++ LICENSE | 373 +++++++++++++++++++++++++++++++++++ README.md | 17 ++ docs/01_legatus.md | 123 ++++++++++++ docs/02_protocol.md | 153 ++++++++++++++ 9 files changed, 1148 insertions(+) create mode 100644 .gitattributes create mode 100644 .githooks/pre-commit create mode 100644 .githooks/test-pre-commit.sh create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 docs/01_legatus.md create mode 100644 docs/02_protocol.md diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..ca40a21 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,175 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# +# Pre-commit hook (shared with Ianitor). Rejects staged files that must never be in git: +# - binaries: any NUL byte anywhere in the staged blob (git attributes do not matter) +# - private keys: PEM/PKCS#8/OpenSSH/PGP blocks, SSH2 (RFC 4716) keys, PuTTY .ppk, +# age secret keys, JWK private keys (an object with "kty" RSA/EC/OKP and "d"), +# WireGuard private keys (wg-quick `PrivateKey =` or YAML `private_key:`), and +# key-store file names +# - files over 5 MB (5,000,000 bytes, as CLAUDE.md says) +# - build output and dependencies: target/, node_modules/, dist/, .svelte-kit/ anywhere; +# build/ at the repository root, in apps//, or next to a package.json +# Name checks are case-insensitive. Paths are read NUL-separated, so quotes, tabs, +# backslashes or newlines in file names cannot slip past. A staged file that cannot be read, +# or any git command that fails, blocks the commit. +# +# Contents are checked in a few batch passes over the index (one `git cat-file`, two +# `git grep`), not with processes per file. +# +# Enable once per clone: git config core.hooksPath .githooks +# Test it: bash .githooks/test-pre-commit.sh + +if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 4 ]; then + echo "pre-commit: needs bash 4 or newer (this is ${BASH_VERSION:-not bash}); commit blocked." >&2 + echo "pre-commit: use Git Bash on Windows, any Linux, or a newer bash on macOS." >&2 + exit 1 +fi + +set -u +LIMIT=5000000 + +# Patterns are written so that this file does not match them itself. They are matched +# case-insensitively. +KEY_PATTERNS=( + '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----' + '---- BEGIN SSH2 ENCRYPTED PRIVATE KEY[ ]----' + '---- BEGIN SSH2 PRIVATE KEY[ ]----' + 'PuTTY-User-Key-File-[0-9]+:' + 'AGE-SECRET-KEY-[1][0-9A-Z]+' + '^[[:space:]]*(-[[:space:]]*)?["'\'']?private_?key["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9+/]{42,43}=?["'\'']?[[:space:]]*,?[[:space:]]*$' +) +# One flat JSON object (JWK members are flat) holding a private-key parameter set. +JWK_OBJECT='\{[^{}]*\}' +JWK_KTY='"kt[y]"[[:space:]]*:[[:space:]]*"(RSA|EC|OKP)"' +JWK_D='"[d]"[[:space:]]*:[[:space:]]*"' + +failed=0 +reject() { + # %q keeps odd characters in names visible and harmless. + printf 'pre-commit: rejected %q: %s\n' "$1" "$2" >&2 + failed=1 +} +die() { + echo "pre-commit: $1; commit blocked." >&2 + exit 1 +} + +tmp=$(mktemp -d 2>/dev/null || { d="${TMPDIR:-/tmp}/ianitor-pre-commit.$$"; mkdir -p "$d" && echo "$d"; }) || + die "cannot create a temporary directory" +trap 'rm -rf "$tmp"' EXIT + +git diff --cached --raw -z --no-abbrev --no-renames --diff-filter=ACMT >"$tmp/list" || + die "cannot list the staged files" +git ls-files -z -- ':(glob)**/package.json' >"$tmp/packages" || + die "cannot list package.json files" + +declare -A staged=() pkgdir=() +paths=() shas=() + +while IFS= read -r -d '' p; do + d=${p%package.json} + d=${d%/} + # The root package.json needs no entry: build/ at the root is always output. + [ -n "$d" ] && pkgdir[${d,,}]=1 +done <"$tmp/packages" + +# build/ is output only at the root, in apps// or beside a package.json. +is_build_output() { + local lower=$1 prefix= + [[ $lower == build/* || $lower =~ ^apps/[^/]+/build/ ]] && return 0 + local rest=$lower part + while [[ $rest == */* ]]; do + part=${rest%%/*} + rest=${rest#*/} + if [[ $part == build && -n $prefix && -n ${pkgdir[${prefix%/}]+x} ]]; then + return 0 + fi + prefix+="$part/" + done + return 1 +} + +# --raw -z gives ": " NUL "" NUL. +while IFS= read -r -d '' meta && IFS= read -r -d '' path; do + read -r -a f <<<"${meta#:}" + mode=${f[1]} sha=${f[3]} + lower=${path,,} + + case "/$lower" in + */target/*|*/node_modules/*|*/dist/*|*/.svelte-kit/*) + reject "$path" "build output or dependency directory" ;; + esac + if is_build_output "$lower"; then + reject "$path" "build output directory" + fi + + base=${lower##*/} + case "$base" in + *.pub) ;; + *.key|*.p12|*.pfx|*.jks|*.keystore|*.ppk|id_rsa|id_dsa|id_ecdsa|id_ed25519|id_rsa.*|id_dsa.*|id_ecdsa.*|id_ed25519.*) + reject "$path" "private key file name" ;; + esac + + # Submodule entries have no blob to inspect. + [ "$mode" = 160000 ] && continue + staged[$path]=$sha + paths+=("$path") + shas+=("$sha") +done <"$tmp/list" + +if [ "${#paths[@]}" -gt 0 ]; then + # Sizes: one batch for every blob, in order. + printf '%s\n' "${shas[@]}" | git cat-file --batch-check='%(objectname) %(objecttype) %(objectsize)' >"$tmp/sizes" || + die "cannot read the staged blobs" + i=0 + while read -r _ type size; do + p=${paths[$i]} + if [ "$type" != blob ] || ! [[ $size =~ ^[0-9]+$ ]]; then + reject "$p" "the staged content cannot be read" + elif (( size > LIMIT )); then + reject "$p" "$size bytes is over the 5 MB limit (5,000,000 bytes)" + fi + i=$((i + 1)) + done <"$tmp/sizes" + [ "$i" -eq "${#paths[@]}" ] || die "cannot read the size of every staged blob" + + # Contents: git grep over the index, every file read as text (-a), names NUL-separated, + # then kept only when staged. Exit 1 means no match; anything above blocks the commit. + search() { + local out=$1 rc + shift + git -c grep.fullName=true -c color.grep=never grep --cached --no-recurse-submodules \ + -a -l -z "$@" >"$out" + rc=$? + [ "$rc" -le 1 ] || die "git grep failed (exit $rc)" + } + + search "$tmp/nul" -P '\x00' + while IFS= read -r -d '' p; do + [ -n "${staged[$p]+x}" ] && reject "$p" "binary file (contains NUL bytes)" + done <"$tmp/nul" + + args=() + for pattern in "${KEY_PATTERNS[@]}"; do args+=(-e "$pattern"); done + search "$tmp/keys" -i -E "${args[@]}" + while IFS= read -r -d '' p; do + [ -n "${staged[$p]+x}" ] && reject "$p" "contains a private key" + done <"$tmp/keys" + + # JWK members may span lines, so candidates are flattened and split into objects. + search "$tmp/jwk" -F -e '"kt''y"' + while IFS= read -r -d '' p; do + [ -n "${staged[$p]+x}" ] || continue + if git cat-file blob "${staged[$p]}" | tr '\r\n\t' ' ' | grep -a -o -E "$JWK_OBJECT" | + grep -a -E "$JWK_KTY" | grep -a -q -E "$JWK_D"; then + reject "$p" "contains a JWK private key" + fi + done <"$tmp/jwk" +fi + +if [ "$failed" -ne 0 ]; then + echo 'pre-commit: commit blocked. Unstage the files above (git rm --cached ).' >&2 + exit 1 +fi +exit 0 diff --git a/.githooks/test-pre-commit.sh b/.githooks/test-pre-commit.sh new file mode 100644 index 0000000..771e14a --- /dev/null +++ b/.githooks/test-pre-commit.sh @@ -0,0 +1,255 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# +# Self-test for .githooks/pre-commit. Creates a throw-away repository, points it at the +# hook and checks that every forbidden case is rejected and normal files are accepted. +# Includes every bypass QC found (odd file names, attributes, NULs late in a file, 5 MB +# boundary, other key formats). Usage: bash .githooks/test-pre-commit.sh (Git Bash or Linux) + +set -u +HOOKS=$(cd "$(dirname "$0")" && pwd) +WORK=$(mktemp -d 2>/dev/null || mktemp -d -t ianitor-hook) +trap 'rm -rf "$WORK"' EXIT INT TERM + +cd "$WORK" || exit 2 +git init -q . +git config user.name hook-test +git config user.email hook-test@invalid +git config core.hooksPath "$HOOKS" +git config core.autocrlf false +# Allow index entries Windows cannot check out ("quotes", tabs, backslashes) so the hook +# itself is what rejects them. +git config core.protectNTFS false +git commit -q --allow-empty -m base --no-gpg-sign + +pass=0 +fail=0 + +commit_and_check() { + local want=$1 what=$2 got + if git commit -q -m "$what" --no-gpg-sign >/dev/null 2>"$WORK/.err"; then + got=accept + elif grep -q 'pre-commit: rejected' "$WORK/.err"; then + got=reject + else + got="error ($(head -c 200 "$WORK/.err"))" # failed, but not because of the hook + fi + if [ "$got" = "$want" ]; then + pass=$((pass + 1)); printf 'ok %-7s %s\n' "$want" "$what" + else + fail=$((fail + 1)); printf 'FAIL wanted %s, got %s: %s\n' "$want" "$got" "$what"; cat "$WORK/.err" + fi + git reset -q --hard HEAD >/dev/null 2>&1 + git clean -q -fdx -e .err >/dev/null 2>&1 +} + +# expect (file must exist in the work tree) +expect() { + git add -f -- "$3" + commit_and_check "$1" "$2" +} + +# expect_staged +# Stages content under a path that may be impossible to create on this file system +# (quotes, tabs or backslashes in names on Windows). +expect_staged() { + local sha + sha=$(git hash-object -w -- "$4") + if ! git update-index --add --cacheinfo "100644,$sha,$3"; then + fail=$((fail + 1)); printf 'FAIL could not stage the test path: %s +' "$2" + return + fi + commit_and_check "$1" "$2" +} + +B='-----BEGIN' +E='-----END' +# An absolute path next to $WORK (not "$WORK/..", which no longer resolves once $WORK is gone), +# removed first. +SRC="$(dirname "$WORK")/ianitor-hook-src.$$" +mkdir -p "$SRC" || exit 2 +trap 'rm -rf "$SRC" "$WORK"' EXIT INT TERM +printf '%s RSA PRIVATE KEY-----\nMIIBOgIBAAJBAK\n%s RSA PRIVATE KEY-----\n' "$B" "$E" > "$SRC/pem" +head -c 6291456 /dev/zero | tr '\000' 'a' > "$SRC/six-mb" + +printf 'hello\n' > readme.txt +expect accept "plain text file" readme.txt + +printf 'fn main() {}\n' > main.rs +expect accept "source file" main.rs + +printf '\000\001\002\003binary\000' > blob.bin +expect reject "binary file" blob.bin + +{ head -c 10000 /dev/zero | tr '\000' 'a'; printf '\000tail'; } > late-nul.txt +expect reject "NUL byte after the first 8000 bytes" late-nul.txt + +printf '*.dat diff\n' > .gitattributes +expect accept ".gitattributes marking *.dat as text" .gitattributes +printf 'abc\000def' > forced.dat +expect reject "binary file that .gitattributes calls text" forced.dat + +cp "$SRC/pem" notes.txt +expect reject "PEM RSA private key in a .txt file" notes.txt + +printf '%s PRIVATE KEY-----\nMIGHAgEAMBMG\n%s PRIVATE KEY-----\n' "$B" "$E" > pkcs8.pem +expect reject "PKCS#8 private key" pkcs8.pem + +printf '%s ENCRYPTED PRIVATE KEY-----\nMIIFHDBOBgkq\n%s ENCRYPTED PRIVATE KEY-----\n' "$B" "$E" > enc.pem +expect reject "encrypted PKCS#8 private key" enc.pem + +printf '%s EC PRIVATE KEY-----\nMHcCAQEEI\n%s EC PRIVATE KEY-----\n' "$B" "$E" > ec.txt +expect reject "EC private key" ec.txt + +printf '%s OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA\n%s OPENSSH PRIVATE KEY-----\n' "$B" "$E" > deploy +expect reject "OpenSSH private key" deploy + +printf -- '---- BEGIN SSH2 ENCRYPTED PRIVATE %s ----\nP2/56wAAA\n' KEY > ssh2.txt +expect reject "SSH2 (RFC 4716) encrypted private key" ssh2.txt + +printf 'PuTTY-User-Key-File-%s: ssh-ed25519\nEncryption: none\n' 3 > putty.txt +expect reject "PuTTY private key content" putty.txt + +printf 'not really a key\n' > me.ppk +expect reject "*.ppk file name" me.ppk + +printf '# created: 2026\nage-secret-key-%s\n' 1qyz8xrfk3w6j9p2m4n5l7kxqzj5s8tvh3r2w6y9 > lower.txt +expect reject "age secret key in lower case" lower.txt + +printf '# created: 2026\nAGE-SECRET-KEY-%s\n' 1QYZ8XRFK3W6J9P2M4N5L7KXQZJ5S8TVH3R2W6Y9 > identity.txt +expect reject "age secret key" identity.txt + +printf '{"k%s":"EC","crv":"P-256","x":"f83O","y":"x_FE","d":"jpsQ"}\n' ty > key.json +expect reject "JWK private key" key.json + +printf '{"k%s":"EC","crv":"P-256","x":"f83O","y":"x_FE"}\n' ty > pub.json +expect accept "JWK public key" pub.json + +printf '{\n "k%s"\n : "RSA",\n "n": "0vx7",\n "e": "AQAB",\n "d"\n :\n "X4cT"\n}\n' ty > rsa.json +expect reject "JWK private key across lines, newline before the colon" rsa.json + +printf '{"keys":[{"k%s":"OKP","crv":"Ed25519","x":"11qY","d":"nWGx"}]}\n' ty > jwks.json +expect reject "OKP private key inside a JWKS" jwks.json + +printf '{"jwk":{"k%s":"EC","x":"f83O","y":"x_FE"},"meta":{"d":"2026-11-07"}}\n' ty > mixed.json +expect accept "JWK public key with an unrelated \"d\" in another object" mixed.json + +printf '{"k%s":"oct","k":"GawgguFy","d":"not a private-key parameter"}\n' ty > oct.json +expect accept "\"d\" with kty oct is not an RSA/EC/OKP private key" oct.json + +printf '[Interface]\nPrivate%s = %s\nAddress = 10.0.0.2/32\n' Key yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= > wg0.conf +expect reject "WireGuard private key" wg0.conf + +printf 'wireguard:\n interface:\n private_%s: yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\n' key > wg.yaml +expect reject "WireGuard private_key in YAML" wg.yaml + +printf 'peers:\n - private_%s: "yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk="\n' key > wg2.yml +expect reject "WireGuard private_key in a YAML list, quoted" wg2.yml + +printf 'private_%s_file: /run/secrets/wg\n' key > wg3.yaml +expect accept "WireGuard private_key_file path (no key)" wg3.yaml + +printf '*.txt binary\n' > .gitattributes && cp "$SRC/pem" attr.txt && git add .gitattributes +expect reject "PEM key in a file .gitattributes marks binary" attr.txt + +printf 'not really a key\n' > server.key +expect reject "*.key file name" server.key + +printf 'not really a key\n' > SERVER.KEY +expect reject "*.KEY file name in upper case" SERVER.KEY + +printf 'not really a key\n' > id_ed25519 +expect reject "id_ed25519 file name" id_ed25519 + +printf 'ssh-ed25519 AAAAC3Nza test\n' > id_ed25519.pub +expect accept "public key id_ed25519.pub" id_ed25519.pub + +printf '%s CERTIFICATE-----\nMIIBszCCAVmg\n%s CERTIFICATE-----\n' "$B" "$E" > cert.pem +expect accept "certificate (public) PEM" cert.pem + +cp "$SRC/six-mb" big.txt +expect reject "6 MB text file" big.txt + +head -c 5000001 /dev/zero | tr '\000' 'a' > over.txt +expect reject "5,000,001 bytes" over.txt + +head -c 5242880 /dev/zero | tr '\000' 'a' > mib.txt +expect reject "5 MiB (5,242,880 bytes)" mib.txt + +head -c 5000000 /dev/zero | tr '\000' 'a' > exact.txt +expect accept "exactly 5,000,000 bytes" exact.txt + +mkdir -p crates/x/target/debug && printf 'x\n' > crates/x/target/debug/out.txt +expect reject "file under target/" crates/x/target/debug/out.txt + +mkdir -p TARGET && printf 'x\n' > TARGET/out.txt +expect reject "file under TARGET/ (upper case)" TARGET/out.txt + +mkdir -p apps/web/node_modules/pkg && printf 'x\n' > apps/web/node_modules/pkg/index.js +expect reject "file under node_modules/" apps/web/node_modules/pkg/index.js + +mkdir -p apps/web/dist && printf 'x\n' > apps/web/dist/index.html +expect reject "file under dist/" apps/web/dist/index.html + +mkdir -p apps/web/build && printf 'x\n' > apps/web/build/index.html +expect reject "file under apps//build/" apps/web/build/index.html + +mkdir -p build && printf 'x\n' > build/out.js +expect reject "file under build/ at the root" build/out.js + +mkdir -p crates/x/src/build && printf 'pub mod x;\n' > crates/x/src/build/mod.rs +expect accept "source module named build (crates/x/src/build/mod.rs)" crates/x/src/build/mod.rs + +mkdir -p apps/web/src/build && printf 'x\n' > apps/web/src/build/x.ts +expect accept "apps/web/src/build/ is not output" apps/web/src/build/x.ts + +mkdir -p packages/ui/build && printf '{}\n' > packages/ui/package.json && printf 'x\n' > packages/ui/build/ui.js +git add packages/ui/package.json +expect reject "build/ next to a package.json" packages/ui/build/ui.js + +mkdir -p docs/build && printf 'x\n' > docs/build/notes.md +expect accept "build/ with no package.json beside it" docs/build/notes.md + +mkdir -p apps/web/.svelte-kit && printf 'x\n' > apps/web/.svelte-kit/env.js +expect reject "file under .svelte-kit/" apps/web/.svelte-kit/env.js + +# Names git would C-quote: only reachable through the index on Windows. +expect_staged reject "PEM key in a file named with a double quote" 'a"b.txt' "$SRC/pem" +expect_staged reject "PEM key in a file named with a tab" "$(printf 'tab\tx.txt')" "$SRC/pem" +expect_staged reject "6 MB file named with a backslash" 'big\file.txt' "$SRC/six-mb" +expect_staged reject "*.key named with a backslash" 'srv\x.key' "$SRC/pem" +expect_staged reject "PEM key in a file named with a newline" "$(printf 'new\nline.txt')" "$SRC/pem" +printf 'fine\n' > "$SRC/fine" +expect_staged accept "harmless file named with a double quote" 'say"hi".txt' "$SRC/fine" + +# Bash 3 or a POSIX sh: the hook refuses with a clear message. Only testable where sh is +# not bash (dash on Debian); Git Bash's sh is bash. +if [ -z "$(sh -c 'echo "${BASH_VERSION:-}"')" ]; then + printf 'x\n' > shtest.txt && git add shtest.txt + if sh "$HOOKS/pre-commit" 2>"$WORK/.err"; then + fail=$((fail + 1)); echo "FAIL the hook ran under a shell that is not bash 4" + elif grep -q 'needs bash 4' "$WORK/.err"; then + pass=$((pass + 1)); echo "ok reject run by sh (not bash): clear message" + else + fail=$((fail + 1)); echo "FAIL no clear message under sh:"; cat "$WORK/.err" + fi + git reset -q --hard HEAD; git clean -q -fdx -e .err +else + echo "skip sh is bash here; the bash-4 check is exercised where sh is dash" +fi + +# Speed: 300 ordinary files in one commit. +mkdir -p many +for n in $(seq 1 300); do printf 'line %d\n' "$n" > "many/f$n.txt"; done +git add many +start=$(date +%s%N) +commit_and_check accept "300 ordinary files in one commit" +ms=$(( ($(date +%s%N) - start) / 1000000 )) +printf ' (300 files: %d ms)\n' "$ms" +if [ "$ms" -gt 10000 ]; then + fail=$((fail + 1)); echo "FAIL 300 files took over 10 s" +fi + +printf '\nhook: %d passed, %d failed\n' "$pass" "$fail" +[ "$fail" -eq 0 ] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..964596b --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +target/ +*.key +*.p12 +*.pfx +.env +.env.* +*.log +.idea/ +.vscode/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..111afaa --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,42 @@ +# CLAUDE.md — Legatus + +Legatus is Fabrica Domi's agent: one small Rust binary per OS, installed with one copied command. Two roles Fabrica +toggles: *build here* and *deploy here*. It connects outbound only, to the Fabrica server, over mTLS (its client +certificate from domi-pki, the root in Custos). Nothing unsigned runs: before it touches anything it checks the +release's signature against the team's release key. MPL-2.0. Read docs/01_legatus.md (design) and +docs/02_protocol.md (the wire protocol Fabrica implements) first. + +## Layout +crates/protocol legatus-protocol: PURE. Enrollment codes and their single use, messages (enroll, hello, job, + report, renew), the job replay guard, the agent registry (which certificate is current), the + release manifest and its signature check. No I/O, no clock: the caller passes `now`. +crates/linux legatus-linux: the Linux (systemd) target: versioned release dirs, atomic symlink switch, + systemd restart, health check, auto rollback. Unix only. +crates/agent legatus (the binary): state dir, the HTTPS/mTLS client (rustls, root pinned from the + enrollment code), enroll, the job loop, the deploy pipeline (download, verify, unpack, backend). +install/ the one-line installer (install.sh) Fabrica serves. +tests/linux the container integration test of the Linux target (real systemd). + +## Commands +cargo test --workspace # quote test counts per crate; an exit code alone is not green +cargo clippy --workspace --all-targets -- -D warnings +tests/linux/run.sh # Linux target against real systemd in a container (needs Docker/Podman) +On Mark's PC: CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo, CARGO_TARGET_DIR=D:\cargo-target\legatus. +The Linux backend's own tests run on Linux only (`cfg(target_os = "linux")`). +One-time per clone: git config core.hooksPath .githooks (self-test: bash .githooks/test-pre-commit.sh) + +## Rules +- Everything from the network is hostile: messages, jobs, manifests, signatures, artifacts (tar entries), certificates. + Typed `Result`, size limits, no `unwrap()`/`expect()`/`panic!` outside tests (clippy denies them). +- Nothing unsigned runs: the signature is checked before any byte of an artifact is unpacked; a refusal is reported. +- Outbound only. Legatus never listens on a port. +- The protocol crate stays pure; transport, files and processes live in `agent` and `linux`. +- Tests first where the risk is: enrollment, certificates, signatures, the job guard, tar unpacking, switch and rollback. +- Secrets (the agent key, enrollment codes) never in logs, files in git, or error messages. The key file is 0600. +- Commits: `[] : `. No AI attribution, no trailers, ever. +- Never in git: target/, binaries, private keys, files over 5 MB (the pre-commit hook enforces it). +- $GITEA_TOKEN is never echoed or written anywhere. +- Workflow: branch → Gitea PR via API → short adversarial self-review in the PR body → merge --no-ff → push → + `git rev-parse HEAD origin/main`. +- Disks on Mark's PC: nothing on C:. Build output on D:\cargo-target, containers on D:. +- The README says "Built, tested and signed by Fabrica Domi" only once Fabrica really builds, tests and signs it. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d0a1fa1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..63845be --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# Legatus + +The small Fabrica Domi agent. Installed with one copied command, it connects **outbound only** to your Fabrica server +over mTLS, and does two jobs you switch on in Fabrica: **build here** and **deploy here**. + +**Nothing unsigned runs:** before Legatus touches anything it checks the release's signature against your team's +release key. Unsigned, wrongly signed or tampered releases are refused and reported. + +```sh +curl -fsSL https:///legatus/install.sh | sudo sh -s -- lgt1- +``` + +Status: v0.1, foundations: enrollment, mTLS, the signature check, and the Linux (systemd) target with atomic switch +and automatic rollback. Docker, Kubernetes, NixOS and Windows Server targets come next. + +Design: [docs/01_legatus.md](docs/01_legatus.md). Protocol: [docs/02_protocol.md](docs/02_protocol.md). +Licence: MPL-2.0. diff --git a/docs/01_legatus.md b/docs/01_legatus.md new file mode 100644 index 0000000..ef0ae16 --- /dev/null +++ b/docs/01_legatus.md @@ -0,0 +1,123 @@ +# 01 · Legatus v0.1: the agent's foundations + +Phase T3a of Fabrica's coherence roadmap (`docs/32_coherence.md`, 2.2–2.4). Legatus (envoy) acts for Fabrica on a +machine: it builds there (*build here*) and deploys there (*deploy here*). This page is the design; the wire protocol +Fabrica implements is [02_protocol.md](02_protocol.md). + +## The promise it keeps + +> **Nothing unsigned runs.** The agent refuses any release whose signature does not chain to the team's release key. + +And: no inbound ports (it dials out), one copied command to install, and every refusal is reported to Fabrica, never +silent. + +## Pieces + +| Crate | What | Pure? | +|:--|:--|:--| +| `legatus-protocol` | enrollment codes and their single use, the messages, the job guard, the agent registry, the release manifest and its signature check, safe archive paths | yes | +| `legatus-linux` | the Linux (systemd) target: release dirs, atomic switch, restart, health, rollback | no (files, `systemctl`) | +| `legatus` | the binary: state, HTTPS/mTLS client, enroll, the job loop, the deploy pipeline | no | + +The server side (Fabrica, T3b) uses `legatus-protocol` and `domi-pki` and implements 02_protocol.md. + +## Install (one copied command) + +Fabrica's *Add target* shows one line with a fresh enrollment code: + +```sh +curl -fsSL https://fabrica.example/legatus/install.sh | sudo sh -s -- lgt1- +``` + +`install.sh` downloads the Legatus binary for this OS and CPU from the same origin, checks its SHA-256 against the +`SHA256SUMS` beside it (and the minisign signature when `minisign` is installed), installs it to +`/usr/local/bin/legatus`, runs `legatus enroll ` and starts `legatus.service`. + +Trust: the very first download trusts the HTTPS origin, as every `curl | sh` does. From `legatus enroll` on, nothing +is trusted on the network's word: the code pins the Domi root, the root pins the server, the server's certificate pins +the agent, and the team's release key pins every release. + +## The enrollment code + +`lgt1-` and lowercase base32 of: version, the SHA-256 of the Domi root certificate, a 128-bit secret, the server URL, +and a 4-byte checksum (typos are caught before anything is sent). Single use and short-lived (one hour by default). +Fabrica stores only the secret's SHA-256, so a copy of its database does not hold live codes. + +`legatus enroll` makes the agent's key (ECDSA P-256, `0600`, never leaves the machine), sends a CSR with the secret +over TLS to the server, accepts the server only if its chain ends at the pinned root, and gets back its agent +certificate (domi-pki, 30 days), its team and agent ids, its roles, and the team's release keys, which it pins. + +## The connection + +Outbound HTTPS to the Fabrica server with the agent certificate (mTLS). The agent long-polls for jobs and posts +reports; no WebSocket, no inbound port, works through any HTTP-friendly network. The server is checked against the +pinned root and its host name on every connection; the agent's certificate is checked by Fabrica with +`legatus_protocol::Registry` on every request. + +Certificates are refused when: + +- **expired** or not yet valid (both directions); +- **replayed**: an agent certificate that is no longer the agent's current one (renewed, re-enrolled) or of an agent + that was removed; +- **foreign**: another root, a Domi certificate that is not an agent's (a phone's device certificate), an agent of + another team, or a chain that skips the agents intermediate. + +The agent renews its certificate over the existing connection when 10 days are left. + +## Roles + +`build` and `deploy`, both off after enrollment unless the code grants them; Fabrica toggles them with a `config` +job. A job for a role that is off is refused and reported. Legatus 0.1 reports `build: []` in its capabilities: the +build role's executor (Fabrica's runner) comes later; the toggle and its enforcement exist now. + +## Before touching anything: the release check + +A deploy job carries the release manifest (the exact signed bytes) and its minisign signature. The agent: + +1. checks the signature with the release keys it pinned at enrollment (a missing signature, an unknown key or a bad + signature: refused); +2. reads the manifest strictly: its team must be the agent's team, its app and version the job's, the artifact named + exactly once; +3. downloads the artifact over mTLS, no larger than the manifest says, and checks its SHA-256 (a tampered artifact: + refused, deleted); +4. only then unpacks it (regular files and directories only; no absolute paths, no `..`, no links, size and count + limits) and hands it to the target backend. + +Release keys change only by re-enrolling in v0.1, never by a message from the server: a compromised server alone cannot +make the agent run something the team did not sign. (A key rotation signed by a current key is for later.) + +Jobs are guarded against replay: each has a 128-bit id, an issue time and an expiry (at most one hour later); an +expired job, a job from the future, or an id seen before is refused. Seen ids survive restarts. + +## The Linux target (systemd) + +```text +/var/lib/legatus/apps//releases// one dir per release, unpacked from the signed artifact +/var/lib/legatus/apps//current -> releases/ +``` + +Deploy: unpack into `releases/.incoming-…`, rename to `releases/`, point a new symlink at it and `rename(2)` +it over `current` (atomic: a reader sees the old or the new release, never neither), `systemctl restart `, then +the health check: the unit is active and, when the job gives one, a local health URL (`http://127.0.0.1…`, +`localhost` or `[::1]` only) answers 2xx, within the timeout. On a failed check: switch `current` back to the +previous release, restart, check again, and report `failed` with `rolled_back`. Old releases are pruned, keeping the +newest three plus whatever `current` and the previous point at. + +The unit file itself is the user's (or, from T3b, generated by Fabrica's UI); its `ExecStart` runs from `current/`. + +## Tests (first) + +- the enrollment code: round trip, typos caught, single use (twice: refused), expired refused, unknown refused; +- certificates: expired, replayed (superseded, removed agent) and foreign (other root, device certificate, other team, + wrong intermediate) refused, by the registry and on a real TLS handshake both ways; +- releases: a tampered artifact, a wrong key, a missing or garbled signature, a manifest for another app, version or + team: refused, and the backend is never called; +- the job guard: expired, future, too long-lived and replayed jobs refused; +- archive paths: absolute, `..`, links, device files refused; +- Linux: the atomic switch, the health check, auto rollback on a failed check, pruning (on Linux; and in a container + with real systemd: `tests/linux/run.sh`). + +## Out of scope for v0.1 (T3b, T5) + +The other four targets (NixOS, Windows Server, Docker, Kubernetes), the build executor, Fabrica's server side and UI, +the Windows installer, `.deb`/`.rpm`, remote operations (logs, restart, rollback on demand), signed key rotation. diff --git a/docs/02_protocol.md b/docs/02_protocol.md new file mode 100644 index 0000000..28b2489 --- /dev/null +++ b/docs/02_protocol.md @@ -0,0 +1,153 @@ +# 02 · The Legatus protocol, version 1 + +What the agent and the Fabrica server say to each other. The types, limits and checks are in the pure crate +`legatus-protocol`; Fabrica implements the server side with that crate and `domi-pki` (handover: +Fabrica `docs/handover/t3a-legatus-protocol.md`). Everything a party receives is hostile until checked. + +## Transport + +- HTTPS (HTTP/1.1, TLS 1.3 or 1.2) to `https:///legatus/v1/…`; the server is the one in the enrollment code. +- **The agent only dials out.** It never listens. +- **The server's chain** is leaf, the intermediate, and the Domi root itself (the agent pins the root by its SHA-256 + until it has stored it). The leaf must be valid for the server's host name and for serverAuth. Fabrica issues it with + `domi_pki::issue_server` from the agents intermediate. +- **The agent's certificate** (mTLS) is required on every endpoint but `enroll`. The server's TLS layer asks for a + client certificate without requiring one; the application checks it per request with + `legatus_protocol::Registry::accept` (domi-pki `verify_agent` and the registry) and answers `401` when it is absent, + `403 certificate_refused` when it is refused. +- Bodies are JSON (`application/json`, UTF-8), at most 256 KiB, unknown fields refused. Every message has `"v": 1`. +- Errors: the HTTP status and `{"error": "", "message": ""}`. +- Times are unix seconds (UTC). Each side allows 5 minutes of clock skew. + +## Enrollment + +### The code (made by Fabrica, shown in *Add target*) + +`lgt1-` followed by lowercase RFC 4648 base32 (no padding) of: + +| Bytes | Field | +|:--|:--| +| 1 | version, `1` | +| 32 | SHA-256 of the Domi root certificate (DER) | +| 16 | secret, random | +| 1 | `n`, length of the server URL, 1–200 | +| n | server URL: `https://host` or `https://host:port`, nothing else | +| 4 | the first 4 bytes of SHA-256 of everything before | + +Fabrica keeps `{sha256(secret), team, agent, roles, expires_at, used_at}`; it never stores the secret. +`EnrollmentBook::issue` / `redeem` is the reference logic: unknown, used and expired codes are refused, and a code is +used up by the first request that presents it, in one transaction (`UPDATE … SET used_at = now WHERE digest = ? AND +used_at IS NULL AND expires_at > now`). + +### `POST /legatus/v1/enroll` (TLS, no client certificate) + +```json +{ "v": 1, "secret": "<32 lowercase hex>", "csr": "-----BEGIN CERTIFICATE REQUEST-----…", + "host": { "hostname": "web-1", "os": "linux", "arch": "x86_64", "version": "0.1.0" } } +``` + +The server checks the CSR first (domi-pki: signature, ECDSA P-256), then redeems the code, then issues +`domi_pki::issue_agent(agents_intermediate, csr, team, agent, now)` and records the serial as the agent's current one +(re-enrolling an agent replaces it: its old certificate stops working). + +`200`: + +```json +{ "v": 1, "team": "acme", "agent": "web-1", + "chain": "", + "root": "", + "roles": { "build": false, "deploy": true }, + "release_keys": ["RWQ…base64 minisign public key…"], + "poll_seconds": 25 } +``` + +The agent checks that `root` hashes to the pinned SHA-256, that `chain` is an agent certificate for its own key under +that root (`verify_agent`), and stores all of it. `release_keys` must hold 1 to 8 keys; they are pinned. + +Refusals: `403 code_unknown`, `403 code_used`, `403 code_expired`, `400 bad_csr`, `400 bad_request`. + +## After enrollment (mTLS) + +### `POST /legatus/v1/hello` + +```json +{ "v": 1, "version": "0.1.0", "os": "linux", "arch": "x86_64", "hostname": "web-1", + "capabilities": { "deploy": ["linux"], "build": [] }, + "deployed": [ { "app": "shop", "version": "1.4.0" } ] } +``` + +`200`: `{ "v": 1, "team": "acme", "agent": "web-1", "roles": {…}, "server_time": 1800000000, "renew": false }`. +`renew: true` asks the agent to renew now (the server may also just let it renew at 10 days left). + +### `GET /legatus/v1/jobs?wait=` + +Long poll. `204` when there is nothing within `wait`; `200` with one job: + +```json +{ "v": 1, "id": "<32 lowercase hex>", "issued_at": 1800000000, "expires_at": 1800000600, + "kind": "deploy", "spec": { … } } +``` + +`expires_at` is at most 3600 s after `issued_at`. The agent refuses (and reports) a job that is expired, issued more +than 5 minutes in the future, lives too long, or whose id it has seen before (`JobGuard`). + +`kind` is one of: + +- `deploy`: + ```json + { "app": "shop", "version": "1.4.0", "artifact": "shop-linux-x86_64.tar.gz", + "release": { "manifest": "", + "signature": "" }, + "target": { "kind": "linux", + "linux": { "unit": "shop.service", "health_url": "http://127.0.0.1:8080/health", + "health_timeout_seconds": 30, "keep": 3 } } } + ``` +- `config`: `{ "roles": { "build": true, "deploy": true } }` (roles toggled in Fabrica). + +Any other `kind` (or target `kind`) is refused with `unsupported` and reported, so Fabrica sees what an older agent +cannot do. `build` is reserved for the build role's executor. + +### `GET /legatus/v1/artifacts//` + +The artifact's bytes (`application/octet-stream`, `Content-Length`). Only for a deploy job sent to this agent. + +### `POST /legatus/v1/reports` + +```json +{ "v": 1, "job": "", "at": 1800000010, "status": "succeeded", + "step": "health", "message": "shop 1.4.0 is running", "rolled_back": false, + "deployed": { "app": "shop", "version": "1.4.0" } } +``` + +`status`: `accepted`, `refused`, `running`, `succeeded`, `failed`. `step` (optional): `guard`, `role`, `verify`, +`download`, `unpack`, `switch`, `restart`, `health`, `rollback`. `refused` means nothing was touched. `failed` after +`switch` comes with `rolled_back` (true when the previous release is running again). `message` is plain English, at +most 2000 characters, and never holds a secret. `204` in reply. + +Refusal reasons the agent uses (in `message`, prefixed by a stable code): `role_off`, `expired`, `replayed`, +`future`, `unsupported`, `unsigned`, `unknown_key`, `bad_signature`, `bad_manifest`, `wrong_release` (team, app, +version or artifact differ from the job), `tampered` (size or SHA-256), `bad_archive`. + +### `POST /legatus/v1/renew` + +`{ "v": 1, "csr": "" }` → `200 { "v": 1, "chain": "" }`. The server records the new serial as *pending*: +the old certificate keeps working until the new one is first used, then the old one is refused +(`Registry::renewed`, `accept`). + +## The release manifest (signed by the team's release key in Custos) + +```json +{ "v": 1, "team": "acme", "app": "shop", "version": "1.4.0", "created_at": 1800000000, + "artifacts": [ { "name": "shop-linux-x86_64.tar.gz", "sha256": "<64 lowercase hex>", "size": 1234567 } ] } +``` + +Signed with minisign (Ed25519, prehashed: what Custos's `minisign` format makes today) over the exact bytes. The +release key is the team's (T1's team vault). Artifact names: 1–128 of `A-Z a-z 0-9 . _ + -`, not starting with `.`. +App ids are domi-pki ids; versions 1–64 of `A-Z a-z 0-9 . _ + -`, not `.` or `..`. At most 64 artifacts; a size at +most 4 GiB. + +Archives for the Linux target are `.tar.gz` with regular files and directories only. + +## Versioning + +`v` is 1. A server that sees an agent's `version` it does not know still speaks v1; a new field is a new `v`.