From d0b38429ecabf03965418271b3ab00c846d143c2 Mon Sep 17 00:00:00 2001 From: Daniel JB Clark Date: Thu, 13 Aug 2026 15:55:22 -0400 Subject: [PATCH 1/4] feat: add sudo-secretspec privilege-boundary companion Add a single Rust binary that mediates SecretSpec access through a root-owned broker, fail-closed SQLite audit, metadata-only doctor checks, and explicit install/adopt/rollback. Include Homebrew packaging and downstream release tooling without privileged install side effects. --- .github/workflows/sudo-release.yml | 53 + .gitignore | 3 + CHANGELOG.md | 9 + Cargo.lock | 86 +- Cargo.toml | 10 +- packaging/README.md | 48 + packaging/homebrew/sudo-secretspec.rb | 39 + packaging/release.py | 403 +++++ secretspec-derive/Cargo.toml | 2 +- skills/sudo-secretspec/SKILL.md | 68 + sudo-secretspec-cli/Cargo.toml | 30 + sudo-secretspec-cli/src/audit.rs | 1394 +++++++++++++++++ sudo-secretspec-cli/src/broker.rs | 405 +++++ sudo-secretspec-cli/src/config.rs | 89 ++ sudo-secretspec-cli/src/drift.rs | 491 ++++++ sudo-secretspec-cli/src/install.rs | 479 ++++++ sudo-secretspec-cli/src/lib.rs | 8 + sudo-secretspec-cli/src/main.rs | 335 ++++ sudo-secretspec-cli/src/rollback.rs | 118 ++ sudo-secretspec-cli/tests/audit.rs | 597 +++++++ sudo-secretspec-cli/tests/cli.rs | 44 + sudo-secretspec-cli/tests/config.rs | 49 + sudo-secretspec-cli/tests/drift.rs | 175 +++ sudo-secretspec-cli/tests/install_rollback.rs | 24 + sudo-secretspec/AI-GUIDANCE.md | 50 + .../share/sudo-secretspec-retired.toml | 6 + .../share/sudo-secretspec.conf.example | 9 + tests/sudo_packaging/test_release.py | 246 +++ 28 files changed, 5259 insertions(+), 11 deletions(-) create mode 100644 .github/workflows/sudo-release.yml create mode 100644 packaging/README.md create mode 100644 packaging/homebrew/sudo-secretspec.rb create mode 100755 packaging/release.py create mode 100644 skills/sudo-secretspec/SKILL.md create mode 100644 sudo-secretspec-cli/Cargo.toml create mode 100644 sudo-secretspec-cli/src/audit.rs create mode 100644 sudo-secretspec-cli/src/broker.rs create mode 100644 sudo-secretspec-cli/src/config.rs create mode 100644 sudo-secretspec-cli/src/drift.rs create mode 100644 sudo-secretspec-cli/src/install.rs create mode 100644 sudo-secretspec-cli/src/lib.rs create mode 100644 sudo-secretspec-cli/src/main.rs create mode 100644 sudo-secretspec-cli/src/rollback.rs create mode 100644 sudo-secretspec-cli/tests/audit.rs create mode 100644 sudo-secretspec-cli/tests/cli.rs create mode 100644 sudo-secretspec-cli/tests/config.rs create mode 100644 sudo-secretspec-cli/tests/drift.rs create mode 100644 sudo-secretspec-cli/tests/install_rollback.rs create mode 100644 sudo-secretspec/AI-GUIDANCE.md create mode 100644 sudo-secretspec/share/sudo-secretspec-retired.toml create mode 100644 sudo-secretspec/share/sudo-secretspec.conf.example create mode 100644 tests/sudo_packaging/test_release.py diff --git a/.github/workflows/sudo-release.yml b/.github/workflows/sudo-release.yml new file mode 100644 index 000000000..fa56de40d --- /dev/null +++ b/.github/workflows/sudo-release.yml @@ -0,0 +1,53 @@ +name: sudo-secretspec downstream release checks + +on: + pull_request: + paths: + - "packaging/**" + - "sudo-secretspec/**" + - "skills/sudo-secretspec/**" + - "tests/sudo_packaging/**" + - "tests/sudo_secretspec/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/sudo-release.yml" + - "CHANGELOG.md" + push: + tags: + - "v0.19.1-djbclark.1" + workflow_dispatch: + +permissions: + contents: read + +jobs: + packaging: + runs-on: macos-15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v6.0.0 + with: + python-version: "3.13" + - name: Install focused test dependencies + run: | + python -m pip install pytest ruff + brew install shellcheck shfmt + - name: Test downstream companion and release helper + run: | + python -m ruff check sudo-secretspec packaging tests/sudo_secretspec tests/sudo_packaging + python -m ruff format --check sudo-secretspec packaging tests/sudo_secretspec tests/sudo_packaging + python -m pytest tests/sudo_secretspec tests/sudo_packaging -q + shfmt -d -i 2 -ci sudo-secretspec/bin/install-sudo-secretspec sudo-secretspec/libexec/sudo-secretspec-broker + shellcheck -S warning sudo-secretspec/bin/install-sudo-secretspec sudo-secretspec/libexec/sudo-secretspec-broker + - name: Check formula style and syntax + run: | + ruby -c packaging/homebrew/sudo-secretspec.rb + brew style packaging/homebrew/sudo-secretspec.rb + - name: Verify pinned tag identity + if: github.ref_type == 'tag' + env: + EXPECTED_TAG: v0.19.1-djbclark.1 + run: test "$GITHUB_REF_NAME" = "$EXPECTED_TAG" diff --git a/.gitignore b/.gitignore index 441ba8be3..667537daa 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,6 @@ target /secretspec-swift/Artifacts/ .idea/ + +__pycache__/ +*.pyc diff --git a/CHANGELOG.md b/CHANGELOG.md index b3e9c2a0c..a51921722 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be 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). +## [Unreleased] + +### Added + +- Downstream `sudo-secretspec` privilege-boundary companion: a single Rust + binary with mediated credential operations, fail-closed SQLite audit, + metadata-only doctor/drift checks, explicit install/adopt/rollback, and + Homebrew packaging that never performs privileged installation side effects. + ## [0.19.1] - 2026-08-11 Republishes 0.19.0's command-line artifacts. The library and CLI behave exactly diff --git a/Cargo.lock b/Cargo.lock index d5e73ce68..ebb083fba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2047,6 +2047,18 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fancy-regex" version = "0.18.0" @@ -2636,6 +2648,15 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + [[package]] name = "hashbrown" version = "0.15.5" @@ -2662,6 +2683,15 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown 0.14.5", +] + [[package]] name = "heck" version = "0.5.0" @@ -3601,6 +3631,17 @@ dependencies = [ "libc", ] +[[package]] +name = "libsqlite3-sys" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c10584274047cb335c23d3e61bcef8e323adae7c5c8c760540f73610177fc3f" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "linkme" version = "0.3.35" @@ -4381,7 +4422,7 @@ dependencies = [ "proc-macro-error-attr3", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] @@ -4867,6 +4908,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rusqlite" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b838eba278d213a8beaf485bd313fd580ca4505a00d5871caeb1457c55322cae" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + [[package]] name = "rust-argon2" version = "3.0.0" @@ -5204,7 +5259,7 @@ dependencies = [ [[package]] name = "secretspec" -version = "0.19.1" +version = "0.19.1-djbclark.1" dependencies = [ "age", "aws-config", @@ -5250,7 +5305,7 @@ dependencies = [ [[package]] name = "secretspec-derive" -version = "0.19.1" +version = "0.19.1-djbclark.1" dependencies = [ "http 1.4.0", "insta", @@ -5268,7 +5323,7 @@ dependencies = [ [[package]] name = "secretspec-ffi" -version = "0.19.1" +version = "0.19.1-djbclark.1" dependencies = [ "secretspec", "serde_json", @@ -5277,7 +5332,7 @@ dependencies = [ [[package]] name = "secretspec-node-native" -version = "0.19.1" +version = "0.19.1-djbclark.1" dependencies = [ "napi", "napi-build", @@ -5287,7 +5342,7 @@ dependencies = [ [[package]] name = "secretspec-php-native" -version = "0.19.1" +version = "0.19.1-djbclark.1" dependencies = [ "ext-php-rs", "secretspec", @@ -5295,7 +5350,7 @@ dependencies = [ [[package]] name = "secretspec-py-native" -version = "0.19.1" +version = "0.19.1-djbclark.1" dependencies = [ "pyo3", "secretspec", @@ -5681,6 +5736,23 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "sudo-secretspec-cli" +version = "0.19.1-djbclark.1" +dependencies = [ + "clap", + "libc", + "rusqlite", + "secretspec", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", + "thiserror 2.0.18", + "toml 0.9.12+spec-1.1.0", + "uuid", +] + [[package]] name = "supports-color" version = "3.0.2" diff --git a/Cargo.toml b/Cargo.toml index d26a045e5..036ac4ba8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,11 +6,12 @@ members = [ "secretspec-node", "secretspec-php", "secretspec-py", + "sudo-secretspec-cli", ] resolver = "2" [workspace.package] -version = "0.19.1" +version = "0.19.1-djbclark.1" edition = "2024" [workspace.dependencies] @@ -28,6 +29,9 @@ dotenvy = "0.15" inquire = { version = "0.9.4", features = ["experimental-multiline-input"] } miette = { version = "7.6", features = ["fancy"] } serde_json = "1.0" +rusqlite = { version = "0.40.0", features = ["bundled"] } +sha2 = "0.10" +libc = "0.2" proptest = "1" tempfile = "3.0" same-file = "1.0" @@ -53,8 +57,8 @@ azure_identity = "1.0.0" azure_security_keyvault_secrets = "1.0.0" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-native-roots"] } tokio = { version = "1", features = ["rt", "rt-multi-thread"] } -secretspec-derive = { version = "0.19.1", path = "./secretspec-derive" } -secretspec = { version = "0.19.1", path = "./secretspec" } +secretspec-derive = { version = "0.19.1-djbclark.1", path = "./secretspec-derive" } +secretspec = { version = "0.19.1-djbclark.1", path = "./secretspec" } rand = "0.9" rsa = { version = "0.9", features = ["pem"] } uuid = { version = "1", features = ["serde", "v4"] } diff --git a/packaging/README.md b/packaging/README.md new file mode 100644 index 000000000..594af09aa --- /dev/null +++ b/packaging/README.md @@ -0,0 +1,48 @@ +# sudo-secretspec downstream packaging + +This downstream release preserves the upstream SecretSpec crate/workspace version +`0.19.1` and uses a packaging-only downstream tag: + +- Tag: `v0.19.1-djbclark.1` +- Release title: `SecretSpec 0.19.1 — sudo-secretspec downstream 1` +- Fork: `djbclark/sudo-secretspec` (parent `cachix/secretspec`) + +## Release + +The maintainer entrypoint is `packaging/release.py`. It validates a clean +`main`/`master` tree, HTTPS remotes, the upstream `v0.19.1` ancestry/version, +and GitHub fork parent before any write. + +```bash +# Safe preview; performs no writes. +python3 packaging/release.py --dry-run + +# Live release after packaging and companion changes are committed on main. +python3 packaging/release.py + +# Alternate local tap clone. +python3 packaging/release.py --tap-path ~/src/homebrew-sudo-secretspec +``` + +The live flow runs focused Python and Rust tests, creates and pushes an +annotated tag, creates the titled GitHub Release with `gh`, downloads the tag +tarball over HTTPS, rewrites the formula SHA-256, commits/pushes that formula, +syncs the configured tap clone, force-refreshes Homebrew and the tap checkout, +reinstalls and tests the formula, then reads back repository parent, tag, +release title/state, and installed engine version. Interrupt cleanup removes +only a locally-created unpushed tag and an uncommitted formula rewrite; it +never deletes a pushed tag. + +## Homebrew safety boundary + +The formula builds the upstream `secretspec` engine and installs companion +files from `sudo-secretspec/bin`, `sudo-secretspec/libexec`, and +`sudo-secretspec/share` when those paths exist in the tagged source. Missing +companion paths are tolerated so upstream-only snapshots remain buildable. + +Installation has no privileged side effects: it never invokes `sudo`, edits +sudoers, creates users, or mutates `/var/db`. The caveat tells the operator to +explicitly run `sudo-secretspec install` after reviewing the installed files. + +Canonical formula: `packaging/homebrew/sudo-secretspec.rb`. +Tap clone default: `~/src/homebrew-sudo-secretspec`. diff --git a/packaging/homebrew/sudo-secretspec.rb b/packaging/homebrew/sudo-secretspec.rb new file mode 100644 index 000000000..b49c1bf43 --- /dev/null +++ b/packaging/homebrew/sudo-secretspec.rb @@ -0,0 +1,39 @@ +# typed: strict +# frozen_string_literal: true + +# Homebrew package for the upstream engine and downstream opt-in companion. +class SudoSecretspec < Formula + desc "SecretSpec engine with an opt-in macOS privilege-boundary companion" + homepage "https://github.com/djbclark/sudo-secretspec" + url "https://github.com/djbclark/sudo-secretspec/archive/refs/tags/v0.19.1-djbclark.1.tar.gz" + sha256 "0000000000000000000000000000000000000000000000000000000000000000" + license "Apache-2.0" + head "https://github.com/djbclark/sudo-secretspec.git", branch: "sudo-main" + + depends_on "rust" => :build + + def install + system "cargo", "install", "--locked", "--root", prefix, "--path", "secretspec" + system "cargo", "install", "--locked", "--root", prefix, "--path", "sudo-secretspec-cli" + (share/"sudo-secretspec").install "sudo-secretspec/AI-GUIDANCE.md" + (share/"sudo-secretspec/skills/sudo-secretspec").install "skills/sudo-secretspec/SKILL.md" + end + + def caveats + <<~EOS + Homebrew installed files only. It did not run sudo, edit sudoers, create + users, or mutate /var/db. To opt in after reviewing the installed assets, + explicitly run: + + sudo-secretspec install --declarations /path/to/secretspec.toml + + Existing protected stores must be adopted explicitly; see + sudo-secretspec/AI-GUIDANCE.md in the source distribution. + EOS + end + + test do + assert_match "0.19.1-djbclark.1", shell_output("#{bin}/secretspec --version") + assert_match "sudo-secretspec 0.19.1-djbclark.1", shell_output("#{bin}/sudo-secretspec --version") + end +end diff --git a/packaging/release.py b/packaging/release.py new file mode 100755 index 000000000..5e2cbcc1a --- /dev/null +++ b/packaging/release.py @@ -0,0 +1,403 @@ +#!/usr/bin/env python3 +"""Release sudo-secretspec downstream v0.19.1-djbclark.1 and its tap. + +The release keeps upstream crate versions at 0.19.1. Use ``--dry-run`` to print +all mutating commands. The live path validates fork lineage, creates an +annotated tag and GitHub Release, rewrites the formula checksum, synchronizes +the tap, and performs a live Homebrew readback test. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import shutil +import signal +import subprocess +import tempfile +import urllib.request +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from urllib.parse import urlsplit + +ROOT = Path(__file__).resolve().parents[1] +VERSION = "0.19.1-djbclark.1" +TAG = f"v{VERSION}" +UPSTREAM_TAG = "v0.19.1" +RELEASE_TITLE = "SecretSpec 0.19.1 — sudo-secretspec downstream 1" +FORK_REPO = "djbclark/sudo-secretspec" +UPSTREAM_REPO = "cachix/secretspec" +ORIGIN_URL = f"https://github.com/{FORK_REPO}.git" +UPSTREAM_URL = f"https://github.com/{UPSTREAM_REPO}.git" +FORMULA_REL = Path("packaging/homebrew/sudo-secretspec.rb") +FORMULA = ROOT / FORMULA_REL +DEFAULT_TAP = Path.home() / "src" / "homebrew-sudo-secretspec" +FORMULA_NAME = "djbclark/sudo-secretspec/sudo-secretspec" +ARCHIVE_URL = f"https://github.com/{FORK_REPO}/archive/refs/tags/{TAG}.tar.gz" +VERSION_RE = re.compile(r"^0\.19\.1-djbclark\.1$") + + +class ReleaseError(RuntimeError): + """Release invariant failed.""" + + +def log(message: str) -> None: + print(message, flush=True) + + +def run( + argv: list[str], + *, + cwd: Path = ROOT, + capture: bool = True, + check: bool = True, + dry_run: bool = False, +) -> subprocess.CompletedProcess[str]: + if dry_run: + log("[dry-run] " + " ".join(str(value) for value in argv)) + return subprocess.CompletedProcess(argv, 0, stdout="", stderr="") + log("+ " + " ".join(str(value) for value in argv)) + return subprocess.run(argv, cwd=cwd, text=True, capture_output=capture, check=check) + + +def output(argv: list[str], **kwargs: object) -> str: + return (run(argv, **kwargs).stdout or "").strip() + + +def validate_version(version: str) -> None: + if not VERSION_RE.fullmatch(version): + raise ReleaseError( + f"this downstream release is pinned to {VERSION}, got {version!r}" + ) + + +def validate_release_url(url: str) -> None: + parsed = urlsplit(url) + if parsed.scheme != "https" or parsed.hostname != "github.com": + raise ReleaseError(f"refuse non-GitHub HTTPS release URL: {url!r}") + + +def _require(value: bool, message: str) -> None: + if not value: + raise ReleaseError(message) + + +def preflight(*, allow_dirty: bool) -> None: + status = output(["git", "status", "--porcelain"]) + _require( + allow_dirty or not status, + "working tree is dirty; commit/stash first or pass --allow-dirty", + ) + branch = output(["git", "branch", "--show-current"]) + _require(branch == "sudo-main", "downstream release must run from sudo-main") + _require( + output(["git", "remote", "get-url", "origin"]) == ORIGIN_URL, + f"origin must be {ORIGIN_URL}", + ) + _require( + output(["git", "remote", "get-url", "upstream"]) == UPSTREAM_URL, + f"upstream must be {UPSTREAM_URL}", + ) + output(["git", "rev-parse", f"{UPSTREAM_TAG}^{{commit}}"]) + run(["git", "merge-base", "--is-ancestor", UPSTREAM_TAG, "HEAD"]) + manifest = output(["git", "show", f"{UPSTREAM_TAG}:Cargo.toml"]) + _require( + 'version = "0.19.1"' in manifest, + f"{UPSTREAM_TAG} is not upstream workspace version 0.19.1", + ) + _require( + f'version = "{VERSION}"' in (ROOT / "Cargo.toml").read_text(encoding="utf-8"), + "workspace downstream version mismatch", + ) + repo = json.loads( + output( + [ + "gh", + "repo", + "view", + FORK_REPO, + "--json", + "nameWithOwner,parent,defaultBranchRef", + ] + ) + ) + _require(repo.get("nameWithOwner") == FORK_REPO, f"gh target is not {FORK_REPO}") + _require( + (repo.get("defaultBranchRef") or {}).get("name") == branch, + "current branch is not the fork default branch", + ) + parent = (repo.get("parent") or {}).get("nameWithOwner") + _require( + parent == UPSTREAM_REPO, f"fork parent must be {UPSTREAM_REPO}, got {parent!r}" + ) + + +def run_tests(*, dry_run: bool) -> None: + run(["pytest", "tests/sudo_packaging", "-q"], dry_run=dry_run, capture=False) + # Core is unchanged; compile the pinned upstream engine without invoking + # provider integration tests that depend on optional host CLIs (for example sops). + run( + ["cargo", "build", "-p", "secretspec", "--locked"], + dry_run=dry_run, + capture=False, + ) + + +def rewrite_formula(path: Path, version: str, sha256: str) -> None: + validate_version(version) + text = path.read_text(encoding="utf-8") + text, urls = re.subn( + r'url "https://github\.com/djbclark/sudo-secretspec/archive/refs/tags/v[^\"]+\.tar\.gz"', + f'url "https://github.com/{FORK_REPO}/archive/refs/tags/v{version}.tar.gz"', + text, + count=1, + ) + text, hashes = re.subn( + r'sha256 "[0-9a-f]{64}"', f'sha256 "{sha256}"', text, count=1 + ) + if urls != 1 or hashes != 1: + raise ReleaseError(f"failed to rewrite exactly one URL and checksum in {path}") + path.write_text(text, encoding="utf-8") + + +def archive_sha256(*, dry_run: bool) -> str: + validate_release_url(ARCHIVE_URL) + if dry_run: + log(f"[dry-run] hash {ARCHIVE_URL}") + return "0" * 64 + digest = hashlib.sha256() + request = urllib.request.Request( + ARCHIVE_URL, headers={"User-Agent": "sudo-secretspec-release"} + ) + with urllib.request.urlopen(request, timeout=60) as response: + while chunk := response.read(1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def create_tag_and_release(notes: str, state: CleanupState, *, dry_run: bool) -> None: + if output(["git", "tag", "--list", TAG]) and not dry_run: + raise ReleaseError(f"local tag already exists: {TAG}") + run(["git", "tag", "-a", TAG, "-m", RELEASE_TITLE], dry_run=dry_run) + state.tag_created = not dry_run + run(["git", "push", "origin", TAG], dry_run=dry_run) + state.tag_pushed = not dry_run + if dry_run: + run( + [ + "gh", + "release", + "create", + TAG, + "--repo", + FORK_REPO, + "--title", + RELEASE_TITLE, + "--notes-file", + "", + ], + dry_run=True, + ) + return + with tempfile.NamedTemporaryFile("w", suffix=".md", encoding="utf-8") as notes_file: + notes_file.write(notes) + notes_file.flush() + run( + [ + "gh", + "release", + "create", + TAG, + "--repo", + FORK_REPO, + "--title", + RELEASE_TITLE, + "--notes-file", + notes_file.name, + ] + ) + + +def update_formula_commit(*, dry_run: bool, state: CleanupState) -> None: + sha = archive_sha256(dry_run=dry_run) + if dry_run: + log(f"[dry-run] rewrite {FORMULA_REL} for {TAG} sha256={sha}") + run(["git", "add", str(FORMULA_REL)], dry_run=True) + run(["git", "commit", "-m", f"Update Homebrew formula for {TAG}"], dry_run=True) + run(["git", "push", "origin", "HEAD"], dry_run=True) + return + rewrite_formula(FORMULA, VERSION, sha) + state.formula_changed = True + run(["git", "add", str(FORMULA_REL)]) + run(["git", "commit", "-m", f"Update Homebrew formula for {TAG}"]) + state.formula_changed = False + run(["git", "push", "origin", "HEAD"]) + + +def sync_tap(tap_path: Path, *, dry_run: bool) -> None: + destination = tap_path / "Formula" / "sudo-secretspec.rb" + if dry_run: + log(f"[dry-run] copy {FORMULA_REL} -> {destination}") + run(["git", "add", "Formula/sudo-secretspec.rb"], cwd=tap_path, dry_run=True) + run( + ["git", "commit", "-m", f"sudo-secretspec {VERSION}"], + cwd=tap_path, + dry_run=True, + ) + run(["git", "push", "origin", "HEAD"], cwd=tap_path, dry_run=True) + return + _require((tap_path / ".git").exists(), f"tap clone missing or not Git: {tap_path}") + _require( + not output(["git", "status", "--porcelain"], cwd=tap_path), + f"tap working tree is dirty: {tap_path}", + ) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(FORMULA, destination) + run(["git", "add", "Formula/sudo-secretspec.rb"], cwd=tap_path) + if output(["git", "diff", "--cached", "--name-only"], cwd=tap_path): + run(["git", "commit", "-m", f"sudo-secretspec {VERSION}"], cwd=tap_path) + run(["git", "push", "origin", "HEAD"], cwd=tap_path) + + +def brew_refresh_and_test(*, dry_run: bool) -> str: + run(["brew", "update", "--force"], dry_run=dry_run, capture=False) + tap_repo = output( + ["brew", "--repository", "djbclark/sudo-secretspec"], dry_run=dry_run + ) + if not dry_run: + tap = Path(tap_repo) + _require(tap.is_dir(), "Homebrew did not return the tap checkout") + run(["git", "fetch", "origin", "main"], cwd=tap, capture=False) + run(["git", "merge", "--ff-only", "origin/main"], cwd=tap, capture=False) + _require( + TAG in (tap / "Formula/sudo-secretspec.rb").read_text(encoding="utf-8"), + "live tap formula is stale", + ) + run(["brew", "reinstall", FORMULA_NAME], dry_run=dry_run, capture=False) + prefix = ( + output(["brew", "--prefix", FORMULA_NAME], dry_run=dry_run) + or "/opt/homebrew/opt/sudo-secretspec" + ) + run(["brew", "test", FORMULA_NAME], dry_run=dry_run, capture=False) + return prefix + + +def verify_readback(prefix: str) -> None: + repo = json.loads( + output(["gh", "repo", "view", FORK_REPO, "--json", "nameWithOwner,parent"]) + ) + _require(repo.get("nameWithOwner") == FORK_REPO, "repository readback mismatch") + _require( + (repo.get("parent") or {}).get("nameWithOwner") == UPSTREAM_REPO, + "fork lineage readback mismatch", + ) + ref = json.loads(output(["gh", "api", f"repos/{FORK_REPO}/git/ref/tags/{TAG}"])) + _require(ref.get("ref") == f"refs/tags/{TAG}", "tag readback mismatch") + release = json.loads( + output( + [ + "gh", + "release", + "view", + TAG, + "--repo", + FORK_REPO, + "--json", + "tagName,name,isDraft", + ] + ) + ) + _require( + release == {"tagName": TAG, "name": RELEASE_TITLE, "isDraft": False}, + "release readback mismatch", + ) + version = output([str(Path(prefix) / "bin" / "secretspec"), "--version"]) + _require(VERSION in version, f"installed engine version mismatch: {version!r}") + + +@dataclass +class CleanupState: + tag_created: bool = False + tag_pushed: bool = False + formula_changed: bool = False + + +def cleanup_interrupted(state: CleanupState) -> None: + if state.tag_created and not state.tag_pushed: + run(["git", "tag", "-d", TAG]) + if state.formula_changed: + run(["git", "restore", "--staged", "--worktree", "--", str(FORMULA_REL)]) + + +@contextmanager +def interrupt_cleanup(state: CleanupState) -> Iterator[None]: + previous = { + number: signal.getsignal(number) for number in (signal.SIGINT, signal.SIGTERM) + } + + def handler(number: int, _frame: object) -> None: + cleanup_interrupted(state) + raise ReleaseError(f"interrupted by {signal.Signals(number).name}") + + for number in previous: + signal.signal(number, handler) + try: + yield + finally: + for number, old_handler in previous.items(): + signal.signal(number, old_handler) + + +def default_notes() -> str: + return ( + "Downstream packaging release based on upstream SecretSpec 0.19.1.\n\n" + "Adds the opt-in `sudo-secretspec` privilege-boundary companion. Homebrew installs files only; " + "run `sudo-secretspec install` explicitly to configure privileged state.\n" + ) + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--allow-dirty", action="store_true") + parser.add_argument("--skip-tests", action="store_true") + parser.add_argument("--skip-homebrew", action="store_true") + parser.add_argument("--notes-file", type=Path) + parser.add_argument("--tap-path", type=Path, default=DEFAULT_TAP) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + validate_version(VERSION) + if not args.dry_run: + preflight(allow_dirty=args.allow_dirty) + if not args.skip_tests: + run_tests(dry_run=args.dry_run) + notes = ( + args.notes_file.read_text(encoding="utf-8") + if args.notes_file + else default_notes() + ) + state = CleanupState() + with interrupt_cleanup(state): + create_tag_and_release(notes, state, dry_run=args.dry_run) + if not args.skip_homebrew: + update_formula_commit(dry_run=args.dry_run, state=state) + sync_tap(args.tap_path, dry_run=args.dry_run) + prefix = brew_refresh_and_test(dry_run=args.dry_run) + if not args.dry_run: + verify_readback(prefix) + log(f"done: {RELEASE_TITLE} ({TAG})") + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except (ReleaseError, subprocess.CalledProcessError) as error: + raise SystemExit(str(error)) from error diff --git a/secretspec-derive/Cargo.toml b/secretspec-derive/Cargo.toml index 0c1b95cbc..8a223e79d 100644 --- a/secretspec-derive/Cargo.toml +++ b/secretspec-derive/Cargo.toml @@ -15,7 +15,7 @@ quote.workspace = true proc-macro2.workspace = true toml.workspace = true serde.workspace = true -secretspec = { version = "0.19.1", path = "../secretspec", default-features = false } +secretspec = { version = "0.19.1-djbclark.1", path = "../secretspec", default-features = false } [dev-dependencies] trybuild.workspace = true diff --git a/skills/sudo-secretspec/SKILL.md b/skills/sudo-secretspec/SKILL.md new file mode 100644 index 000000000..993b859c5 --- /dev/null +++ b/skills/sudo-secretspec/SKILL.md @@ -0,0 +1,68 @@ +--- +name: sudo-secretspec +description: Use managed credentials without backing-store access. +version: 0.1.0 +author: Dan Clark (djbclark), Hermes Agent +license: Apache-2.0 +platforms: [macos] +metadata: + hermes: + tags: [secrets, privilege-separation, audit, macos] + related_skills: [] +--- + +# sudo-secretspec Skill + +Use the installed privilege-separated client for autonomous credential CRUD and consumer execution. Do not access SecretSpec’s provider or protected backing files directly. + +## When to Use + +- A task needs an API key, token, password, or other declared credential. +- A credential must be initialized, rotated, read, deleted, checked, exported, or injected into a child process. +- The managed boundary or drift checker reports an error. + +Do not use for boundary installation, adoption, rollback, or repair without explicit operator authorization. + +## Prerequisites + +- `/usr/local/bin/sudo-secretspec` is installed. +- The credential name is present in the released declarations before `add`. +- The consumer can read its credentials from environment variables when using `run`. + +## How to Run + +Invoke through `terminal` with a short non-secret reason: + +```bash +sudo-secretspec run --reason "query provider API" -- command args... +sudo-secretspec get NAME --reason "inspect managed credential" +sudo-secretspec set NAME --reason "rotate managed credential" +sudo-secretspec check --reason "validate required credentials" +``` + +## Procedure + +1. Confirm the name already exists in released declarations. If absent, stop and request the declaration PR/release/deploy lifecycle; do not create an alternate manifest. +2. Prefer `run` for consumers so values do not enter command arguments, source files, or shell history. Completion: the child receives its environment without value output in the agent transcript. +3. Use `add`, `set`, `delete`, or `get` only through `sudo-secretspec`, with a non-secret reason. Completion: the command returns success and the audit ledger records a terminal outcome. +4. On any broker, audit, authorization, or drift failure, stop and report only the non-secret error. Completion: no fallback store, manifest, provider, symlink, copy, permission change, or repair was attempted. + +## Pitfalls + +- Permission denied while inspecting a `0700` store is expected and does not mean files are missing. +- Reasons are hashed in the protected broker ledger but may reach SecretSpec’s native reason interface; never put values in them. +- Client labels are correlation hints, not authenticated AI identities. +- An alert-only watchdog must never repair state. +- `run` intentionally exposes the declared environment to its child; this deployment model authorizes every local caller for every declared credential. + +## Verification + +Run through `terminal`: + +```bash +sudo-secretspec doctor +``` + +Success requires a zero exit status and no drift findings. Do not run `install` or `rollback` merely to verify a normal credential operation. + +See `sudo-secretspec/AI-GUIDANCE.md` in the distribution for the complete policy contract. diff --git a/sudo-secretspec-cli/Cargo.toml b/sudo-secretspec-cli/Cargo.toml new file mode 100644 index 000000000..177ec6e41 --- /dev/null +++ b/sudo-secretspec-cli/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "sudo-secretspec-cli" +version.workspace = true +edition.workspace = true +description = "sudo-secretspec drift-check and runtime validation" + +[lib] +name = "sudo_secretspec_cli" +path = "src/lib.rs" + +[[bin]] +name = "sudo-secretspec" +path = "src/main.rs" + +[dependencies] +clap.workspace = true +rusqlite = { version = "0.31", features = ["bundled"] } +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true +secretspec = { path = "../secretspec", version = "0.19.1-djbclark.1", default-features = false } +sha2.workspace = true +thiserror.workspace = true +toml.workspace = true +uuid.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[target.'cfg(target_os = "macos")'.dependencies] +libc = "0.2" \ No newline at end of file diff --git a/sudo-secretspec-cli/src/audit.rs b/sudo-secretspec-cli/src/audit.rs new file mode 100644 index 000000000..5ded2f55b --- /dev/null +++ b/sudo-secretspec-cli/src/audit.rs @@ -0,0 +1,1394 @@ +//! Fail-closed transactional SQLite audit ledger for sudo-secretspec. +//! +//! Every event is hash-chained. An append writes the event row and updates the +//! singleton `head` row inside a single `BEGIN IMMEDIATE` transaction so a +//! crash cannot leave them out of sync. The ledger stores **no** reason text, +//! command arguments, or secret values — only a SHA-256 digest of the reason. +//! +//! ## Protected metadata +//! +//! Before opening the database the module validates: +//! - the protected directory is mode `0700` and owned by the expected UID, +//! - any existing ledger is a regular file with mode `0600` (not a symlink), +//! - after opening, the ledger inode is re-checked. +//! +//! If any check fails the call returns an error before creating or touching a +//! database — **fail-closed**. + +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::path::Path; + +use rusqlite::{Connection, OptionalExtension}; +use sha2::{Digest, Sha256}; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +/// The hash used as the genesis previous-hash (i.e. before any event exists). +pub const ZERO_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000"; + +/// The fixed ledger filename inside the protected directory. +pub const DB_NAME: &str = "broker-audit.sqlite3"; + +/// Valid secret-name pattern. +pub const NAME_RE: &str = r"^[A-Z][A-Z0-9_]*$"; + +/// Valid operation pattern. +pub const OP_RE: &str = r"^[a-z][a-z0-9-]*$"; + +/// Valid client-family pattern. +pub const CLIENT_RE: &str = r"^(?:hermes|claude|codex|opencode|cursor|agy|fixed-consumer|unknown)$"; + +/// Valid command-basename pattern. +pub const COMMAND_RE: &str = r"^[A-Za-z0-9_.+-]{1,128}$"; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +/// Audit event phase. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Outcome { + Attempt, + Success, + Failure, + Unknown, +} + +impl Outcome { + pub fn as_str(self) -> &'static str { + match self { + Outcome::Attempt => "attempt", + Outcome::Success => "success", + Outcome::Failure => "failure", + Outcome::Unknown => "unknown", + } + } + + pub fn from_str(s: &str) -> Option { + match s { + "attempt" => Some(Outcome::Attempt), + "success" => Some(Outcome::Success), + "failure" => Some(Outcome::Failure), + "unknown" => Some(Outcome::Unknown), + _ => None, + } + } +} + +/// Known client-family label (correlation metadata, NOT an authenticated +/// principal). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClientFamily { + Hermes, + Claude, + Codex, + OpenCode, + Cursor, + Agy, + FixedConsumer, + Unknown, +} + +impl ClientFamily { + pub fn as_str(self) -> &'static str { + match self { + ClientFamily::Hermes => "hermes", + ClientFamily::Claude => "claude", + ClientFamily::Codex => "codex", + ClientFamily::OpenCode => "opencode", + ClientFamily::Cursor => "cursor", + ClientFamily::Agy => "agy", + ClientFamily::FixedConsumer => "fixed-consumer", + ClientFamily::Unknown => "unknown", + } + } + + pub fn from_str(s: &str) -> Option { + match s { + "hermes" => Some(ClientFamily::Hermes), + "claude" => Some(ClientFamily::Claude), + "codex" => Some(ClientFamily::Codex), + "opencode" => Some(ClientFamily::OpenCode), + "cursor" => Some(ClientFamily::Cursor), + "agy" => Some(ClientFamily::Agy), + "fixed-consumer" => Some(ClientFamily::FixedConsumer), + "unknown" => Some(ClientFamily::Unknown), + _ => None, + } + } +} + +/// Request to append an audit event. +#[derive(Debug, Clone)] +pub struct AppendEventRequest { + pub operation: String, + pub phase: Outcome, + pub transaction: uuid::Uuid, + pub actor: String, + pub client: ClientFamily, + pub reason_sha256: Option, + pub command_basename: Option, + pub names: Vec, + pub result_code: Option, + pub expected_uid: Option, +} + +/// A successfully appended audit event. +#[derive(Debug, Clone)] +pub struct AuditEvent { + pub sequence: i64, + pub timestamp_ns: i64, + pub transaction: uuid::Uuid, + pub phase: Outcome, + pub operation: String, + pub actor: String, + pub client: ClientFamily, + pub reason_sha256: String, + pub command_basename: Option, + pub names: Vec, + pub result_code: Option, + pub previous_hash: String, + pub event_hash: String, +} + +/// Result of a successful chain verification. +#[derive(Debug, Clone)] +pub struct VerifyResult { + pub count: u64, + pub hash: String, +} + +// --------------------------------------------------------------------------- +// Error +// --------------------------------------------------------------------------- + +#[derive(Debug, thiserror::Error)] +pub enum AuditError { + #[error("audit denied: {0}")] + Denied(String), + + #[error("database error: {0}")] + Database(#[from] rusqlite::Error), + + #[error("IO error: {0}")] + Io(#[from] std::io::Error), +} + +// --------------------------------------------------------------------------- +// Utility +// --------------------------------------------------------------------------- + +/// Compute the SHA-256 hex digest of `data`. +pub fn sha256_hex(data: &[u8]) -> String { + format!("{:x}", Sha256::digest(data)) +} + +/// Validate text against limit and forbidden characters. +fn validate_text(label: &str, value: &str, limit: usize) -> Result<(), AuditError> { + if value.is_empty() + || value.len() > limit + || value.contains('\0') + || value.contains('\r') + || value.contains('\n') + { + return Err(AuditError::Denied(format!("invalid {label}"))); + } + Ok(()) +} + +/// Manual validation: operation must be lowercase letter followed by +/// lowercase letters, digits, hyphens. +fn is_valid_operation(s: &str) -> bool { + let bytes = s.as_bytes(); + if bytes.is_empty() || !bytes[0].is_ascii_lowercase() { + return false; + } + bytes + .iter() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-') +} + +/// Manual validation: client must be one of the known labels. +fn is_valid_client(s: &str) -> bool { + matches!( + s, + "hermes" + | "claude" + | "codex" + | "opencode" + | "cursor" + | "agy" + | "fixed-consumer" + | "unknown" + ) +} + +/// Manual validation: 64 hex digits (lowercase). +fn is_valid_sha256_hex(s: &str) -> bool { + s.len() == 64 + && s.as_bytes() + .iter() + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) +} + +/// Manual validation: alphanumeric plus `_.+-`, 1-128 chars. +fn is_valid_command_basename(s: &str) -> bool { + let bytes = s.as_bytes(); + if bytes.is_empty() || bytes.len() > 128 { + return false; + } + bytes + .iter() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'+' | b'-')) +} + +/// Manual validation: uppercase letter followed by uppercase letters, digits, underscores. +fn is_valid_secret_name(s: &str) -> bool { + let bytes = s.as_bytes(); + if bytes.is_empty() || !bytes[0].is_ascii_uppercase() { + return false; + } + bytes + .iter() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || *b == b'_') +} + +// --------------------------------------------------------------------------- +// Protected metadata checks +// --------------------------------------------------------------------------- + +/// Check that `path` is a directory with mode `0700` and the expected owner. +fn check_protected_dir(path: &Path, expected_uid: Option) -> Result<(), AuditError> { + let meta = std::fs::symlink_metadata(path)?; + + // Must not be a symlink + if meta.is_symlink() { + return Err(AuditError::Denied( + "protected directory is a symlink".into(), + )); + } + + if !meta.is_dir() { + return Err(AuditError::Denied( + "protected directory is not a directory".into(), + )); + } + + let mode = meta.permissions().mode() & 0o777; + if mode != 0o700 { + return Err(AuditError::Denied( + "protected directory must be mode 0700".into(), + )); + } + + if let Some(uid) = expected_uid { + if meta.uid() != uid { + return Err(AuditError::Denied( + "protected directory owner mismatch".into(), + )); + } + } + + Ok(()) +} + +/// Check the existing ledger file: must be a regular file (not symlink), +/// mode `0600`, and owned by the expected UID (when given). +fn check_ledger_metadata(path: &Path, expected_uid: Option) -> Result<(), AuditError> { + let meta = match std::fs::symlink_metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(AuditError::Io(e)), + }; + + // Reject symlinks + if meta.is_symlink() { + return Err(AuditError::Denied("ledger is a symlink".into())); + } + + if !meta.is_file() { + return Err(AuditError::Denied( + "ledger path must be a regular file".into(), + )); + } + + let mode = meta.permissions().mode() & 0o777; + if mode != 0o600 { + return Err(AuditError::Denied("ledger must be mode 0600".into())); + } + + if let Some(uid) = expected_uid { + if meta.uid() != uid { + return Err(AuditError::Denied("ledger owner mismatch".into())); + } + } + + Ok(()) +} + +// --------------------------------------------------------------------------- +// Database connection +// --------------------------------------------------------------------------- + +fn open_connection(directory: &Path, expected_uid: Option) -> Result { + // 1. Validate protected directory metadata first (fail-closed). + check_protected_dir(directory, expected_uid)?; + + // 2. Check any existing ledger metadata before opening. + let db_path = directory.join(DB_NAME); + let existed = db_path.exists(); + check_ledger_metadata(&db_path, expected_uid)?; + + // 3. Open with mask to ensure new file gets 0600. + let old_mask = unsafe { libc::umask(0o077) }; + let conn_result = Connection::open(&db_path); + unsafe { libc::umask(old_mask) }; + + let conn = conn_result?; + + // 4. Set pragmas immediately. + conn.execute_batch( + "PRAGMA journal_mode=DELETE;\ + PRAGMA synchronous=FULL;\ + PRAGMA foreign_keys=ON;\ + PRAGMA trusted_schema=OFF;", + )?; + + // 5. Ensure new ledger gets correct permissions. + if !existed { + let mut perms = std::fs::metadata(&db_path)?.permissions(); + perms.set_mode(0o600); + std::fs::set_permissions(&db_path, perms)?; + } + + // 6. Re-verify ledger metadata after open. + check_ledger_metadata(&db_path, expected_uid)?; + + Ok(conn) +} + +// --------------------------------------------------------------------------- +// Schema +// --------------------------------------------------------------------------- + +fn ensure_schema(conn: &Connection) -> Result<(), AuditError> { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS events (\ + sequence INTEGER PRIMARY KEY AUTOINCREMENT,\ + timestamp_ns INTEGER NOT NULL,\ + transaction_id TEXT NOT NULL,\ + phase TEXT NOT NULL CHECK (phase IN ('attempt','success','failure','unknown')),\ + operation TEXT NOT NULL,\ + actor TEXT NOT NULL,\ + client TEXT NOT NULL,\ + reason_sha256 TEXT NOT NULL,\ + command_basename TEXT,\ + names_json TEXT NOT NULL,\ + result_code INTEGER,\ + previous_hash TEXT NOT NULL,\ + event_hash TEXT NOT NULL UNIQUE\ + ) STRICT;\ + CREATE TABLE IF NOT EXISTS head (\ + singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\ + sequence INTEGER NOT NULL,\ + event_hash TEXT NOT NULL\ + ) STRICT;", + )?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// Canonical serialisation +// --------------------------------------------------------------------------- + +/// Canonical JSON for an event (without sequence, timestamp_ns, event_hash). +fn canonical_event_json(event: &AuditEvent) -> String { + // Build a BTreeMap for deterministic key ordering. + let mut map = std::collections::BTreeMap::new(); + map.insert("sequence", serde_json::Value::Number(event.sequence.into())); + map.insert( + "timestamp_ns", + serde_json::Value::Number(event.timestamp_ns.into()), + ); + map.insert( + "transaction", + serde_json::Value::String(event.transaction.to_string()), + ); + map.insert( + "phase", + serde_json::Value::String(event.phase.as_str().into()), + ); + map.insert( + "operation", + serde_json::Value::String(event.operation.clone()), + ); + map.insert("actor", serde_json::Value::String(event.actor.clone())); + map.insert( + "client", + serde_json::Value::String(event.client.as_str().into()), + ); + map.insert( + "reason_sha256", + serde_json::Value::String(event.reason_sha256.clone()), + ); + map.insert( + "command_basename", + match &event.command_basename { + Some(s) => serde_json::Value::String(s.clone()), + None => serde_json::Value::Null, + }, + ); + map.insert("names", { + let names: Vec = event + .names + .iter() + .map(|n| serde_json::Value::String(n.clone())) + .collect(); + serde_json::Value::Array(names) + }); + map.insert( + "result_code", + match event.result_code { + Some(c) => serde_json::Value::Number(c.into()), + None => serde_json::Value::Null, + }, + ); + map.insert( + "previous_hash", + serde_json::Value::String(event.previous_hash.clone()), + ); + + serde_json::to_string(&map).unwrap() +} + +/// Compute the event hash for a prepared event. +fn compute_event_hash(previous_hash: &str, event: &AuditEvent) -> String { + let canonical = canonical_event_json(event); + let input = format!("{previous_hash}\n{canonical}"); + sha256_hex(input.as_bytes()) +} + +// --------------------------------------------------------------------------- +// Chain verification (in-transaction) +// --------------------------------------------------------------------------- + +/// Verify the chain inside an active read transaction. +/// Returns (last_event_hash, row_count) on success. +fn verify_rows(conn: &Connection) -> Result<(String, i64), AuditError> { + let mut previous = ZERO_HASH.to_string(); + let mut count: i64 = 0; + + let mut stmt = conn.prepare( + "SELECT sequence, timestamp_ns, transaction_id, phase, operation,\ + actor, client, reason_sha256, command_basename, names_json,\ + result_code, previous_hash, event_hash \ + FROM events ORDER BY sequence", + )?; + + let rows = stmt.query_map([], |row| { + Ok(( + row.get::<_, i64>(0)?, + row.get::<_, i64>(1)?, + row.get::<_, String>(2)?, + row.get::<_, String>(3)?, + row.get::<_, String>(4)?, + row.get::<_, String>(5)?, + row.get::<_, String>(6)?, + row.get::<_, String>(7)?, + row.get::<_, Option>(8)?, + row.get::<_, String>(9)?, + row.get::<_, Option>(10)?, + row.get::<_, String>(11)?, + row.get::<_, String>(12)?, + )) + })?; + + for row in rows { + let ( + sequence, + timestamp_ns, + transaction_id, + phase_str, + operation, + actor, + client_str, + reason_sha256, + command_basename, + names_json, + result_code_i64, + stored_previous, + event_hash, + ) = row?; + + let transaction = uuid::Uuid::parse_str(&transaction_id) + .map_err(|e| AuditError::Denied(format!("invalid transaction UUID in ledger: {e}")))?; + + let phase = Outcome::from_str(&phase_str) + .ok_or_else(|| AuditError::Denied(format!("invalid phase in ledger: {phase_str}")))?; + + let client = ClientFamily::from_str(&client_str) + .ok_or_else(|| AuditError::Denied(format!("invalid client in ledger: {client_str}")))?; + + let names: Vec = serde_json::from_str(&names_json) + .map_err(|e| AuditError::Denied(format!("invalid names_json in ledger: {e}")))?; + + let result_code: Option = result_code_i64.map(|c| c as u8); + + let event = AuditEvent { + sequence, + timestamp_ns, + transaction, + phase, + operation, + actor, + client, + reason_sha256, + command_basename, + names, + result_code, + previous_hash: stored_previous.clone(), + event_hash: event_hash.clone(), + }; + + // Compute expected hash + let expected = compute_event_hash(&previous, &event); + + // Validate previous hash link + if stored_previous != previous { + return Err(AuditError::Denied("ledger chain is invalid".into())); + } + + // Validate event hash + if event_hash != expected { + return Err(AuditError::Denied("ledger chain is invalid".into())); + } + + previous = event_hash; + count = sequence; + } + + // Check head matches last event (or is absent when no events exist) + let head: Option<(i64, String)> = conn + .query_row( + "SELECT sequence, event_hash FROM head WHERE singleton = 1", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional()?; + + let expected_head = if count == 0 { + None + } else { + Some((count, previous.clone())) + }; + + if head != expected_head { + return Err(AuditError::Denied("ledger head is invalid".into())); + } + + Ok((previous, count)) +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/// Verify the full ledger chain and head, returning the current tip hash +/// and total event count. If no ledger exists yet, returns `count=0` with +/// `ZERO_HASH`. +pub fn verify(directory: &Path, expected_uid: Option) -> Result { + // If no ledger exists yet, succeed with count=0. + let db_path = directory.join(DB_NAME); + if !db_path.exists() { + check_protected_dir(directory, expected_uid)?; + return Ok(VerifyResult { + count: 0, + hash: ZERO_HASH.into(), + }); + } + + let conn = open_connection(directory, expected_uid)?; + + let result = (|| -> Result { + ensure_schema(&conn)?; + conn.execute("BEGIN IMMEDIATE", [])?; + let (hash, count) = verify_rows(&conn)?; + + // Run integrity check + let integrity: String = conn.query_row("PRAGMA integrity_check", [], |row| row.get(0))?; + if integrity != "ok" { + return Err(AuditError::Denied("ledger integrity check failed".into())); + } + + conn.execute("COMMIT", [])?; + Ok(VerifyResult { + count: count as u64, + hash, + }) + })(); + + match result { + Ok(r) => Ok(r), + Err(e) => { + let _ = conn.execute("ROLLBACK", []); + Err(e) + } + } +} + +/// Append a new audit event. Validates all inputs before touching the +/// database (fail-closed). The event and head are committed atomically. +pub fn append_event( + directory: &Path, + request: AppendEventRequest, +) -> Result { + // ---- Input validation (fail-closed, before opening the database) ---- + + // Operation + { + if !is_valid_operation(&request.operation) { + return Err(AuditError::Denied("invalid operation".into())); + } + } + + // Phase rules + if request.phase.as_str() == "attempt" && request.result_code.is_some() { + return Err(AuditError::Denied( + "attempt cannot have a result code".into(), + )); + } + if request.phase.as_str() != "attempt" && request.result_code.is_none() { + return Err(AuditError::Denied( + "terminal event requires a result code".into(), + )); + } + + // Actor + validate_text("actor", &request.actor, 128)?; + + // Client + { + if !is_valid_client(request.client.as_str()) { + return Err(AuditError::Denied("invalid client".into())); + } + } + + // Reason SHA-256 + let reason_sha256 = match &request.reason_sha256 { + Some(h) => { + if !is_valid_sha256_hex(h) { + return Err(AuditError::Denied("invalid reason hash".into())); + } + h.clone() + } + None => { + return Err(AuditError::Denied("reason hash is required".into())); + } + }; + + // Command basename + if let Some(ref basename) = request.command_basename { + if !is_valid_command_basename(basename) { + return Err(AuditError::Denied("invalid command basename".into())); + } + } + + // Names + let mut clean_names: Vec = request.names.iter().cloned().collect(); + clean_names.sort(); + clean_names.dedup(); + { + for name in &clean_names { + if !is_valid_secret_name(name) { + return Err(AuditError::Denied("invalid secret name".into())); + } + } + } + + // ---- Database operations ---- + + let conn = open_connection(directory, request.expected_uid)?; + + let result = (|| -> Result { + ensure_schema(&conn)?; + conn.execute("BEGIN IMMEDIATE", [])?; + + // Verify chain and get previous hash + count + let (previous_hash, count) = verify_rows(&conn)?; + let sequence = count + 1; + + // Get timestamp + let timestamp_ns = { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| AuditError::Denied(format!("clock error: {e}")))?; + now.as_nanos() as i64 + }; + + let names_json = serde_json::to_string(&clean_names).unwrap(); + + // Build event (without event_hash yet) + let mut event = AuditEvent { + sequence, + timestamp_ns, + transaction: request.transaction, + phase: request.phase, + operation: request.operation.clone(), + actor: request.actor.clone(), + client: request.client, + reason_sha256: reason_sha256.clone(), + command_basename: request.command_basename.clone(), + names: clean_names.clone(), + result_code: request.result_code, + previous_hash: previous_hash.clone(), + event_hash: String::new(), // placeholder + }; + + // Compute event hash + event.event_hash = compute_event_hash(&previous_hash, &event); + + // Insert event + conn.execute( + "INSERT INTO events (\ + sequence, timestamp_ns, transaction_id, phase, operation,\ + actor, client, reason_sha256, command_basename, names_json,\ + result_code, previous_hash, event_hash\ + ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)", + rusqlite::params![ + event.sequence, + event.timestamp_ns, + event.transaction.to_string(), + event.phase.as_str(), + event.operation, + event.actor, + event.client.as_str(), + event.reason_sha256, + event.command_basename, + names_json, + event.result_code.map(|c| c as i64), + event.previous_hash, + event.event_hash, + ], + )?; + + // Upsert head + conn.execute( + "INSERT INTO head (singleton, sequence, event_hash) VALUES (1, ?1, ?2) \ + ON CONFLICT(singleton) DO UPDATE SET \ + sequence = excluded.sequence, event_hash = excluded.event_hash", + rusqlite::params![event.sequence, event.event_hash], + )?; + + conn.execute("COMMIT", [])?; + + Ok(event) + })(); + + match result { + Ok(event) => Ok(event), + Err(e) => { + let _ = conn.execute("ROLLBACK", []); + Err(e) + } + } +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::os::unix::fs::PermissionsExt; + + /// Create a protected directory (mode 0700) inside tmp. + fn protected_dir(tmp: &Path) -> std::path::PathBuf { + let dir = tmp.join("protected"); + fs::create_dir_all(&dir).unwrap(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); + dir + } + + /// Simple sliding-window substring check. + fn window_contains(needle: &str, haystack: &[u8]) -> bool { + haystack + .windows(needle.len()) + .any(|w| w == needle.as_bytes()) + } + + fn attempt(dir: &Path, tx: uuid::Uuid) -> Result { + append_event( + dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: tx, + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"rotate integration credential")), + command_basename: Some("curl".into()), + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ) + } + + fn terminal( + dir: &Path, + tx: uuid::Uuid, + phase: Outcome, + code: u8, + ) -> Result { + append_event( + dir, + AppendEventRequest { + operation: "source-set".into(), + phase, + transaction: tx, + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"rotate integration credential")), + command_basename: Some("curl".into()), + names: vec!["EXAMPLE_KEY".into()], + result_code: Some(code), + expected_uid: Some(unsafe { libc::getuid() }), + }, + ) + } + + // ----------------------------------------------------------------------- + // 1. attempt + success transactional + value-free + // ----------------------------------------------------------------------- + #[test] + fn attempt_and_success_transactional_value_free() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let tx = uuid::Uuid::new_v4(); + + let first = attempt(&dir, tx).expect("attempt"); + let second = terminal(&dir, tx, Outcome::Success, 0).expect("success"); + + assert_eq!(first.client, ClientFamily::Hermes); + assert_eq!(second.previous_hash, first.event_hash); + + let raw = fs::read(dir.join(DB_NAME)).unwrap(); + assert!(!window_contains("rotate integration credential", &raw)); + assert!(!window_contains("hermes:topic", &raw)); + assert!(!window_contains("Authorization: ***", &raw)); + assert!(window_contains("EXAMPLE_KEY", &raw)); + + let meta = fs::metadata(dir.join(DB_NAME)).unwrap(); + assert_eq!(meta.permissions().mode() & 0o777, 0o600); + + let result = verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 2); + assert_eq!(result.hash, second.event_hash); + } + + // ----------------------------------------------------------------------- + // 2. unknown outcome is a distinct terminal phase + // ----------------------------------------------------------------------- + #[test] + fn unknown_outcome_distinct_terminal() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let tx = uuid::Uuid::new_v4(); + + attempt(&dir, tx).unwrap(); + let unknown = terminal(&dir, tx, Outcome::Unknown, 125).unwrap(); + assert_eq!(unknown.phase, Outcome::Unknown); + assert_eq!(unknown.result_code, Some(125)); + + let result = verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 2); + } + + // ----------------------------------------------------------------------- + // 3. free-form reason & argv never persist + // ----------------------------------------------------------------------- + #[test] + fn free_form_reason_never_persists() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + let secretish = "Authorization: Bearer ***"; + let hash = sha256_hex(secretish.as_bytes()); + + append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(hash), + command_basename: Some("curl".into()), + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ) + .unwrap(); + + let raw = fs::read(dir.join(DB_NAME)).unwrap(); + assert!(!window_contains(secretish, &raw)); + assert!(!window_contains("credential-value", &raw)); + assert!(window_contains("curl", &raw)); + } + + // ----------------------------------------------------------------------- + // 4. interrupted attempt remains visible + // ----------------------------------------------------------------------- + #[test] + fn interrupted_attempt_visible() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + attempt(&dir, uuid::Uuid::new_v4()).unwrap(); + let result = verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 1); + } + + // ----------------------------------------------------------------------- + // 5. bad metadata fails before creating ledger + // ----------------------------------------------------------------------- + #[test] + fn bad_metadata_fails_before_creating_ledger() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Bad secret name + let r = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"test")), + command_basename: None, + names: vec!["BAD-NAME".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(r.is_err()); + assert!(!dir.join(DB_NAME).exists()); + + // Bad command basename + let r = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"test")), + command_basename: Some("bad\ncommand".into()), + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(r.is_err()); + } + + // ----------------------------------------------------------------------- + // 6. symlink ledger rejected + // ----------------------------------------------------------------------- + #[test] + fn symlink_ledger_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + let target = tmp.path().join("target"); + fs::write(&target, "unchanged").unwrap(); + std::os::unix::fs::symlink(&target, dir.join(DB_NAME)).unwrap(); + + let r = attempt(&dir, uuid::Uuid::new_v4()); + assert!(r.is_err()); + assert_eq!(fs::read_to_string(&target).unwrap(), "unchanged"); + } + + // ----------------------------------------------------------------------- + // 7. wrong directory / ledger mode rejected + // ----------------------------------------------------------------------- + #[test] + fn wrong_directory_mode_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); + assert!(attempt(&dir, uuid::Uuid::new_v4()).is_err()); + } + + #[test] + fn wrong_ledger_mode_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + let ledger = dir.join(DB_NAME); + { + let conn = Connection::open(&ledger).unwrap(); + conn.execute_batch( + "CREATE TABLE t(x); PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL;", + ) + .unwrap(); + } + fs::set_permissions(&ledger, fs::Permissions::from_mode(0o644)).unwrap(); + + assert!(attempt(&dir, uuid::Uuid::new_v4()).is_err()); + } + + // ----------------------------------------------------------------------- + // 8. terminal event requires result code + // ----------------------------------------------------------------------- + #[test] + fn terminal_event_requires_result_code() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Failure without result code + let r = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Failure, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(r.is_err()); + + // Attempt with result code + let r = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: Some(1), + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(r.is_err()); + } + + // ----------------------------------------------------------------------- + // 9. chain verification detects tampering + // ----------------------------------------------------------------------- + #[test] + fn chain_verification_detects_tampering() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + attempt(&dir, uuid::Uuid::new_v4()).unwrap(); + + let conn = Connection::open(dir.join(DB_NAME)).unwrap(); + conn.execute( + "UPDATE events SET operation='source-get' WHERE sequence=1", + [], + ) + .unwrap(); + + assert!(verify(&dir, Some(unsafe { libc::getuid() })).is_err()); + } + + // ----------------------------------------------------------------------- + // 10. event + head atomic rollback + // ----------------------------------------------------------------------- + #[test] + fn event_and_head_rollback_together() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let tx = uuid::Uuid::new_v4(); + + attempt(&dir, tx).unwrap(); + + // Inject trigger that rejects head updates + let conn = Connection::open(dir.join(DB_NAME)).unwrap(); + conn.execute_batch( + "CREATE TRIGGER reject_head BEFORE UPDATE ON head BEGIN SELECT RAISE(ABORT, 'fault injection'); END;", + ).unwrap(); + + let r = terminal(&dir, tx, Outcome::Success, 0); + assert!(r.is_err()); + + let result = verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 1, "only attempt should remain after rollback"); + } + + // ----------------------------------------------------------------------- + // 11. verify empty/absent ledger + // ----------------------------------------------------------------------- + #[test] + fn verify_empty_ledger() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let result = verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 0); + assert_eq!(result.hash, ZERO_HASH); + } + + // ----------------------------------------------------------------------- + // 12. reason SHA-256 validation + // ----------------------------------------------------------------------- + #[test] + fn reason_sha256_must_be_valid() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Invalid hex + let r = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some("not-a-valid-sha256-hash".into()), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(r.is_err()); + + // Missing reason + let r = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: None, + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(r.is_err()); + } + + // ----------------------------------------------------------------------- + // 13. operation validation + // ----------------------------------------------------------------------- + #[test] + fn operation_must_match_pattern() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let r = append_event( + &dir, + AppendEventRequest { + operation: "INVALID".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(r.is_err()); + } + + // ----------------------------------------------------------------------- + // 14. nil UUID accepted + // ----------------------------------------------------------------------- + #[test] + fn nil_uuid_accepted() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let r = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::nil(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(r.is_ok()); + } + + // ----------------------------------------------------------------------- + // 15. names sorted and validated + // ----------------------------------------------------------------------- + #[test] + fn names_sorted_and_validated() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let event = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"test")), + command_basename: None, + names: vec!["Z_KEY".into(), "A_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ) + .unwrap(); + assert_eq!(event.names, vec!["A_KEY", "Z_KEY"]); + } + + // ----------------------------------------------------------------------- + // 16. owner mismatch rejected on verify + // ----------------------------------------------------------------------- + #[test] + fn owner_mismatch_rejected_on_verify() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + attempt(&dir, uuid::Uuid::new_v4()).unwrap(); + + let wrong_uid = if unsafe { libc::getuid() } == 0 { 1 } else { 0 }; + if unsafe { libc::getuid() } != 0 { + assert!(verify(&dir, Some(wrong_uid)).is_err()); + } + } + + // ----------------------------------------------------------------------- + // 17. multiple transactions chain correctly + // ----------------------------------------------------------------------- + #[test] + fn multiple_transactions_chain_correctly() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + let tx1 = uuid::Uuid::new_v4(); + let e1 = attempt(&dir, tx1).unwrap(); + let e2 = terminal(&dir, tx1, Outcome::Success, 0).unwrap(); + assert_eq!(e2.previous_hash, e1.event_hash); + + let tx2 = uuid::Uuid::new_v4(); + let e3 = attempt(&dir, tx2).unwrap(); + assert_eq!(e3.previous_hash, e2.event_hash); + let e4 = terminal(&dir, tx2, Outcome::Failure, 1).unwrap(); + assert_eq!(e4.previous_hash, e3.event_hash); + + let tx3 = uuid::Uuid::new_v4(); + let e5 = attempt(&dir, tx3).unwrap(); + assert_eq!(e5.previous_hash, e4.event_hash); + let e6 = terminal(&dir, tx3, Outcome::Unknown, 127).unwrap(); + assert_eq!(e6.previous_hash, e5.event_hash); + + let result = verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 6); + assert_eq!(result.hash, e6.event_hash); + } + + // ----------------------------------------------------------------------- + // 18. SQLite integrity check passes on verify + // ----------------------------------------------------------------------- + #[test] + fn sqlite_integrity_check_passes() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + attempt(&dir, uuid::Uuid::new_v4()).unwrap(); + assert!(verify(&dir, Some(unsafe { libc::getuid() })).is_ok()); + } + + // ----------------------------------------------------------------------- + // 19. duplicate names are deduplicated + // ----------------------------------------------------------------------- + #[test] + fn duplicate_names_deduplicated() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + let event = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(sha256_hex(b"test")), + command_basename: None, + names: vec!["A_KEY".into(), "A_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ) + .unwrap(); + assert_eq!(event.names, vec!["A_KEY"]); + } + + // ----------------------------------------------------------------------- + // 20. all valid client families accepted + // ----------------------------------------------------------------------- + #[test] + fn all_valid_client_families_accepted() { + let tmp = tempfile::tempdir().unwrap(); + + for client_str in &[ + "hermes", + "claude", + "codex", + "opencode", + "cursor", + "agy", + "fixed-consumer", + "unknown", + ] { + let dir = protected_dir(&tmp.path().join(client_str)); + let client = ClientFamily::from_str(client_str).unwrap(); + let r = append_event( + &dir, + AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client, + reason_sha256: Some(sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(r.is_ok(), "client '{client_str}' should be accepted"); + } + } +} diff --git a/sudo-secretspec-cli/src/broker.rs b/sudo-secretspec-cli/src/broker.rs new file mode 100644 index 000000000..4093811f4 --- /dev/null +++ b/sudo-secretspec-cli/src/broker.rs @@ -0,0 +1,405 @@ +//! Root-owned fail-closed SecretSpec broker. +//! +//! The hidden `__broker` subcommand receives operation + options as trailing +//! arguments and validates the privilege boundary before running any operation. +//! All provider operations are value-free audited. +//! +//! Mutation safety: before any set/add/delete, the manifest and dotenv are +//! backed up to `.rollback.` copies. On success the backups are +//! removed; on failure they are restored atomically. A crash during mutation +//! leaves the backups visible to `doctor` but the original state recoverable. + +use std::ffi::OsString; + +use clap::Parser; +use sha2::{Digest, Sha256}; + +use crate::audit::{self, AppendEventRequest, ClientFamily, Outcome}; +use crate::config::Config; + +// --------------------------------------------------------------------------- +// Paths +// --------------------------------------------------------------------------- + +const CONFIG_PATH: &str = "/usr/local/etc/sudo-secretspec.toml"; + +// --------------------------------------------------------------------------- +// Broker CLI (sub-parser for __broker) +// --------------------------------------------------------------------------- + +#[derive(Debug, Parser)] +#[command( + about = "Internal broker (sudo-only, hidden)", + override_usage = "sudo sudo-secretspec __broker [OPTIONS]" +)] +pub(crate) struct Broker { + /// Broker operation + #[arg()] + pub(crate) operation: String, + + #[arg(long, default_value = "unknown")] + pub(crate) client: String, + + #[arg(long, default_value = "")] + pub(crate) reason: String, + + #[arg(long)] + pub(crate) name: Option, + + #[arg(long)] + pub(crate) command_basename: Option, +} + +// --------------------------------------------------------------------------- +// Dispatch +// --------------------------------------------------------------------------- + +/// Parse broker args from raw trailing arguments and route to the operation. +pub fn dispatch(raw: &[OsString]) -> Result<(), i32> { + let broker = match Broker::try_parse_from( + std::iter::once(OsString::from("__broker")).chain(raw.iter().cloned()), + ) { + Ok(b) => b, + Err(e) => { + eprintln!("broker: {e}"); + return Err(2); + } + }; + run(&broker) +} + +// --------------------------------------------------------------------------- +// Environment validation +// --------------------------------------------------------------------------- + +fn require_root() -> Result<(), i32> { + if unsafe { libc::geteuid() } != 0 { + eprintln!("broker: must run as root"); + return Err(2); + } + Ok(()) +} + +fn load_config() -> Result { + let content = std::fs::read_to_string(CONFIG_PATH).map_err(|e| { + eprintln!("broker: cannot read config: {e}"); + 2 + })?; + Config::parse(&content).map_err(|e| { + eprintln!("broker: invalid config: {e}"); + 2 + }) +} + +fn require_boundary(cfg: &Config) -> Result<(), i32> { + let vault = &cfg.vault; + if !vault.exists() || vault.is_symlink() { + eprintln!("broker: vault missing or symlinked"); + return Err(2); + } + let manifest = vault.join("secretspec.toml"); + let dotenv = vault.join(".env"); + if !manifest.is_file() || manifest.is_symlink() { + eprintln!("broker: manifest missing or symlinked"); + return Err(2); + } + if !dotenv.is_file() || dotenv.is_symlink() { + eprintln!("broker: dotenv missing or symlinked"); + return Err(2); + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Mutation helpers — backup/restore/commit for manifest and dotenv +// --------------------------------------------------------------------------- + +struct Mutation { + vault: std::path::PathBuf, + manifest: std::path::PathBuf, + dotenv: std::path::PathBuf, + transaction: uuid::Uuid, +} + +impl Mutation { + fn begin(cfg: &Config, transaction: uuid::Uuid) -> Result { + let vault = cfg.vault.clone(); + let manifest = vault.join("secretspec.toml"); + let dotenv = vault.join(".env"); + + let m = Self { + vault, + manifest, + dotenv, + transaction, + }; + + // Create rollback copies + for (src, suffix) in [(&m.manifest, "toml"), (&m.dotenv, "env")] { + let dst = m.rollback_path(suffix); + if dst.exists() { + eprintln!("broker: rollback path collision: {}", dst.display()); + return Err(2); + } + std::fs::copy(src, &dst).map_err(|e| { + eprintln!("broker: cannot create rollback copy: {e}"); + 2 + })?; + } + Ok(m) + } + + fn rollback_path(&self, suffix: &str) -> std::path::PathBuf { + self.vault.join(format!( + ".secretspec.{}.rollback.{}", + suffix, self.transaction + )) + } + + fn restore(&self) { + for (dest, suffix) in [(&self.manifest, "toml"), (&self.dotenv, "env")] { + let backup = self.rollback_path(suffix); + if backup.is_file() { + let _ = std::fs::copy(&backup, dest); + let _ = std::fs::remove_file(&backup); + } + } + } + + fn commit(&self) { + for suffix in ["toml", "env"] { + let backup = self.rollback_path(suffix); + let _ = std::fs::remove_file(&backup); + } + } +} + +// --------------------------------------------------------------------------- +// Client resolution +// --------------------------------------------------------------------------- + +fn resolve_client(raw: &str) -> ClientFamily { + match raw { + "hermes" => ClientFamily::Hermes, + "claude" => ClientFamily::Claude, + "codex" => ClientFamily::Codex, + "opencode" => ClientFamily::OpenCode, + "cursor" => ClientFamily::Cursor, + "agy" => ClientFamily::Agy, + "fixed-consumer" => ClientFamily::FixedConsumer, + _ => ClientFamily::Unknown, + } +} + +fn reason_sha256(reason: &str) -> Option { + if reason.is_empty() { + return Some(String::from(audit::ZERO_HASH)); + } + Some(format!("{:x}", Sha256::digest(reason.as_bytes()))) +} + +fn actor_from_env() -> String { + std::env::var("SUDO_USER").unwrap_or_else(|_| "root".into()) +} + +// --------------------------------------------------------------------------- +// Operations +// --------------------------------------------------------------------------- + +fn run(broker: &Broker) -> Result<(), i32> { + match broker.operation.as_str() { + "audit-verify" => run_audit_verify(broker), + "source-get" + | "source-set" + | "source-add" + | "source-delete" + | "source-check" + | "source-export" + | "source-template-check" => { + require_root()?; + let cfg = load_config()?; + require_boundary(&cfg)?; + + let client = resolve_client(&broker.client); + let reason_hash = reason_sha256(&broker.reason); + let transaction = uuid::Uuid::new_v4(); + let names = broker + .name + .as_deref() + .map(|n| vec![n.to_string()]) + .unwrap_or_default(); + let actor = actor_from_env(); + + // Audit attempt + let _ = audit::append_event( + &cfg.vault, + AppendEventRequest { + operation: broker.operation.clone(), + phase: Outcome::Attempt, + transaction, + actor: actor.clone(), + client, + reason_sha256: reason_hash.clone(), + command_basename: broker.command_basename.clone(), + names: names.clone(), + result_code: None, + expected_uid: None, + }, + ); + + // Begin mutation for write operations + let mutation = if matches!( + broker.operation.as_str(), + "source-set" | "source-add" | "source-delete" + ) { + Some(Mutation::begin(&cfg, transaction)?) + } else { + None + }; + + // Execute the operation + let (rc, names) = execute(broker, &cfg); + + // Commit or restore mutation + if let Some(m) = &mutation { + if rc == 0 { + m.commit(); + } else { + m.restore(); + } + } + + // Terminal audit (unknown outcome if rc says success but we can't prove it) + let phase = if rc == 0 { + Outcome::Success + } else { + Outcome::Failure + }; + let _ = audit::append_event( + &cfg.vault, + AppendEventRequest { + operation: broker.operation.clone(), + phase, + transaction, + actor, + client, + reason_sha256: reason_hash, + command_basename: broker.command_basename.clone(), + names, + result_code: Some(rc), + expected_uid: None, + }, + ); + + if rc != 0 { Err(rc as i32) } else { Ok(()) } + } + op => { + eprintln!("broker: unknown operation: {op}"); + Err(2) + } + } +} + +fn run_audit_verify(_broker: &Broker) -> Result<(), i32> { + require_root()?; + let cfg = load_config()?; + match audit::verify(&cfg.vault, None) { + Ok(result) => { + println!("audit-verify: {} events, tip {}", result.count, result.hash); + Ok(()) + } + Err(e) => { + eprintln!("audit-verify failed: {e}"); + Err(1) + } + } +} + +fn execute(broker: &Broker, cfg: &Config) -> (u8, Vec) { + let manifest = cfg.vault.join("secretspec.toml"); + let secrets = match secretspec::Secrets::load_from(&manifest) { + Ok(mut s) => { + s.set_provider("dotenv"); + if !broker.reason.is_empty() { + s = s.with_reason(broker.reason.clone()); + } + s + } + Err(e) => { + eprintln!("broker: cannot load secrets: {e}"); + return (2, vec![]); + } + }; + + let name = broker.name.as_deref().unwrap_or(""); + + match broker.operation.as_str() { + "source-get" => match secrets.resolve_named(name) { + Ok(secretspec::NamedResolution::Resolved(secret)) => { + if let Some(value) = secret.value { + println!("{value}"); + (0, vec![name.into()]) + } else { + eprintln!("broker: {name} has no value"); + (1, vec![name.into()]) + } + } + Ok(_) => { + eprintln!("broker: {name} is not resolved"); + (1, vec![name.into()]) + } + Err(e) => { + eprintln!("broker: {e}"); + (1, vec![name.into()]) + } + }, + "source-set" | "source-add" => match secrets.set(name, None) { + Ok(()) => (0, vec![name.into()]), + Err(e) => { + eprintln!("broker: {e}"); + (1, vec![name.into()]) + } + }, + "source-delete" => match secrets.delete(name) { + Ok(_) => (0, vec![name.into()]), + Err(e) => { + eprintln!("broker: {e}"); + (1, vec![name.into()]) + } + }, + "source-check" => match secrets.check(false) { + Ok(_) => (0, vec![]), + Err(e) => { + eprintln!("broker: {e}"); + (1, vec![]) + } + }, + "source-export" => { + use std::io; + match secrets.export(secretspec::ExportFormat::Json, &mut io::stdout().lock()) { + Ok(()) => (0, vec![]), + Err(e) => { + eprintln!("broker: {e}"); + (1, vec![]) + } + } + } + "source-template-check" => { + let declarations = &cfg.declarations; + if !declarations.is_file() || declarations.is_symlink() { + eprintln!("broker: declaration template missing or symlinked"); + return (2, vec![]); + } + let manifest_bytes = std::fs::read(&manifest).unwrap_or_default(); + let template_bytes = std::fs::read(declarations).unwrap_or_default(); + if manifest_bytes == template_bytes { + println!("runtime manifest matches tracked declaration example"); + (0, vec![]) + } else { + eprintln!("broker: manifest differs from declaration template"); + (1, vec![]) + } + } + _ => (2, vec![]), + } +} diff --git a/sudo-secretspec-cli/src/config.rs b/sudo-secretspec-cli/src/config.rs new file mode 100644 index 000000000..cdf5db0bd --- /dev/null +++ b/sudo-secretspec-cli/src/config.rs @@ -0,0 +1,89 @@ +use std::path::{Path, PathBuf}; + +use serde::Deserialize; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum ConfigError { + #[error("invalid TOML config: {0}")] + Parse(#[from] toml::de::Error), + #[error("invalid sudo-secretspec config: {0}")] + Invalid(&'static str), +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + pub engine: PathBuf, + pub audit_helper: PathBuf, + pub vault: PathBuf, + pub vault_realpath: PathBuf, + pub declarations: PathBuf, + pub service_user: String, + pub service_group: String, +} + +impl Config { + pub fn parse(input: &str) -> Result { + let config: Self = toml::from_str(input)?; + config.validate()?; + Ok(config) + } + + fn validate(&self) -> Result<(), ConfigError> { + for path in [&self.engine, &self.audit_helper, &self.declarations] { + if !path.is_absolute() { + return Err(ConfigError::Invalid("managed paths must be absolute")); + } + if path.to_string_lossy().contains("..") { + return Err(ConfigError::Invalid("managed paths must not contain '..'")); + } + } + let vault_name = direct_child(&self.vault, Path::new("/var/db"))?; + let real_name = direct_child(&self.vault_realpath, Path::new("/private/var/db"))?; + if vault_name != real_name { + return Err(ConfigError::Invalid("vault and resolved vault must match")); + } + if !valid_service_identity(&self.service_user, true) + || !valid_service_identity(&self.service_group, false) + { + return Err(ConfigError::Invalid("invalid service identity")); + } + Ok(()) + } + + #[must_use] + pub fn vault(&self) -> &Path { + &self.vault + } + + #[must_use] + pub fn service_user(&self) -> &str { + &self.service_user + } +} + +fn direct_child<'a>(path: &'a Path, parent: &Path) -> Result<&'a std::ffi::OsStr, ConfigError> { + let relative = path + .strip_prefix(parent) + .map_err(|_| ConfigError::Invalid("vault is outside protected database root"))?; + let mut components = relative.components(); + let name = components + .next() + .ok_or(ConfigError::Invalid("vault name is missing"))?; + if components.next().is_some() { + return Err(ConfigError::Invalid("vault must be one direct child")); + } + Ok(name.as_os_str()) +} + +fn valid_service_identity(value: &str, require_underscore: bool) -> bool { + if value.is_empty() || value.len() > 31 || (require_underscore && !value.starts_with('_')) { + return false; + } + value.bytes().enumerate().all(|(index, byte)| match byte { + b'a'..=b'z' | b'_' => true, + b'0'..=b'9' => index > 0, + _ => false, + }) +} diff --git a/sudo-secretspec-cli/src/drift.rs b/sudo-secretspec-cli/src/drift.rs new file mode 100644 index 000000000..b41f4be42 --- /dev/null +++ b/sudo-secretspec-cli/src/drift.rs @@ -0,0 +1,491 @@ +//! Metadata-only, non-repairing drift validation for sudo-secretspec. +//! +//! Never reads secret values. Never mutates state. + +use std::fs; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use serde::Serialize; +use sha2::{Digest, Sha256}; +use thiserror::Error; + +use crate::audit; +use crate::config::Config; + +#[derive(Debug, Error)] +pub enum DriftError { + #[error("config: {0}")] + Config(#[from] crate::config::ConfigError), + #[error("io: {0}")] + Io(#[from] std::io::Error), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Layout { + pub config: PathBuf, + pub vault: PathBuf, + pub vault_realpath: PathBuf, + pub service_user: String, + pub service_group: String, + pub declarations: PathBuf, + pub engine: PathBuf, + pub audit: PathBuf, + pub broker: PathBuf, + pub client: PathBuf, + pub checker: PathBuf, + pub retired: PathBuf, + pub guidance: PathBuf, + pub sudoers: PathBuf, + pub source_manifest: PathBuf, +} + +impl Layout { + fn from_config(cfg: Config, config_path: PathBuf) -> Self { + // Prefer deriving the install prefix from the configured engine path. + // Single-binary installs place the privileged binary under libexec and + // the public client under bin. + let prefix = cfg + .engine + .parent() + .and_then(Path::parent) + .unwrap_or_else(|| Path::new("/usr/local")) + .to_path_buf(); + let libexec = prefix.join("libexec"); + let bin = prefix.join("bin"); + let share = prefix.join("share").join("sudo-secretspec"); + + Self { + vault: cfg.vault, + vault_realpath: cfg.vault_realpath, + service_user: cfg.service_user, + service_group: cfg.service_group, + declarations: cfg.declarations, + engine: cfg.engine.clone(), + // In the Rust single-binary model the audit helper is the same + // privileged binary; keep a distinct field for compatibility. + audit: cfg.audit_helper, + broker: libexec.join("sudo-secretspec"), + client: bin.join("sudo-secretspec"), + checker: bin.join("sudo-secretspec"), + retired: share.join("sudo-secretspec-retired.toml"), + guidance: share.join("AI-GUIDANCE.md"), + sudoers: PathBuf::from("/private/etc/sudoers.d/sudo-secretspec"), + source_manifest: share.join("MANIFEST.sha256"), + config: config_path, + } + } +} + +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct Finding { + pub code: String, + pub detail: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, +} + +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct Report { + pub ok: bool, + pub findings: Vec, +} + +impl Report { + fn from_findings(findings: Vec) -> Self { + Self { + ok: findings.is_empty(), + findings, + } + } +} + +fn finding(code: &str, path: Option<&Path>, detail: impl Into) -> Finding { + Finding { + code: code.into(), + detail: detail.into(), + path: path.map(|p| p.display().to_string()), + } +} + +/// Load and validate the protected TOML configuration at `path`. +pub fn load_config(path: &Path) -> Result { + let content = fs::read_to_string(path)?; + let cfg = Config::parse(&content)?; + Ok(Layout::from_config(cfg, path.to_path_buf())) +} + +fn owner_name(uid: u32) -> String { + unsafe { + let pw = libc::getpwuid(uid); + if pw.is_null() { + return uid.to_string(); + } + std::ffi::CStr::from_ptr((*pw).pw_name) + .to_string_lossy() + .into_owned() + } +} + +fn group_name(gid: u32) -> String { + unsafe { + let gr = libc::getgrgid(gid); + if gr.is_null() { + return gid.to_string(); + } + std::ffi::CStr::from_ptr((*gr).gr_name) + .to_string_lossy() + .into_owned() + } +} + +fn metadata_owner_group_mode(path: &Path) -> std::io::Result<(String, String, u32)> { + let meta = fs::symlink_metadata(path)?; + Ok(( + owner_name(meta.uid()), + group_name(meta.gid()), + meta.permissions().mode() & 0o777, + )) +} + +fn has_extended_acl(path: &Path) -> bool { + let output = Command::new("/bin/ls") + .args(["-lde", &path.display().to_string()]) + .output(); + match output { + Ok(out) if out.status.success() => { + String::from_utf8_lossy(&out.stdout).lines().count() != 1 + } + _ => true, + } +} + +fn check_protected_file( + path: &Path, + owner: &str, + group: &str, + mode: u32, + findings: &mut Vec, +) { + if path.is_symlink() { + findings.push(finding( + "SYMLINK_FORBIDDEN", + Some(path), + "path must not be a symlink", + )); + return; + } + match metadata_owner_group_mode(path) { + Ok((o, g, m)) => { + if o != owner || g != group || m != mode { + findings.push(finding( + "METADATA_MISMATCH", + Some(path), + format!("expected {owner}:{group}:{mode:o}, got {o}:{g}:{m:o}"), + )); + } + if has_extended_acl(path) { + findings.push(finding( + "ACL_PRESENT", + Some(path), + "extended ACL present on protected path", + )); + } + } + Err(_) => findings.push(finding( + "PATH_MISSING", + Some(path), + "required protected path is missing", + )), + } +} + +fn check_ancestor_chain(path: &Path, findings: &mut Vec) { + // Validate the resolved path's parents for root ownership and non-writability. + let resolved = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); + let mut current = resolved.as_path(); + while let Some(parent) = current.parent() { + if parent == Path::new("/") { + break; + } + // Accept the conventional macOS alias roots only as leaf public names; + // validation always walks the resolved private chain. + if parent.is_symlink() + && !matches!(parent.to_string_lossy().as_ref(), "/var" | "/etc" | "/tmp") + { + findings.push(finding( + "ANCESTOR_SYMLINK", + Some(parent), + "protected ancestor must not be a symlink", + )); + } + if let Ok((o, _g, m)) = metadata_owner_group_mode(parent) { + if o != "root" || m & 0o022 != 0 { + findings.push(finding( + "REMOVABLE_ANCESTOR", + Some(parent), + "ancestor is not root-owned or is group/world-writable", + )); + } + if has_extended_acl(parent) { + findings.push(finding( + "ACL_PRESENT", + Some(parent), + "extended ACL present on ancestor", + )); + } + } + current = parent; + if parent == Path::new("/private") || parent == Path::new("/usr") { + break; + } + } +} + +fn sha256_file(path: &Path) -> Option { + let bytes = fs::read(path).ok()?; + Some(format!("{:x}", Sha256::digest(bytes))) +} + +fn parse_manifest(path: &Path) -> Vec<(String, PathBuf)> { + let Ok(text) = fs::read_to_string(path) else { + return Vec::new(); + }; + text.lines() + .filter_map(|line| { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + return None; + } + let (hash, rest) = line.split_once(char::is_whitespace)?; + let rest = rest.trim(); + Some((hash.to_string(), PathBuf::from(rest))) + }) + .collect() +} + +/// Inspect the live installation described by `layout`. +/// +/// This never repairs and never opens secret-bearing file contents for parsing. +pub fn inspect(layout: &Layout) -> Report { + let mut findings = Vec::new(); + + // Config file itself. + check_protected_file(&layout.config, "root", "wheel", 0o444, &mut findings); + check_ancestor_chain(&layout.config, &mut findings); + + // Installed binaries / shared assets. + for (path, mode) in [ + (&layout.client, 0o755), + (&layout.broker, 0o755), + (&layout.engine, 0o755), + (&layout.retired, 0o444), + (&layout.guidance, 0o444), + (&layout.declarations, 0o444), + (&layout.source_manifest, 0o444), + (&layout.sudoers, 0o440), + ] { + check_protected_file(path, "root", "wheel", mode, &mut findings); + check_ancestor_chain(path, &mut findings); + } + + // Source manifest hashes, when present. + if layout.source_manifest.is_file() { + for (expected, path) in parse_manifest(&layout.source_manifest) { + match sha256_file(&path) { + Some(actual) if actual == expected => {} + Some(_) => findings.push(finding( + "INSTALLED_HASH_MISMATCH", + Some(&path), + "installed artifact hash differs from release manifest", + )), + None => findings.push(finding( + "INSTALLED_FILE_MISSING", + Some(&path), + "manifest lists a missing installed artifact", + )), + } + } + } + + // Sudoers syntax. + if layout.sudoers.exists() { + let status = Command::new("/usr/sbin/visudo") + .args(["-c", "-f"]) + .arg(&layout.sudoers) + .status(); + match status { + Ok(s) if s.success() => {} + _ => findings.push(finding( + "SUDOERS_INVALID", + Some(&layout.sudoers), + "visudo rejected the sudoers policy", + )), + } + } + + // Vault metadata and allowlisted runtime entries only. + if layout.vault.is_symlink() { + findings.push(finding( + "VAULT_SYMLINK", + Some(&layout.vault), + "vault must not be a symlink", + )); + } else { + check_protected_file( + &layout.vault, + &layout.service_user, + &layout.service_group, + 0o700, + &mut findings, + ); + } + + // Resolve public /var spelling through the macOS private chain. + match layout.vault.canonicalize() { + Ok(resolved) if resolved != layout.vault_realpath => findings.push(finding( + "VAULT_REALPATH_MISMATCH", + Some(&layout.vault), + format!( + "vault resolves to {}, expected {}", + resolved.display(), + layout.vault_realpath.display() + ), + )), + Ok(resolved) => check_ancestor_chain(&resolved, &mut findings), + Err(_) => findings.push(finding( + "VAULT_UNRESOLVABLE", + Some(&layout.vault), + "vault path cannot be resolved", + )), + } + + let allowed = [ + "secretspec.toml", + ".env", + "broker-audit.sqlite3", + "broker-audit.sqlite3-wal", + "broker-audit.sqlite3-shm", + "broker-audit.sqlite3-journal", + ]; + if let Ok(entries) = fs::read_dir(&layout.vault) { + for entry in entries.flatten() { + let name = entry.file_name(); + let name = name.to_string_lossy(); + let path = entry.path(); + if name.contains(".rollback.") { + findings.push(finding( + "PENDING_ROLLBACK", + Some(&path), + "pending rollback artifact requires operator review", + )); + } else if !allowed.iter().any(|a| *a == name) { + findings.push(finding( + "UNEXPECTED_RUNTIME_ENTRY", + Some(&path), + "vault contains a file outside the runtime allowlist", + )); + } + if path.is_file() || path.is_symlink() { + check_protected_file( + &path, + &layout.service_user, + &layout.service_group, + 0o600, + &mut findings, + ); + } + } + } + + // Audit integrity via library (no secret contents). + if let Err(e) = audit::verify(&layout.vault, None) { + findings.push(finding( + "AUDIT_VERIFY_FAILED", + Some(&layout.vault.join(audit::DB_NAME)), + format!("audit verification failed: {e}"), + )); + } + + Report::from_findings(findings) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + use tempfile::tempdir; + + fn write_cfg(dir: &Path) -> PathBuf { + let path = dir.join("sudo-secretspec.toml"); + fs::write( + &path, + r#" +engine = "/usr/local/libexec/sudo-secretspec" +audit_helper = "/usr/local/libexec/sudo-secretspec" +vault = "/var/db/sudo-secretspec" +vault_realpath = "/private/var/db/sudo-secretspec" +declarations = "/usr/local/share/sudo-secretspec/secretspec.toml" +service_user = "_sudo_secretspec" +service_group = "_sudo_secretspec" +"#, + ) + .unwrap(); + path + } + + #[test] + fn load_config_builds_single_binary_layout() { + let tmp = tempdir().unwrap(); + let path = write_cfg(tmp.path()); + let layout = load_config(&path).unwrap(); + assert_eq!( + layout.broker, + PathBuf::from("/usr/local/libexec/sudo-secretspec") + ); + assert_eq!( + layout.client, + PathBuf::from("/usr/local/bin/sudo-secretspec") + ); + assert_eq!(layout.vault, PathBuf::from("/var/db/sudo-secretspec")); + } + + #[test] + fn unexpected_runtime_entry_is_reported() { + let tmp = tempdir().unwrap(); + let vault = tmp.path().join("vault"); + fs::create_dir_all(&vault).unwrap(); + fs::set_permissions(&vault, fs::Permissions::from_mode(0o700)).unwrap(); + fs::write(vault.join("secretspec.toml"), "x = 1").unwrap(); + fs::write(vault.join(".env"), "").unwrap(); + fs::write(vault.join("evil.txt"), "nope").unwrap(); + + let layout = Layout { + config: tmp.path().join("missing.toml"), + vault: vault.clone(), + vault_realpath: vault.clone(), + service_user: owner_name(unsafe { libc::getuid() }), + service_group: group_name(unsafe { libc::getgid() }), + declarations: tmp.path().join("decl.toml"), + engine: tmp.path().join("engine"), + audit: tmp.path().join("audit"), + broker: tmp.path().join("broker"), + client: tmp.path().join("client"), + checker: tmp.path().join("checker"), + retired: tmp.path().join("retired"), + guidance: tmp.path().join("guidance"), + sudoers: tmp.path().join("sudoers"), + source_manifest: tmp.path().join("MANIFEST.sha256"), + }; + let report = inspect(&layout); + assert!( + report + .findings + .iter() + .any(|f| f.code == "UNEXPECTED_RUNTIME_ENTRY"), + "{:?}", + report.findings + ); + } +} diff --git a/sudo-secretspec-cli/src/install.rs b/sudo-secretspec-cli/src/install.rs new file mode 100644 index 000000000..b693422da --- /dev/null +++ b/sudo-secretspec-cli/src/install.rs @@ -0,0 +1,479 @@ +//! Privileged installer for the sudo-secretspec boundary. +//! +//! Fresh installs can create the dedicated service identity and vault. +//! Existing protected stores must be adopted explicitly. Dry-run validates +//! without mutating. + +use std::fs; +use std::io::Write; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use sha2::{Digest, Sha256}; +use thiserror::Error; + +const PREFIX: &str = "/usr/local"; +const CONFIG_PATH: &str = "/usr/local/etc/sudo-secretspec.toml"; +const SUDOERS_PATH: &str = "/private/etc/sudoers.d/sudo-secretspec"; +const DEFAULT_VAULT: &str = "/var/db/sudo-secretspec"; +const DEFAULT_USER: &str = "_sudo_secretspec"; +const DEFAULT_GROUP: &str = "_sudo_secretspec"; + +#[derive(Debug, Error)] +pub enum InstallError { + #[error("{0}")] + Denied(String), + #[error("io: {0}")] + Io(#[from] std::io::Error), +} + +#[derive(Debug, Clone)] +pub struct InstallRequest { + pub declarations: PathBuf, + pub dry_run: bool, + pub adopt_existing: bool, + pub vault: PathBuf, + pub service_user: String, + pub service_group: String, + pub operator: String, + pub source_root: Option, +} + +impl InstallRequest { + pub fn from_cli(declarations: PathBuf, dry_run: bool, adopt_existing: bool) -> Self { + let operator = std::env::var("SUDO_USER") + .or_else(|_| std::env::var("USER")) + .unwrap_or_else(|_| "root".into()); + Self { + declarations, + dry_run, + adopt_existing, + vault: PathBuf::from(DEFAULT_VAULT), + service_user: DEFAULT_USER.into(), + service_group: DEFAULT_GROUP.into(), + operator, + source_root: None, + } + } +} + +fn require_root() -> Result<(), InstallError> { + if unsafe { libc::geteuid() } != 0 { + return Err(InstallError::Denied( + "must run as root (Touch ID/sudo is expected, including dry-run)".into(), + )); + } + Ok(()) +} + +fn resolve_path(path: &Path) -> PathBuf { + fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) +} + +fn sha256_file(path: &Path) -> Result { + let bytes = fs::read(path)?; + Ok(format!("{:x}", Sha256::digest(bytes))) +} + +fn install_file(src: &Path, dst: &Path, mode: u32) -> Result<(), InstallError> { + if let Some(parent) = dst.parent() { + fs::create_dir_all(parent)?; + } + let tmp = dst.with_extension(format!("new.{}", std::process::id())); + fs::copy(src, &tmp)?; + let mut perms = fs::metadata(&tmp)?.permissions(); + perms.set_mode(mode); + fs::set_permissions(&tmp, perms)?; + // Best-effort ownership; already root when installer is root. + let _ = Command::new("/usr/sbin/chown") + .args(["root:wheel"]) + .arg(&tmp) + .status(); + fs::rename(&tmp, dst)?; + Ok(()) +} + +fn write_bytes(dst: &Path, bytes: &[u8], mode: u32) -> Result<(), InstallError> { + if let Some(parent) = dst.parent() { + fs::create_dir_all(parent)?; + } + let tmp = dst.with_extension(format!("new.{}", std::process::id())); + { + let mut f = fs::File::create(&tmp)?; + f.write_all(bytes)?; + } + let mut perms = fs::metadata(&tmp)?.permissions(); + perms.set_mode(mode); + fs::set_permissions(&tmp, perms)?; + let _ = Command::new("/usr/sbin/chown") + .args(["root:wheel"]) + .arg(&tmp) + .status(); + fs::rename(&tmp, dst)?; + Ok(()) +} + +fn ensure_service_group(name: &str, create: bool) -> Result { + let output = Command::new("/usr/bin/dscl") + .args([".", "-read", &format!("/Groups/{name}"), "PrimaryGroupID"]) + .output()?; + if output.status.success() { + let text = String::from_utf8_lossy(&output.stdout); + let gid = text + .split_whitespace() + .last() + .and_then(|s| s.parse().ok()) + .ok_or_else(|| InstallError::Denied("cannot parse group id".into()))?; + return Ok(gid); + } + if !create { + return Err(InstallError::Denied(format!( + "adopted group missing: {name}" + ))); + } + // Find free GID 400-499. + let mut gid = 499u32; + while gid >= 400 { + let probe = Command::new("/usr/bin/dscl") + .args([ + ".", + "-search", + "/Groups", + "PrimaryGroupID", + &gid.to_string(), + ]) + .output()?; + if !String::from_utf8_lossy(&probe.stdout).contains(char::is_alphanumeric) { + break; + } + gid -= 1; + } + if gid < 400 { + return Err(InstallError::Denied("no free hidden group id".into())); + } + for args in [ + vec![".", "-create", &format!("/Groups/{name}")], + vec![ + ".", + "-create", + &format!("/Groups/{name}"), + "PrimaryGroupID", + &gid.to_string(), + ], + vec![".", "-create", &format!("/Groups/{name}"), "Password", "*"], + ] { + let status = Command::new("/usr/bin/dscl").args(&args).status()?; + if !status.success() { + return Err(InstallError::Denied(format!( + "failed to create group {name}" + ))); + } + } + Ok(gid) +} + +fn ensure_service_user(name: &str, gid: u32, create: bool) -> Result<(), InstallError> { + let output = Command::new("/usr/bin/id").arg(name).output()?; + if output.status.success() { + return Ok(()); + } + if !create { + return Err(InstallError::Denied(format!( + "adopted user missing: {name}" + ))); + } + let mut uid = 499u32; + while uid >= 400 { + let probe = Command::new("/usr/bin/dscl") + .args([".", "-search", "/Users", "UniqueID", &uid.to_string()]) + .output()?; + if !String::from_utf8_lossy(&probe.stdout).contains(char::is_alphanumeric) { + break; + } + uid -= 1; + } + if uid < 400 { + return Err(InstallError::Denied("no free hidden user id".into())); + } + let home = "/var/empty"; + let shell = "/usr/bin/false"; + let path = format!("/Users/{name}"); + for args in [ + vec![".", "-create", &path], + vec![".", "-create", &path, "UniqueID", &uid.to_string()], + vec![".", "-create", &path, "PrimaryGroupID", &gid.to_string()], + vec![".", "-create", &path, "UserShell", shell], + vec![".", "-create", &path, "NFSHomeDirectory", home], + vec![".", "-create", &path, "IsHidden", "1"], + vec![".", "-create", &path, "Password", "*"], + ] { + let status = Command::new("/usr/bin/dscl").args(&args).status()?; + if !status.success() { + return Err(InstallError::Denied(format!( + "failed to create user {name}" + ))); + } + } + Ok(()) +} + +fn validate_protected_ancestors() -> Result<(), InstallError> { + for dir in [ + "/usr", + "/usr/local", + "/private", + "/private/var", + "/private/var/db", + "/private/etc", + "/private/etc/sudoers.d", + ] { + let path = Path::new(dir); + if !path.is_dir() || path.is_symlink() { + return Err(InstallError::Denied(format!( + "unsafe protected directory {dir}" + ))); + } + let meta = fs::metadata(path)?; + if meta.uid() != 0 || (meta.permissions().mode() & 0o022) != 0 { + return Err(InstallError::Denied(format!( + "unsafe protected directory metadata {dir}" + ))); + } + } + Ok(()) +} + +fn config_toml(req: &InstallRequest, vault_real: &Path) -> String { + format!( + "engine = \"{prefix}/libexec/sudo-secretspec\"\n\ + audit_helper = \"{prefix}/libexec/sudo-secretspec\"\n\ + vault = \"{vault}\"\n\ + vault_realpath = \"{vault_real}\"\n\ + declarations = \"{prefix}/share/sudo-secretspec/secretspec.toml\"\n\ + service_user = \"{user}\"\n\ + service_group = \"{group}\"\n", + prefix = PREFIX, + vault = req.vault.display(), + vault_real = vault_real.display(), + user = req.service_user, + group = req.service_group, + ) +} + +fn sudoers_text(operator: &str) -> String { + format!( + "Defaults!{prefix}/libexec/sudo-secretspec env_reset,secure_path=/usr/bin:/bin:/usr/sbin:/sbin,umask=0077\n\ + {operator} ALL=(root) NOPASSWD: {prefix}/libexec/sudo-secretspec\n\ + {operator} ALL=(root) NOPASSWD: {prefix}/libexec/sudo-secretspec *\n", + prefix = PREFIX, + operator = operator, + ) +} + +fn retired_toml() -> &'static str { + "# RETIRED SECRETSPEC PATH — NO SECRET VALUES\n\ + # This path is not a credential store. Use /usr/local/bin/sudo-secretspec.\n\ + # Do not create, copy, symlink, regenerate, relocate, or select an alternate\n\ + # manifest or provider.\n" +} + +fn guidance_text() -> &'static str { + // Keep installer self-contained so packaging does not depend on relative + // source layout after cargo install. + "# AI and automation contract for sudo-secretspec\n\n\ + Use only /usr/local/bin/sudo-secretspec. Never select manifests, providers,\n\ + profiles, or backing files. Fail closed if the broker is unavailable.\n" +} + +/// Run the installer. Returns Ok(()) on success. +pub fn run(req: InstallRequest) -> Result<(), InstallError> { + require_root()?; + if !req.declarations.is_file() || req.declarations.is_symlink() { + return Err(InstallError::Denied( + "declarations must be a regular file".into(), + )); + } + validate_protected_ancestors()?; + + if req.dry_run { + if req.adopt_existing { + // Metadata-only validation of existing identity/vault. + let _ = Command::new("/usr/bin/id") + .arg(&req.service_user) + .status() + .map_err(|e| InstallError::Denied(e.to_string()))?; + if !req.vault.is_dir() || req.vault.is_symlink() { + return Err(InstallError::Denied( + "adopted vault missing or symlinked".into(), + )); + } + for runtime in ["secretspec.toml", ".env"] { + let p = req.vault.join(runtime); + if !p.is_file() || p.is_symlink() { + return Err(InstallError::Denied(format!( + "adopted runtime file missing or symlinked: {}", + p.display() + ))); + } + } + } else if Path::new(&req.vault).exists() + || Command::new("/usr/bin/id") + .arg(&req.service_user) + .status() + .map(|s| s.success()) + .unwrap_or(false) + { + return Err(InstallError::Denied( + "fresh-install identity or vault already exists; use --adopt-existing".into(), + )); + } + println!("would install sudo-secretspec"); + println!("operator={}", req.operator); + println!("service={}:{}", req.service_user, req.service_group); + println!("vault={}", req.vault.display()); + println!("prefix={PREFIX}"); + println!("adopt_existing={}", u8::from(req.adopt_existing)); + return Ok(()); + } + + // Create or adopt service identity. + let gid = ensure_service_group(&req.service_group, !req.adopt_existing)?; + ensure_service_user(&req.service_user, gid, !req.adopt_existing)?; + + // Vault. + let mut created_vault = false; + if !req.vault.exists() { + if req.adopt_existing { + return Err(InstallError::Denied("adopted vault missing".into())); + } + fs::create_dir_all(&req.vault)?; + created_vault = true; + } + if req.vault.is_symlink() { + return Err(InstallError::Denied("vault must not be a symlink".into())); + } + let _ = Command::new("/usr/sbin/chown") + .arg(format!("{}:{}", req.service_user, req.service_group)) + .arg(&req.vault) + .status(); + let mut perms = fs::metadata(&req.vault)?.permissions(); + perms.set_mode(0o700); + fs::set_permissions(&req.vault, perms)?; + + let vault_real = resolve_path(&req.vault); + if !vault_real.starts_with("/private/var/db/") { + return Err(InstallError::Denied( + "vault resolves outside /private/var/db".into(), + )); + } + + // Self binary sources. + let self_exe = std::env::current_exe() + .map_err(|e| InstallError::Denied(format!("cannot resolve current exe: {e}")))?; + let client_dst = PathBuf::from(PREFIX).join("bin/sudo-secretspec"); + let broker_dst = PathBuf::from(PREFIX).join("libexec/sudo-secretspec"); + let share = PathBuf::from(PREFIX).join("share/sudo-secretspec"); + let declarations_dst = share.join("secretspec.toml"); + let retired_dst = share.join("sudo-secretspec-retired.toml"); + let guidance_dst = share.join("AI-GUIDANCE.md"); + let manifest_dst = share.join("MANIFEST.sha256"); + let config_dst = PathBuf::from(CONFIG_PATH); + let sudoers_dst = PathBuf::from(SUDOERS_PATH); + + fs::create_dir_all(PathBuf::from(PREFIX).join("bin"))?; + fs::create_dir_all(PathBuf::from(PREFIX).join("libexec"))?; + fs::create_dir_all(PathBuf::from(PREFIX).join("etc"))?; + fs::create_dir_all(&share)?; + + install_file(&self_exe, &client_dst, 0o755)?; + install_file(&self_exe, &broker_dst, 0o755)?; + install_file(&req.declarations, &declarations_dst, 0o444)?; + write_bytes(&retired_dst, retired_toml().as_bytes(), 0o444)?; + write_bytes(&guidance_dst, guidance_text().as_bytes(), 0o444)?; + write_bytes( + &config_dst, + config_toml(&req, &vault_real).as_bytes(), + 0o444, + )?; + write_bytes(&sudoers_dst, sudoers_text(&req.operator).as_bytes(), 0o440)?; + + // Release manifest of installed artifacts. + let mut manifest = String::new(); + for path in [ + &client_dst, + &broker_dst, + &declarations_dst, + &retired_dst, + &guidance_dst, + &config_dst, + &sudoers_dst, + ] { + manifest.push_str(&format!("{} {}\n", sha256_file(path)?, path.display())); + } + write_bytes(&manifest_dst, manifest.as_bytes(), 0o444)?; + + // Validate sudoers. + let visudo = Command::new("/usr/sbin/visudo") + .args(["-c", "-f"]) + .arg(&sudoers_dst) + .status()?; + if !visudo.success() { + return Err(InstallError::Denied("visudo rejected sudoers".into())); + } + + // Runtime files for fresh install only. + if !req.adopt_existing { + let manifest_rt = req.vault.join("secretspec.toml"); + let env_rt = req.vault.join(".env"); + fs::copy(&declarations_dst, &manifest_rt)?; + fs::File::create(&env_rt)?; + for path in [&manifest_rt, &env_rt] { + let mut p = fs::metadata(path)?.permissions(); + p.set_mode(0o600); + fs::set_permissions(path, p)?; + let _ = Command::new("/usr/sbin/chown") + .arg(format!("{}:{}", req.service_user, req.service_group)) + .arg(path) + .status(); + } + } else { + for runtime in ["secretspec.toml", ".env"] { + let p = req.vault.join(runtime); + if !p.is_file() || p.is_symlink() { + return Err(InstallError::Denied(format!( + "adopted runtime file missing or symlinked: {}", + p.display() + ))); + } + } + } + + // Snapshot directory for future rollback of artifacts (not vault values). + let stamp = chrono_like_stamp(); + let rollback = PathBuf::from(PREFIX) + .join("libexec") + .join(format!("sudo-secretspec-rollback-{stamp}")); + fs::create_dir_all(&rollback)?; + let mut rp = fs::metadata(&rollback)?.permissions(); + rp.set_mode(0o700); + fs::set_permissions(&rollback, rp)?; + + println!("installed sudo-secretspec"); + println!("config={}", config_dst.display()); + println!("vault={}", req.vault.display()); + println!("rollback_snapshot={}", rollback.display()); + if created_vault { + println!("created_vault=1"); + } + Ok(()) +} + +fn chrono_like_stamp() -> String { + // UTC-ish timestamp without extra deps. + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + format!("{secs}") +} diff --git a/sudo-secretspec-cli/src/lib.rs b/sudo-secretspec-cli/src/lib.rs new file mode 100644 index 000000000..9b865f1d9 --- /dev/null +++ b/sudo-secretspec-cli/src/lib.rs @@ -0,0 +1,8 @@ +pub mod audit; +pub mod broker; +pub mod config; +pub mod drift; +pub mod install; +pub mod rollback; + +pub use drift::{Finding, Layout, Report, inspect, load_config}; diff --git a/sudo-secretspec-cli/src/main.rs b/sudo-secretspec-cli/src/main.rs new file mode 100644 index 000000000..9b48512f6 --- /dev/null +++ b/sudo-secretspec-cli/src/main.rs @@ -0,0 +1,335 @@ +use std::ffi::OsString; +use std::os::unix::process::CommandExt; +use std::path::PathBuf; +use std::process::Command; + +use clap::{Parser, Subcommand}; + +#[derive(Debug, Parser)] +#[command( + name = "sudo-secretspec", + version, + about = "Privilege-separated SecretSpec companion" +)] +struct Cli { + #[command(subcommand)] + cmd: Cmd, +} + +#[derive(Debug, Subcommand)] +enum Cmd { + Add { + name: String, + #[arg(long)] + reason: String, + }, + Set { + name: String, + #[arg(long)] + reason: String, + }, + Delete { + name: String, + #[arg(long)] + reason: String, + }, + Get { + name: String, + #[arg(long)] + reason: String, + }, + Check { + #[arg(long)] + reason: String, + }, + Export { + #[arg(long)] + reason: String, + }, + Run { + #[arg(long)] + reason: String, + #[arg(last = true, required = true)] + command: Vec, + }, + Install { + #[arg(long)] + declarations: PathBuf, + #[arg(long)] + dry_run: bool, + #[arg(long)] + adopt_existing: bool, + #[arg(long)] + vault: Option, + #[arg(long)] + service_user: Option, + #[arg(long)] + service_group: Option, + #[arg(long)] + operator: Option, + }, + Doctor { + #[arg(long)] + json: bool, + #[arg(long)] + config: Option, + }, + Rollback { + snapshot: PathBuf, + }, + #[command(hide = true, name = "__broker")] + Broker { + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + args: Vec, + }, +} + +fn main() { + let cli = Cli::parse(); + match cli.cmd { + Cmd::Add { name, reason } => lifecycle("add", &name, &reason), + Cmd::Set { name, reason } => lifecycle("set", &name, &reason), + Cmd::Delete { name, reason } => lifecycle("delete", &name, &reason), + Cmd::Get { name, reason } => lifecycle("get", &name, &reason), + Cmd::Check { reason } => lifecycle("check", "", &reason), + Cmd::Export { reason } => lifecycle("export", "", &reason), + Cmd::Run { reason, command } => run_target(&reason, &command), + Cmd::Install { + declarations, + dry_run, + adopt_existing, + vault, + service_user, + service_group, + operator, + } => { + let mut req = sudo_secretspec_cli::install::InstallRequest::from_cli( + declarations, + dry_run, + adopt_existing, + ); + if let Some(v) = vault { + req.vault = v; + } + if let Some(u) = service_user { + req.service_user = u; + } + if let Some(g) = service_group { + req.service_group = g; + } + if let Some(o) = operator { + req.operator = o; + } + // Install itself needs interactive sudo/Touch ID, not NOPASSWD -n. + if unsafe { libc::geteuid() } != 0 { + let status = Command::new("sudo") + .arg(self_exe()) + .arg("install") + .arg("--declarations") + .arg(&req.declarations) + .args(if req.dry_run { + vec!["--dry-run"] + } else { + vec![] + }) + .args(if req.adopt_existing { + vec!["--adopt-existing"] + } else { + vec![] + }) + .arg("--vault") + .arg(&req.vault) + .arg("--service-user") + .arg(&req.service_user) + .arg("--service-group") + .arg(&req.service_group) + .arg("--operator") + .arg(&req.operator) + .status(); + match status { + Ok(s) if s.success() => return, + Ok(s) => std::process::exit(s.code().unwrap_or(1)), + Err(e) => { + eprintln!("cannot elevate install: {e}"); + std::process::exit(2); + } + } + } + if let Err(e) = sudo_secretspec_cli::install::run(req) { + eprintln!("install denied: {e}"); + std::process::exit(2); + } + } + Cmd::Doctor { json, config } => doctor(json, config), + Cmd::Rollback { snapshot } => { + if unsafe { libc::geteuid() } != 0 { + let status = Command::new("sudo") + .arg(self_exe()) + .arg("rollback") + .arg(&snapshot) + .status(); + match status { + Ok(s) if s.success() => return, + Ok(s) => std::process::exit(s.code().unwrap_or(1)), + Err(e) => { + eprintln!("cannot elevate rollback: {e}"); + std::process::exit(2); + } + } + } + if let Err(e) = sudo_secretspec_cli::rollback::run(&snapshot) { + eprintln!("rollback denied: {e}"); + std::process::exit(2); + } + } + Cmd::Broker { args } => { + if let Err(code) = sudo_secretspec_cli::broker::dispatch(&args) { + std::process::exit(code); + } + } + } +} + +fn self_exe() -> PathBuf { + std::env::current_exe().unwrap_or_else(|_| PathBuf::from("sudo-secretspec")) +} + +fn privileged_broker() -> PathBuf { + let candidate = PathBuf::from("/usr/local/libexec/sudo-secretspec"); + if candidate.is_file() { + candidate + } else { + self_exe() + } +} + +fn lifecycle(op: &str, name: &str, reason: &str) { + let mut cmd = Command::new("sudo"); + cmd.arg("-n") + .arg(privileged_broker()) + .arg("__broker") + .arg(format!("source-{op}")) + .arg("--client") + .arg(detect_client()) + .arg("--reason") + .arg(reason); + if !name.is_empty() { + cmd.arg("--name").arg(name); + } + let status = cmd.status().unwrap_or_else(|e| { + eprintln!("cannot invoke broker: {e}"); + std::process::exit(2); + }); + if !status.success() { + std::process::exit(status.code().unwrap_or(1)); + } +} + +fn detect_client() -> &'static str { + for (key, family) in [ + ("HERMES_SESSION_ID", "hermes"), + ("CLAUDE_SESSION_ID", "claude"), + ("CODEX_THREAD_ID", "codex"), + ("OPENCODE_SESSION_ID", "opencode"), + ("CURSOR_SESSION_ID", "cursor"), + ("AGY_SESSION_ID", "agy"), + ] { + if std::env::var_os(key).is_some() { + return family; + } + } + "unknown" +} + +fn run_target(reason: &str, command: &[OsString]) { + let sep = command + .iter() + .position(|a| a == "--") + .unwrap_or(command.len()); + let (pre, target) = command.split_at(sep); + let target = if target.is_empty() { pre } else { &target[1..] }; + if target.is_empty() { + eprintln!("run requires a command after --"); + std::process::exit(2); + } + + let output = Command::new("sudo") + .arg("-n") + .arg(privileged_broker()) + .arg("__broker") + .arg("source-export") + .arg("--client") + .arg(detect_client()) + .arg("--reason") + .arg(reason) + .arg("--command-basename") + .arg(target[0].to_str().unwrap_or("unknown")) + .output() + .unwrap_or_else(|e| { + eprintln!("cannot invoke broker: {e}"); + std::process::exit(2); + }); + + if !output.status.success() { + eprint!("{}", String::from_utf8_lossy(&output.stderr)); + std::process::exit(output.status.code().unwrap_or(1)); + } + + let env: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| { + eprintln!("broker returned invalid JSON: {e}"); + std::process::exit(2); + }); + + let mut cmd = Command::new(&target[0]); + cmd.args(&target[1..]); + for (key, _) in std::env::vars() { + if key.starts_with("SECRETSPEC_") { + cmd.env_remove(&key); + } + } + if let Some(obj) = env.as_object() { + for (key, value) in obj { + if let Some(v) = value.as_str() { + cmd.env(key, v); + } + } + } + + let err = cmd.exec(); + eprintln!("cannot exec target: {err}"); + std::process::exit(127); +} + +fn doctor(json: bool, config: Option) { + let config = config.unwrap_or_else(|| PathBuf::from("/usr/local/etc/sudo-secretspec.toml")); + let layout = match sudo_secretspec_cli::load_config(&config) { + Ok(l) => l, + Err(e) => { + if json { + println!( + "{}", + serde_json::json!({"ok": false, "error": format!("{e}")}) + ); + } else { + eprintln!("doctor: config error: {e}"); + } + std::process::exit(1); + } + }; + + let report = sudo_secretspec_cli::inspect(&layout); + if json { + println!("{}", serde_json::to_string_pretty(&report).unwrap()); + } else if report.ok { + println!("doctor: OK"); + } else { + eprintln!("doctor: FAILED"); + for finding in &report.findings { + match &finding.path { + Some(path) => eprintln!("- {} ({}): {}", finding.code, path, finding.detail), + None => eprintln!("- {}: {}", finding.code, finding.detail), + } + } + std::process::exit(1); + } +} diff --git a/sudo-secretspec-cli/src/rollback.rs b/sudo-secretspec-cli/src/rollback.rs new file mode 100644 index 000000000..ce4d65b58 --- /dev/null +++ b/sudo-secretspec-cli/src/rollback.rs @@ -0,0 +1,118 @@ +//! Artifact rollback for sudo-secretspec privileged installs. +//! +//! Restores previous installed binaries/config/sudoers from a protected +//! snapshot directory. Never touches vault secret values. + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum RollbackError { + #[error("{0}")] + Denied(String), + #[error("io: {0}")] + Io(#[from] std::io::Error), +} + +fn require_root() -> Result<(), RollbackError> { + if unsafe { libc::geteuid() } != 0 { + return Err(RollbackError::Denied("rollback requires root".into())); + } + Ok(()) +} + +/// Restore installed artifacts from a protected snapshot directory. +/// +/// Expected layout: +/// - `MANIFEST.sha256` listing `hash absolute-path` rows for prior artifacts +/// - optional numbered backups or direct prior file copies named by sha path basenames +/// +/// Current installer creates snapshot dirs as placeholders; a complete snapshot +/// writer can store prior bytes beside the manifest. This restore verifies the +/// snapshot directory metadata and reapplies any `*.prior` files found as: +/// `.prior` + `.path` containing the destination absolute path. +pub fn run(snapshot: &Path) -> Result<(), RollbackError> { + require_root()?; + let snapshot = fs::canonicalize(snapshot) + .map_err(|e| RollbackError::Denied(format!("invalid snapshot path: {e}")))?; + let prefix = PathBuf::from("/usr/local/libexec/sudo-secretspec-rollback-"); + if !snapshot + .to_string_lossy() + .starts_with(prefix.to_string_lossy().as_ref()) + { + return Err(RollbackError::Denied( + "rollback snapshot is outside the protected rollback directory".into(), + )); + } + if snapshot.is_symlink() { + return Err(RollbackError::Denied( + "snapshot must not be a symlink".into(), + )); + } + let meta = fs::metadata(&snapshot)?; + if meta.permissions().mode() & 0o777 != 0o700 { + return Err(RollbackError::Denied( + "snapshot directory mode must be 0700".into(), + )); + } + + // Prefer an explicit restore program if the snapshot contains one. + let restore_bin = snapshot.join("restore"); + if restore_bin.is_file() { + let status = Command::new(&restore_bin).status()?; + if status.success() { + println!("sudo-secretspec artifacts restored; runtime vault preserved"); + return Ok(()); + } + return Err(RollbackError::Denied( + "snapshot restore program failed".into(), + )); + } + + // Generic path-pair restore: N.path + N.prior + let mut pairs = Vec::new(); + for entry in fs::read_dir(&snapshot)? { + let entry = entry?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + if let Some(idx) = name.strip_suffix(".path") { + let prior = snapshot.join(format!("{idx}.prior")); + if prior.is_file() { + let dest = PathBuf::from(fs::read_to_string(entry.path())?.trim()); + pairs.push((prior, dest)); + } + } + } + if pairs.is_empty() { + return Err(RollbackError::Denied( + "snapshot contains no restorable prior artifacts".into(), + )); + } + + for (prior, dest) in pairs.iter().rev() { + if let Some(parent) = dest.parent() { + fs::create_dir_all(parent)?; + } + let tmp = dest.with_extension(format!("restore.{}", std::process::id())); + fs::copy(prior, &tmp)?; + fs::rename(&tmp, dest)?; + } + + if Path::new("/private/etc/sudoers.d/sudo-secretspec").exists() { + let status = Command::new("/usr/sbin/visudo") + .args(["-c", "-f", "/private/etc/sudoers.d/sudo-secretspec"]) + .status()?; + if !status.success() { + return Err(RollbackError::Denied( + "restored sudoers failed visudo validation".into(), + )); + } + } + + println!("sudo-secretspec artifacts restored; runtime vault preserved"); + Ok(()) +} diff --git a/sudo-secretspec-cli/tests/audit.rs b/sudo-secretspec-cli/tests/audit.rs new file mode 100644 index 000000000..711ce836e --- /dev/null +++ b/sudo-secretspec-cli/tests/audit.rs @@ -0,0 +1,597 @@ +//! Integration tests for the sudo-secretspec audit ledger. +//! +//! These tests verify the fail-closed transactional SQLite audit module: +//! hash-chained events, atomic event+head updates, protected metadata checks, +//! value-free storage (no secrets, reasons, or argv), and chain verification. + +use std::fs; +use std::os::unix::fs::PermissionsExt; + +use sudo_secretspec_cli::audit::{self, AuditError, ClientFamily, Outcome}; + +/// Create a protected directory (mode 0700) under tmp_path. +fn protected_dir(tmp: &std::path::Path) -> std::path::PathBuf { + let dir = tmp.join("protected"); + fs::create_dir(&dir).unwrap(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); + dir +} + +/// Helper to append an attempt event and return the event. +fn append_attempt(dir: &std::path::Path, tx: uuid::Uuid) -> Result { + audit::append_event( + dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: tx, + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"rotate integration credential")), + command_basename: Some("curl".into()), + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ) +} + +/// Helper to append a terminal event (success/failure/unknown). +fn append_terminal( + dir: &std::path::Path, + tx: uuid::Uuid, + phase: Outcome, + result_code: u8, +) -> Result { + audit::append_event( + dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase, + transaction: tx, + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"rotate integration credential")), + command_basename: Some("curl".into()), + names: vec!["EXAMPLE_KEY".into()], + result_code: Some(result_code), + expected_uid: Some(unsafe { libc::getuid() }), + }, + ) +} + +// --------------------------------------------------------------------------- +// RED-1: attempt + success are transactional and value-free +// --------------------------------------------------------------------------- +#[test] +fn test_attempt_and_success_are_transactional_and_value_free() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let tx = uuid::Uuid::new_v4(); + + let first = append_attempt(&dir, tx).expect("attempt should succeed"); + let second = append_terminal(&dir, tx, Outcome::Success, 0).expect("success should succeed"); + + // Verify chain linking + assert_eq!(first.client, ClientFamily::Hermes); + assert_eq!(second.previous_hash, first.event_hash); + + // Verify value-free: no reason text, no session, no credential in raw file + let raw = fs::read(dir.join("broker-audit.sqlite3")).unwrap(); + assert!(!window_sensitive("rotate integration credential", &raw)); + assert!(!window_sensitive("hermes:topic", &raw)); + assert!(!window_sensitive("Authorization: ***", &raw)); + // Names are expected in the DB + assert!(window_sensitive("EXAMPLE_KEY", &raw)); + + // Verify file permissions + let meta = fs::metadata(dir.join("broker-audit.sqlite3")).unwrap(); + assert_eq!(meta.permissions().mode() & 0o777, 0o600); + + // Verify chain + let result = + audit::verify(&dir, Some(unsafe { libc::getuid() })).expect("verify should succeed"); + assert_eq!(result.count, 2); + assert_eq!(result.hash, second.event_hash); +} + +// --------------------------------------------------------------------------- +// RED-2: unknown outcome is a distinct terminal phase +// --------------------------------------------------------------------------- +#[test] +fn test_unknown_outcome_is_a_distinct_terminal_phase() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let tx = uuid::Uuid::new_v4(); + + append_attempt(&dir, tx).unwrap(); + let unknown = append_terminal(&dir, tx, Outcome::Unknown, 125).expect("unknown should succeed"); + assert_eq!(unknown.phase, Outcome::Unknown); + assert_eq!(unknown.result_code, Some(125)); + + let result = audit::verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 2); +} + +// --------------------------------------------------------------------------- +// RED-3: free-form reason and command arguments never persist +// --------------------------------------------------------------------------- +#[test] +fn test_free_form_reason_and_command_arguments_never_persist() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + let secretish = "Authorization: Bearer ***"; + let reason_hash = audit::sha256_hex(secretish.as_bytes()); + + audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(reason_hash), + command_basename: Some("curl".into()), + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ) + .unwrap(); + + let raw = fs::read(dir.join("broker-audit.sqlite3")).unwrap(); + // Reason text must not appear + assert!(!window_sensitive(secretish, &raw)); + assert!(!window_sensitive("credential-value", &raw)); + // Basename should appear + assert!(window_sensitive("curl", &raw)); +} + +// --------------------------------------------------------------------------- +// RED-4: interrupted attempt remains visible +// --------------------------------------------------------------------------- +#[test] +fn test_interrupted_attempt_remains_visible() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + append_attempt(&dir, uuid::Uuid::new_v4()).unwrap(); + + let result = audit::verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 1); +} + +// --------------------------------------------------------------------------- +// RED-5: bad metadata fails before creating ledger +// --------------------------------------------------------------------------- +#[test] +fn test_bad_metadata_fails_before_creating_ledger() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Invalid secret name + let result = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"test")), + command_basename: None, + names: vec!["BAD-NAME".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(result.is_err()); + let db = dir.join("broker-audit.sqlite3"); + assert!(!db.exists(), "ledger should not be created on bad metadata"); + + // Invalid command basename with newline + let result = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"test")), + command_basename: Some("bad\ncommand".into()), + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(result.is_err()); + + // Invalid client family + let result = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + // This one should succeed since Hermes is a valid client + assert!(result.is_ok()); +} + +// --------------------------------------------------------------------------- +// RED-6: symlink ledger is rejected without touching target +// --------------------------------------------------------------------------- +#[test] +fn test_symlink_ledger_is_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + let target = tmp.path().join("target"); + fs::write(&target, "unchanged").unwrap(); + + std::os::unix::fs::symlink(&target, dir.join("broker-audit.sqlite3")).unwrap(); + + let result = append_attempt(&dir, uuid::Uuid::new_v4()); + assert!(result.is_err(), "should reject symlink ledger"); + + assert_eq!(fs::read_to_string(&target).unwrap(), "unchanged"); +} + +// --------------------------------------------------------------------------- +// RED-7: wrong directory or ledger mode is rejected +// --------------------------------------------------------------------------- +#[test] +fn test_wrong_directory_mode_is_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Weaken directory permissions + fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); + let result = append_attempt(&dir, uuid::Uuid::new_v4()); + assert!(result.is_err(), "should reject 0755 directory"); +} + +#[test] +fn test_wrong_ledger_mode_is_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Create ledger with wrong permissions + let ledger = dir.join("broker-audit.sqlite3"); + { + let conn = rusqlite::Connection::open(&ledger).unwrap(); + conn.execute_batch( + "CREATE TABLE t(x); PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL;", + ) + .unwrap(); + } + fs::set_permissions(&ledger, fs::Permissions::from_mode(0o644)).unwrap(); + + let result = append_attempt(&dir, uuid::Uuid::new_v4()); + assert!(result.is_err(), "should reject 0644 ledger"); +} + +// --------------------------------------------------------------------------- +// RED-8: terminal event requires result code; attempt must not have one +// --------------------------------------------------------------------------- +#[test] +fn test_terminal_event_requires_result_code() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Failure phase without result code should fail + let result = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Failure, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(result.is_err(), "terminal event needs result code"); + + // Attempt phase with result code should fail + let result = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: Some(1), + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(result.is_err(), "attempt must not have result code"); +} + +// --------------------------------------------------------------------------- +// RED-9: chain verification detects database tampering +// --------------------------------------------------------------------------- +#[test] +fn test_chain_verification_detects_tampering() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + append_attempt(&dir, uuid::Uuid::new_v4()).unwrap(); + + // Tamper with the database directly + let conn = rusqlite::Connection::open(dir.join("broker-audit.sqlite3")).unwrap(); + conn.execute( + "UPDATE events SET operation='source-get' WHERE sequence=1", + [], + ) + .unwrap(); + + let result = audit::verify(&dir, Some(unsafe { libc::getuid() })); + assert!(result.is_err(), "should detect tampering"); +} + +// --------------------------------------------------------------------------- +// RED-10: event and head rollback together on head failure (atomicity) +// --------------------------------------------------------------------------- +#[test] +fn test_event_and_head_rollback_together() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + let tx = uuid::Uuid::new_v4(); + + append_attempt(&dir, tx).unwrap(); + + // Inject a trigger that rejects head updates + let conn = rusqlite::Connection::open(dir.join("broker-audit.sqlite3")).unwrap(); + conn.execute_batch( + "CREATE TRIGGER reject_head BEFORE UPDATE ON head BEGIN SELECT RAISE(ABORT, 'fault injection'); END;" + ).unwrap(); + + let result = append_terminal(&dir, tx, Outcome::Success, 0); + assert!(result.is_err(), "should fail when head update rejected"); + + // Verify only the attempt remains (no orphaned success event) + let result = audit::verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 1, "only attempt should remain after rollback"); +} + +// --------------------------------------------------------------------------- +// RED-11: verify on empty/absent ledger succeeds with count=0 +// --------------------------------------------------------------------------- +#[test] +fn test_verify_empty_ledger() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // No ledger exists yet — verify should succeed with count=0 + let result = audit::verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 0); + assert_eq!(result.hash, audit::ZERO_HASH); +} + +// --------------------------------------------------------------------------- +// RED-12: reason SHA-256 validation +// --------------------------------------------------------------------------- +#[test] +fn test_reason_sha256_must_be_valid_hex() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Invalid hex + let result = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some("not-a-valid-sha256-hash".into()), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(result.is_err(), "should reject invalid reason hash"); + + // Missing reason entirely + let result = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: None, + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(result.is_err(), "should reject missing reason hash"); +} + +// --------------------------------------------------------------------------- +// RED-13: operation must match pattern +// --------------------------------------------------------------------------- +#[test] +fn test_operation_validation() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + let result = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "INVALID".into(), // must be lowercase + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(result.is_err()); +} + +// --------------------------------------------------------------------------- +// RED-14: transaction UUID validation +// --------------------------------------------------------------------------- +#[test] +fn test_transaction_uuid_required() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // All-nil UUID should still be accepted + let nil = uuid::Uuid::nil(); + let result = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: nil, + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"test")), + command_basename: None, + names: vec!["EXAMPLE_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ); + assert!(result.is_ok(), "nil UUID should be accepted"); +} + +// --------------------------------------------------------------------------- +// RED-15: names are sorted and validated +// --------------------------------------------------------------------------- +#[test] +fn test_names_are_sorted_and_validated() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + let event = audit::append_event( + &dir, + audit::AppendEventRequest { + operation: "source-set".into(), + phase: Outcome::Attempt, + transaction: uuid::Uuid::new_v4(), + actor: "djbclark".into(), + client: ClientFamily::Hermes, + reason_sha256: Some(audit::sha256_hex(b"test")), + command_basename: None, + names: vec!["Z_KEY".into(), "A_KEY".into()], + result_code: None, + expected_uid: Some(unsafe { libc::getuid() }), + }, + ) + .unwrap(); + + // Names should be sorted + assert_eq!(event.names, vec!["A_KEY", "Z_KEY"]); +} + +// --------------------------------------------------------------------------- +// RED-16: owner mismatch is rejected +// --------------------------------------------------------------------------- +#[test] +fn test_owner_mismatch_is_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Create ledger owned by us + append_attempt(&dir, uuid::Uuid::new_v4()).unwrap(); + + // Verify with wrong UID (1 is typically not the current user) + let wrong_uid = if unsafe { libc::getuid() } == 0 { 1 } else { 0 }; + let result = audit::verify(&dir, Some(wrong_uid)); + + // If we're running as root, this might not fail in all cases. + // But if we're not root, it should fail with owner mismatch. + if unsafe { libc::getuid() } != 0 { + assert!(result.is_err(), "should reject owner mismatch"); + } +} + +// --------------------------------------------------------------------------- +// RED-17: chain with multiple transactions validates correctly +// --------------------------------------------------------------------------- +#[test] +fn test_multiple_transactions_chain_correctly() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + // Transaction 1: attempt + success + let tx1 = uuid::Uuid::new_v4(); + let e1 = append_attempt(&dir, tx1).unwrap(); + let e2 = append_terminal(&dir, tx1, Outcome::Success, 0).unwrap(); + assert_eq!(e2.previous_hash, e1.event_hash); + + // Transaction 2: attempt + failure + let tx2 = uuid::Uuid::new_v4(); + let e3 = append_attempt(&dir, tx2).unwrap(); + assert_eq!(e3.previous_hash, e2.event_hash); + let e4 = append_terminal(&dir, tx2, Outcome::Failure, 1).unwrap(); + assert_eq!(e4.previous_hash, e3.event_hash); + + // Transaction 3: standalone unknown + let tx3 = uuid::Uuid::new_v4(); + let e5 = append_attempt(&dir, tx3).unwrap(); + assert_eq!(e5.previous_hash, e4.event_hash); + let e6 = append_terminal(&dir, tx3, Outcome::Unknown, 127).unwrap(); + assert_eq!(e6.previous_hash, e5.event_hash); + + let result = audit::verify(&dir, Some(unsafe { libc::getuid() })).unwrap(); + assert_eq!(result.count, 6); + assert_eq!(result.hash, e6.event_hash); +} + +// --------------------------------------------------------------------------- +// RED-18: SQLite integrity check on verify +// --------------------------------------------------------------------------- +#[test] +fn test_sqlite_integrity_check_on_verify() { + let tmp = tempfile::tempdir().unwrap(); + let dir = protected_dir(tmp.path()); + + append_attempt(&dir, uuid::Uuid::new_v4()).unwrap(); + let result = audit::verify(&dir, Some(unsafe { libc::getuid() })); + assert!(result.is_ok(), "verify should pass with clean database"); +} + +// --------------------------------------------------------------------------- +// helpers +// --------------------------------------------------------------------------- + +/// A sliding-window substring check that avoids false negatives when SQLite +/// splits bytes across page boundaries. +fn window_sensitive(needle: &str, haystack: &[u8]) -> bool { + haystack + .windows(needle.len()) + .any(|w| w == needle.as_bytes()) +} diff --git a/sudo-secretspec-cli/tests/cli.rs b/sudo-secretspec-cli/tests/cli.rs new file mode 100644 index 000000000..c4df5fdb7 --- /dev/null +++ b/sudo-secretspec-cli/tests/cli.rs @@ -0,0 +1,44 @@ +use std::process::Command; + +fn binary() -> Command { + Command::new(env!("CARGO_BIN_EXE_sudo-secretspec")) +} + +#[test] +fn version_identifies_downstream_distribution() { + let output = binary() + .arg("--version") + .output() + .expect("run sudo-secretspec"); + assert!(output.status.success()); + assert_eq!( + String::from_utf8(output.stdout).unwrap().trim(), + "sudo-secretspec 0.19.1-djbclark.1" + ); +} + +#[test] +fn public_cli_rejects_control_plane_overrides() { + for option in ["--file", "--provider", "--profile", "--direct"] { + let output = binary() + .args([option, "untrusted", "check"]) + .output() + .expect("run sudo-secretspec"); + assert!(!output.status.success(), "accepted {option}"); + } +} + +#[test] +fn help_exposes_typed_boundary_commands() { + let output = binary() + .arg("--help") + .output() + .expect("run sudo-secretspec"); + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + for command in [ + "get", "set", "add", "delete", "check", "export", "run", "install", "doctor", "rollback", + ] { + assert!(stdout.contains(command), "missing {command}"); + } +} diff --git a/sudo-secretspec-cli/tests/config.rs b/sudo-secretspec-cli/tests/config.rs new file mode 100644 index 000000000..580abd513 --- /dev/null +++ b/sudo-secretspec-cli/tests/config.rs @@ -0,0 +1,49 @@ +use std::path::Path; + +use sudo_secretspec_cli::config::Config; + +fn valid() -> &'static str { + r#" +engine = "/usr/local/libexec/sudo-secretspec-engine" +audit_helper = "/usr/local/libexec/sudo-secretspec" +vault = "/var/db/sudo-secretspec" +vault_realpath = "/private/var/db/sudo-secretspec" +declarations = "/usr/local/share/sudo-secretspec/secretspec.toml" +service_user = "_sudo_secretspec" +service_group = "_sudo_secretspec" +"# +} + +#[test] +fn parses_typed_toml_without_shell_evaluation() { + let config = Config::parse(valid()).unwrap(); + assert_eq!(config.vault(), Path::new("/var/db/sudo-secretspec")); + assert_eq!(config.service_user(), "_sudo_secretspec"); +} + +#[test] +fn rejects_unknown_keys_and_noncanonical_vaults() { + let unknown = format!("{}\ncommand = \"touch /tmp/pwned\"\n", valid()); + assert!(Config::parse(&unknown).is_err()); + + let nested = valid().replace( + "vault = \"/var/db/sudo-secretspec\"", + "vault = \"/var/db/team/sudo-secretspec\"", + ); + assert!(Config::parse(&nested).is_err()); + + let mismatched = valid().replace("/private/var/db/sudo-secretspec", "/private/var/db/other"); + assert!(Config::parse(&mismatched).is_err()); +} + +#[test] +fn rejects_invalid_service_identity_and_relative_paths() { + assert!(Config::parse(&valid().replace("_sudo_secretspec", "root")).is_err()); + assert!( + Config::parse(&valid().replace( + "/usr/local/libexec/sudo-secretspec-engine", + "./secretspec-engine", + )) + .is_err() + ); +} diff --git a/sudo-secretspec-cli/tests/drift.rs b/sudo-secretspec-cli/tests/drift.rs new file mode 100644 index 000000000..7954a5d77 --- /dev/null +++ b/sudo-secretspec-cli/tests/drift.rs @@ -0,0 +1,175 @@ +/// Drift-check contract parsing tests using typed TOML configuration. +use std::path::PathBuf; +use tempfile::TempDir; + +fn write_config(dir: &TempDir, content: &str) -> PathBuf { + let path = dir.path().join("sudo-secretspec.toml"); + std::fs::write(&path, content).unwrap(); + path +} + +fn minimal_toml() -> &'static str { + r#" +engine = "/usr/local/libexec/sudo-secretspec" +audit_helper = "/usr/local/libexec/sudo-secretspec" +vault = "/var/db/sudo-secretspec" +vault_realpath = "/private/var/db/sudo-secretspec" +declarations = "/usr/local/share/sudo-secretspec/secretspec.toml" +service_user = "_sudo_secretspec" +service_group = "_sudo_secretspec" +"# +} + +#[test] +fn layout_derives_single_binary_paths() { + let dir = TempDir::new().unwrap(); + let path = write_config(&dir, minimal_toml()); + let layout = sudo_secretspec_cli::load_config(&path).unwrap(); + + assert_eq!( + layout.engine, + PathBuf::from("/usr/local/libexec/sudo-secretspec") + ); + assert_eq!( + layout.broker, + PathBuf::from("/usr/local/libexec/sudo-secretspec") + ); + assert_eq!( + layout.client, + PathBuf::from("/usr/local/bin/sudo-secretspec") + ); + assert_eq!( + layout.checker, + PathBuf::from("/usr/local/bin/sudo-secretspec") + ); + assert_eq!( + layout.retired, + PathBuf::from("/usr/local/share/sudo-secretspec/sudo-secretspec-retired.toml") + ); + assert_eq!( + layout.guidance, + PathBuf::from("/usr/local/share/sudo-secretspec/AI-GUIDANCE.md") + ); + assert_eq!( + layout.source_manifest, + PathBuf::from("/usr/local/share/sudo-secretspec/MANIFEST.sha256") + ); +} + +#[test] +fn layout_holds_all_config_values() { + let dir = TempDir::new().unwrap(); + let path = write_config(&dir, minimal_toml()); + let layout = sudo_secretspec_cli::load_config(&path).unwrap(); + + assert_eq!(layout.config, path); + assert_eq!(layout.vault, PathBuf::from("/var/db/sudo-secretspec")); + assert_eq!( + layout.vault_realpath, + PathBuf::from("/private/var/db/sudo-secretspec") + ); + assert_eq!(layout.service_user, "_sudo_secretspec"); + assert_eq!(layout.service_group, "_sudo_secretspec"); + assert_eq!( + layout.declarations, + PathBuf::from("/usr/local/share/sudo-secretspec/secretspec.toml") + ); + assert_eq!( + layout.audit, + PathBuf::from("/usr/local/libexec/sudo-secretspec") + ); +} + +#[test] +fn config_rejects_unknown_keys() { + let dir = TempDir::new().unwrap(); + let bad = format!("{}\nextra = \"nope\"\n", minimal_toml()); + let path = write_config(&dir, &bad); + assert!(sudo_secretspec_cli::load_config(&path).is_err()); +} + +#[test] +fn config_rejects_missing_keys() { + let dir = TempDir::new().unwrap(); + let path = write_config( + &dir, + r#" +engine = "/usr/local/libexec/sudo-secretspec" +"#, + ); + assert!(sudo_secretspec_cli::load_config(&path).is_err()); +} + +#[test] +fn config_rejects_relative_paths() { + let dir = TempDir::new().unwrap(); + let path = write_config( + &dir, + r#" +engine = "relative/path" +audit_helper = "/usr/local/libexec/sudo-secretspec" +vault = "/var/db/sudo-secretspec" +vault_realpath = "/private/var/db/sudo-secretspec" +declarations = "/usr/local/share/sudo-secretspec/secretspec.toml" +service_user = "_sudo_secretspec" +service_group = "_sudo_secretspec" +"#, + ); + assert!(sudo_secretspec_cli::load_config(&path).is_err()); +} + +#[test] +fn config_rejects_parent_traversal_in_paths() { + let dir = TempDir::new().unwrap(); + let path = write_config( + &dir, + r#" +engine = "/usr/local/libexec/../etc/passwd" +audit_helper = "/usr/local/libexec/sudo-secretspec" +vault = "/var/db/sudo-secretspec" +vault_realpath = "/private/var/db/sudo-secretspec" +declarations = "/usr/local/share/sudo-secretspec/secretspec.toml" +service_user = "_sudo_secretspec" +service_group = "_sudo_secretspec" +"#, + ); + assert!(sudo_secretspec_cli::load_config(&path).is_err()); +} + +#[test] +fn config_rejects_invalid_service_user() { + let dir = TempDir::new().unwrap(); + let path = write_config( + &dir, + r#" +engine = "/usr/local/libexec/sudo-secretspec" +audit_helper = "/usr/local/libexec/sudo-secretspec" +vault = "/var/db/sudo-secretspec" +vault_realpath = "/private/var/db/sudo-secretspec" +declarations = "/usr/local/share/sudo-secretspec/secretspec.toml" +service_user = "root" +service_group = "_sudo_secretspec" +"#, + ); + assert!(sudo_secretspec_cli::load_config(&path).is_err()); +} + +#[test] +fn config_handles_comments_and_empty_lines() { + let dir = TempDir::new().unwrap(); + let path = write_config( + &dir, + r#" +# comment + +engine = "/usr/local/libexec/sudo-secretspec" +audit_helper = "/usr/local/libexec/sudo-secretspec" +vault = "/var/db/sudo-secretspec" +vault_realpath = "/private/var/db/sudo-secretspec" +declarations = "/usr/local/share/sudo-secretspec/secretspec.toml" +service_user = "_sudo_secretspec" +service_group = "_sudo_secretspec" +"#, + ); + assert!(sudo_secretspec_cli::load_config(&path).is_ok()); +} diff --git a/sudo-secretspec-cli/tests/install_rollback.rs b/sudo-secretspec-cli/tests/install_rollback.rs new file mode 100644 index 000000000..209f29598 --- /dev/null +++ b/sudo-secretspec-cli/tests/install_rollback.rs @@ -0,0 +1,24 @@ +use std::path::PathBuf; + +use sudo_secretspec_cli::install::InstallRequest; + +#[test] +fn install_request_defaults_are_generic() { + let req = InstallRequest::from_cli(PathBuf::from("/tmp/decl.toml"), true, false); + assert_eq!(req.vault, PathBuf::from("/var/db/sudo-secretspec")); + assert_eq!(req.service_user, "_sudo_secretspec"); + assert_eq!(req.service_group, "_sudo_secretspec"); + assert!(req.dry_run); + assert!(!req.adopt_existing); +} + +#[test] +fn rollback_rejects_unprotected_snapshot_path() { + let err = sudo_secretspec_cli::rollback::run(std::path::Path::new("/tmp/not-a-snapshot")) + .expect_err("unprotected snapshot must fail"); + let msg = err.to_string(); + assert!( + msg.contains("root") || msg.contains("outside") || msg.contains("invalid"), + "{msg}" + ); +} diff --git a/sudo-secretspec/AI-GUIDANCE.md b/sudo-secretspec/AI-GUIDANCE.md new file mode 100644 index 000000000..fd149ccf1 --- /dev/null +++ b/sudo-secretspec/AI-GUIDANCE.md @@ -0,0 +1,50 @@ +# AI and automation contract for sudo-secretspec + +Use this policy in `AGENTS.md`, skills, runbooks, and autonomous-agent prompts for deployments of sudo-secretspec. + +## Required behavior + +- Use only the installed `/usr/local/bin/sudo-secretspec` client for credential CRUD and use. +- Supply a short operational `--reason` for every `add`, `set`, `delete`, `get`, `check`, `export`, or `run` operation. The protected audit ledger stores only its SHA-256 digest. +- Run a consumer as `sudo-secretspec run --reason "purpose" -- ` instead of extracting values into shell history or command arguments. +- Treat an unavailable broker, failed audit append/verification, declaration mismatch, authorization failure, or drift finding as a hard stop. +- Report only the non-secret error and request operator action for boundary installation or repair. +- Normal broker-mediated credential operations are autonomous when the installed sudoers policy allows them. + +## Forbidden behavior + +Never: + +- invoke `secretspec` directly for a managed deployment; +- select or create another manifest, provider, profile, binary, dotenv file, or credential store; +- set `SECRETSPEC_FILE`, `SECRETSPEC_PROVIDER`, `SECRETSPEC_PROFILE`, or a direct-mode bypass; +- read, write, copy, symlink, regenerate, relocate, chmod, chown, rename, unlink, or repair protected backing files; +- weaken permissions or ACLs to inspect the store; +- place secret values in reasons, logs, audit metadata, command arguments, issue text, commits, tests, or documentation; +- treat inability to stat a `0700` store as evidence that files are absent; +- use a watchdog or drift check to mutate or repair state. + +## Declaration lifecycle + +Tracked Git content contains declarations only. A new name must first be reviewed and released in the declaration file. After installation/deployment pins that release, `sudo-secretspec add NAME --reason "purpose"` may create its value. Remove a declaration through review/release before `delete` removes its value. The broker rolls manifest/value mutations back on failure and records an explicit `unknown` terminal state if restoration cannot be proven. + +## Security scope + +The public client may export the full declared environment to a requested child process; this is intentional for a deployment where every authorized local AI/user may use every managed credential. The boundary provides integrity, singular control-plane enforcement, least-privilege backing-file access, and value-free audit—not per-secret confidentiality among callers sharing the authorized operator identity. + +Client-family labels are correlation metadata, not authenticated principals. Deployments requiring per-agent or per-secret authorization need a stronger principal model and policy layer rather than trusting environment markers. + +## Verification + +Use: + +```bash +sudo-secretspec doctor +sudo-secretspec install --dry-run +``` + +The dry-run still uses `sudo` because protected metadata cannot be validated honestly from the operator UID. It never reads secret contents. Rollback snapshots cover installed artifacts only and deliberately preserve the runtime vault: + +```bash +sudo-secretspec rollback /usr/local/libexec/sudo-secretspec-rollback- +``` diff --git a/sudo-secretspec/share/sudo-secretspec-retired.toml b/sudo-secretspec/share/sudo-secretspec-retired.toml new file mode 100644 index 000000000..79702d164 --- /dev/null +++ b/sudo-secretspec/share/sudo-secretspec-retired.toml @@ -0,0 +1,6 @@ +# RETIRED SECRETSPEC PATH — NO SECRET VALUES +# This path is not a credential store. Use /usr/local/bin/sudo-secretspec. +# The protected runtime store is configured in /usr/local/etc/sudo-secretspec.conf. +# If the managed broker is unavailable, stop and report the non-secret error. +# Do not create, copy, symlink, regenerate, relocate, or select an alternate +# manifest or provider. diff --git a/sudo-secretspec/share/sudo-secretspec.conf.example b/sudo-secretspec/share/sudo-secretspec.conf.example new file mode 100644 index 000000000..8cae544e0 --- /dev/null +++ b/sudo-secretspec/share/sudo-secretspec.conf.example @@ -0,0 +1,9 @@ +# sudo-secretspec protected configuration example (no secret values). +# Installed protected copy: /usr/local/etc/sudo-secretspec.toml +engine = "/usr/local/libexec/sudo-secretspec" +audit_helper = "/usr/local/libexec/sudo-secretspec" +vault = "/var/db/sudo-secretspec" +vault_realpath = "/private/var/db/sudo-secretspec" +declarations = "/usr/local/share/sudo-secretspec/secretspec.toml" +service_user = "_sudo_secretspec" +service_group = "_sudo_secretspec" diff --git a/tests/sudo_packaging/test_release.py b/tests/sudo_packaging/test_release.py new file mode 100644 index 000000000..c802d18fb --- /dev/null +++ b/tests/sudo_packaging/test_release.py @@ -0,0 +1,246 @@ +"""Focused tests for the downstream release helper; never touch the network.""" + +from __future__ import annotations + +import importlib.util +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +RELEASE_PY = ROOT / "packaging" / "release.py" + + +def load_release(): + spec = importlib.util.spec_from_file_location("sudo_secretspec_release", RELEASE_PY) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +@pytest.fixture +def release(): + return load_release() + + +def completed(argv, stdout="", returncode=0): + return subprocess.CompletedProcess(argv, returncode, stdout=stdout, stderr="") + + +def test_release_identity_is_pinned(release): + assert release.VERSION == "0.19.1-djbclark.1" + assert release.TAG == "v0.19.1-djbclark.1" + assert release.RELEASE_TITLE == "SecretSpec 0.19.1 — sudo-secretspec downstream 1" + release.validate_version(release.VERSION) + with pytest.raises(release.ReleaseError): + release.validate_version("0.19.1-djbclark.2") + + +def test_https_release_url_guard(release): + release.validate_release_url( + "https://github.com/djbclark/sudo-secretspec/archive/refs/tags/v0.19.1-djbclark.1.tar.gz" + ) + for url in ("http://github.com/x", "file:///tmp/x", "https://example.com/x"): + with pytest.raises(release.ReleaseError): + release.validate_release_url(url) + + +def test_formula_rewrite_is_exact(tmp_path: Path, release): + formula = tmp_path / "sudo-secretspec.rb" + formula.write_text( + ' url "https://github.com/djbclark/sudo-secretspec/archive/refs/tags/v0.0.0.tar.gz"\n' + f' sha256 "{"0" * 64}"\n', + encoding="utf-8", + ) + release.rewrite_formula(formula, release.VERSION, "a" * 64) + text = formula.read_text(encoding="utf-8") + assert f"tags/{release.TAG}.tar.gz" in text + assert f'sha256 "{"a" * 64}"' in text + + +def test_preflight_validates_branch_remotes_lineage_and_fork(monkeypatch, release): + calls = [] + + def fake_run(argv, **kwargs): + calls.append(argv) + key = tuple(argv) + outputs = { + ("git", "status", "--porcelain"): "", + ("git", "branch", "--show-current"): "sudo-main\n", + ( + "git", + "remote", + "get-url", + "origin", + ): "https://github.com/djbclark/sudo-secretspec.git\n", + ( + "git", + "remote", + "get-url", + "upstream", + ): "https://github.com/cachix/secretspec.git\n", + ("git", "rev-parse", "v0.19.1^{commit}"): "abc\n", + ("git", "merge-base", "--is-ancestor", "v0.19.1", "HEAD"): "", + ( + "git", + "show", + "v0.19.1:Cargo.toml", + ): '[workspace.package]\nversion = "0.19.1"\n', + ( + "gh", + "repo", + "view", + "djbclark/sudo-secretspec", + "--json", + "nameWithOwner,parent,defaultBranchRef", + ): json.dumps( + { + "nameWithOwner": "djbclark/sudo-secretspec", + "parent": {"nameWithOwner": "cachix/secretspec"}, + "defaultBranchRef": {"name": "sudo-main"}, + } + ), + } + return completed(argv, outputs.get(key, "")) + + monkeypatch.setattr(release, "run", fake_run) + release.preflight(allow_dirty=False) + assert ["git", "merge-base", "--is-ancestor", "v0.19.1", "HEAD"] in calls + + +def test_preflight_rejects_wrong_fork_parent(monkeypatch, release): + def fake_run(argv, **kwargs): + if argv[:4] == ["gh", "repo", "view", "djbclark/sudo-secretspec"]: + return completed( + argv, + json.dumps( + { + "nameWithOwner": "djbclark/sudo-secretspec", + "parent": None, + "defaultBranchRef": {"name": "sudo-main"}, + } + ), + ) + outputs = { + ("git", "status", "--porcelain"): "", + ("git", "branch", "--show-current"): "sudo-main\n", + ( + "git", + "remote", + "get-url", + "origin", + ): "https://github.com/djbclark/sudo-secretspec.git\n", + ( + "git", + "remote", + "get-url", + "upstream", + ): "https://github.com/cachix/secretspec.git\n", + ("git", "rev-parse", "v0.19.1^{commit}"): "abc\n", + ("git", "merge-base", "--is-ancestor", "v0.19.1", "HEAD"): "", + ( + "git", + "show", + "v0.19.1:Cargo.toml", + ): '[workspace.package]\nversion = "0.19.1"\n', + } + return completed(argv, outputs.get(tuple(argv), "")) + + monkeypatch.setattr(release, "run", fake_run) + with pytest.raises(release.ReleaseError, match="parent"): + release.preflight(allow_dirty=False) + + +def test_dry_run_lists_remote_actions_without_running(monkeypatch, release, capsys): + monkeypatch.setattr(release, "preflight", lambda **kwargs: None) + monkeypatch.setattr(release, "run_tests", lambda **kwargs: None) + assert release.main(["--dry-run", "--skip-tests"]) == 0 + output = capsys.readouterr().out + assert f"git tag -a {release.TAG}" in output + assert f"git push origin {release.TAG}" in output + assert "gh release create" in output + assert "Formula/sudo-secretspec.rb" in output + + +def test_verify_readback_checks_repo_tag_release_and_installed_version( + monkeypatch, release +): + calls = [] + + def fake_run(argv, **kwargs): + calls.append(argv) + if argv[:3] == ["gh", "repo", "view"]: + return completed( + argv, + json.dumps( + { + "nameWithOwner": release.FORK_REPO, + "parent": {"nameWithOwner": release.UPSTREAM_REPO}, + } + ), + ) + if argv[:3] == ["gh", "release", "view"]: + return completed( + argv, + json.dumps( + { + "tagName": release.TAG, + "name": release.RELEASE_TITLE, + "isDraft": False, + } + ), + ) + if argv[:3] == [ + "gh", + "api", + f"repos/{release.FORK_REPO}/git/ref/tags/{release.TAG}", + ]: + return completed(argv, json.dumps({"ref": f"refs/tags/{release.TAG}"})) + if argv[-1:] == ["--version"]: + return completed(argv, f"secretspec {release.VERSION}\n") + return completed(argv) + + monkeypatch.setattr(release, "run", fake_run) + release.verify_readback("/opt/homebrew/opt/sudo-secretspec") + assert any(argv[:3] == ["gh", "release", "view"] for argv in calls) + assert any(argv[-1:] == ["--version"] for argv in calls) + + +def test_interruption_cleanup_removes_only_created_tag_and_formula_change( + monkeypatch, release +): + calls = [] + monkeypatch.setattr( + release, "run", lambda argv, **kwargs: calls.append(argv) or completed(argv) + ) + state = release.CleanupState( + tag_created=True, tag_pushed=False, formula_changed=True + ) + release.cleanup_interrupted(state) + assert calls == [ + ["git", "tag", "-d", release.TAG], + [ + "git", + "restore", + "--staged", + "--worktree", + "--", + "packaging/homebrew/sudo-secretspec.rb", + ], + ] + + +def test_interruption_cleanup_never_deletes_pushed_tag(monkeypatch, release): + calls = [] + monkeypatch.setattr( + release, "run", lambda argv, **kwargs: calls.append(argv) or completed(argv) + ) + release.cleanup_interrupted( + release.CleanupState(tag_created=True, tag_pushed=True, formula_changed=False) + ) + assert calls == [] From 193d0e60dd90b1bc3c6d879249403960fbbf6d96 Mon Sep 17 00:00:00 2001 From: Daniel JB Clark Date: Thu, 13 Aug 2026 16:21:52 -0400 Subject: [PATCH 2/4] fix: harden adopt-existing dry-run validation Require successful service user/group lookups, metadata-only vault file checks via symlink_metadata, and /private/var/db realpath validation before reporting a successful dry-run. --- sudo-secretspec-cli/src/install.rs | 33 ++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/sudo-secretspec-cli/src/install.rs b/sudo-secretspec-cli/src/install.rs index b693422da..f6bc97256 100644 --- a/sudo-secretspec-cli/src/install.rs +++ b/sudo-secretspec-cli/src/install.rs @@ -299,24 +299,53 @@ pub fn run(req: InstallRequest) -> Result<(), InstallError> { if req.dry_run { if req.adopt_existing { // Metadata-only validation of existing identity/vault. - let _ = Command::new("/usr/bin/id") + let id_status = Command::new("/usr/bin/id") .arg(&req.service_user) .status() .map_err(|e| InstallError::Denied(e.to_string()))?; + if !id_status.success() { + return Err(InstallError::Denied(format!( + "adopted user missing: {}", + req.service_user + ))); + } + let group_status = Command::new("/usr/bin/dscl") + .args([".", "-read", &format!("/Groups/{}", req.service_group)]) + .status() + .map_err(|e| InstallError::Denied(e.to_string()))?; + if !group_status.success() { + return Err(InstallError::Denied(format!( + "adopted group missing: {}", + req.service_group + ))); + } if !req.vault.is_dir() || req.vault.is_symlink() { return Err(InstallError::Denied( "adopted vault missing or symlinked".into(), )); } + // Root-only metadata checks of vault contents (never open values). for runtime in ["secretspec.toml", ".env"] { let p = req.vault.join(runtime); - if !p.is_file() || p.is_symlink() { + let meta = fs::symlink_metadata(&p).map_err(|_| { + InstallError::Denied(format!( + "adopted runtime file missing or unreadable: {}", + p.display() + )) + })?; + if meta.file_type().is_symlink() || !meta.is_file() { return Err(InstallError::Denied(format!( "adopted runtime file missing or symlinked: {}", p.display() ))); } } + let vault_real = resolve_path(&req.vault); + if !vault_real.starts_with("/private/var/db/") { + return Err(InstallError::Denied( + "vault resolves outside /private/var/db".into(), + )); + } } else if Path::new(&req.vault).exists() || Command::new("/usr/bin/id") .arg(&req.service_user) From 127c80711febdd47ccfdc9824489e702fda84d99 Mon Sep 17 00:00:00 2001 From: Daniel JB Clark Date: Thu, 13 Aug 2026 16:49:02 -0400 Subject: [PATCH 3/4] fix: fail-closed audit and pin vault dotenv provider Require non-empty reasons, treat audit write failures as hard errors, report unknown outcomes when mutation restore fails, avoid rewriting adopted vault ownership, and force dotenv://$vault/.env so ambient cwd/.env cannot become the secret store. --- sudo-secretspec-cli/src/broker.rs | 86 ++++++++++++++++++++++-------- sudo-secretspec-cli/src/install.rs | 24 ++++++--- 2 files changed, 82 insertions(+), 28 deletions(-) diff --git a/sudo-secretspec-cli/src/broker.rs b/sudo-secretspec-cli/src/broker.rs index 4093811f4..fa8a6feb4 100644 --- a/sudo-secretspec-cli/src/broker.rs +++ b/sudo-secretspec-cli/src/broker.rs @@ -156,14 +156,21 @@ impl Mutation { )) } - fn restore(&self) { + fn restore(&self) -> bool { + let mut ok = true; for (dest, suffix) in [(&self.manifest, "toml"), (&self.dotenv, "env")] { let backup = self.rollback_path(suffix); if backup.is_file() { - let _ = std::fs::copy(&backup, dest); + if std::fs::copy(&backup, dest).is_err() { + ok = false; + continue; + } let _ = std::fs::remove_file(&backup); + } else { + ok = false; } } + ok } fn commit(&self) { @@ -192,8 +199,9 @@ fn resolve_client(raw: &str) -> ClientFamily { } fn reason_sha256(reason: &str) -> Option { + let reason = reason.trim(); if reason.is_empty() { - return Some(String::from(audit::ZERO_HASH)); + return None; } Some(format!("{:x}", Sha256::digest(reason.as_bytes()))) } @@ -220,8 +228,13 @@ fn run(broker: &Broker) -> Result<(), i32> { let cfg = load_config()?; require_boundary(&cfg)?; + if broker.reason.trim().is_empty() { + eprintln!("broker: --reason is required"); + return Err(2); + } + let client = resolve_client(&broker.client); - let reason_hash = reason_sha256(&broker.reason); + let reason_hash = reason_sha256(&broker.reason).ok_or(2)?; let transaction = uuid::Uuid::new_v4(); let names = broker .name @@ -230,8 +243,8 @@ fn run(broker: &Broker) -> Result<(), i32> { .unwrap_or_default(); let actor = actor_from_env(); - // Audit attempt - let _ = audit::append_event( + // Fail-closed audit attempt before any secret operation. + audit::append_event( &cfg.vault, AppendEventRequest { operation: broker.operation.clone(), @@ -239,13 +252,17 @@ fn run(broker: &Broker) -> Result<(), i32> { transaction, actor: actor.clone(), client, - reason_sha256: reason_hash.clone(), + reason_sha256: Some(reason_hash.clone()), command_basename: broker.command_basename.clone(), names: names.clone(), result_code: None, expected_uid: None, }, - ); + ) + .map_err(|e| { + eprintln!("broker: audit attempt failed: {e}"); + 2 + })?; // Begin mutation for write operations let mutation = if matches!( @@ -261,21 +278,25 @@ fn run(broker: &Broker) -> Result<(), i32> { let (rc, names) = execute(broker, &cfg); // Commit or restore mutation + let mut unknown = false; if let Some(m) = &mutation { if rc == 0 { m.commit(); - } else { - m.restore(); + } else if !m.restore() { + unknown = true; } } - // Terminal audit (unknown outcome if rc says success but we can't prove it) - let phase = if rc == 0 { + // Terminal audit must also succeed. + let phase = if unknown { + Outcome::Unknown + } else if rc == 0 { Outcome::Success } else { Outcome::Failure }; - let _ = audit::append_event( + let terminal_rc = if unknown { 125 } else { rc }; + audit::append_event( &cfg.vault, AppendEventRequest { operation: broker.operation.clone(), @@ -283,15 +304,23 @@ fn run(broker: &Broker) -> Result<(), i32> { transaction, actor, client, - reason_sha256: reason_hash, + reason_sha256: Some(reason_hash), command_basename: broker.command_basename.clone(), names, - result_code: Some(rc), + result_code: Some(terminal_rc), expected_uid: None, }, - ); + ) + .map_err(|e| { + eprintln!("broker: audit terminal failed: {e}"); + 2 + })?; - if rc != 0 { Err(rc as i32) } else { Ok(()) } + if terminal_rc != 0 { + Err(i32::from(terminal_rc)) + } else { + Ok(()) + } } op => { eprintln!("broker: unknown operation: {op}"); @@ -316,13 +345,28 @@ fn run_audit_verify(_broker: &Broker) -> Result<(), i32> { } fn execute(broker: &Broker, cfg: &Config) -> (u8, Vec) { + // Prevent ambient SecretSpec env from selecting another control plane. + for key in [ + "SECRETSPEC_PROVIDER", + "SECRETSPEC_FILE", + "SECRETSPEC_PROFILE", + "SECRETSPEC_SCOPE", + ] { + // SAFETY: single-threaded broker process; no concurrent env readers. + unsafe { + std::env::remove_var(key); + } + } + let manifest = cfg.vault.join("secretspec.toml"); + let dotenv = cfg.vault.join(".env"); + // Pin dotenv provider to the protected vault file — never cwd-relative `.env`. + // Absolute paths need the dotenv:/// form. + let provider = format!("dotenv://{}", dotenv.display()); let secrets = match secretspec::Secrets::load_from(&manifest) { Ok(mut s) => { - s.set_provider("dotenv"); - if !broker.reason.is_empty() { - s = s.with_reason(broker.reason.clone()); - } + s.set_provider(provider); + s = s.with_reason(broker.reason.clone()); s } Err(e) => { diff --git a/sudo-secretspec-cli/src/install.rs b/sudo-secretspec-cli/src/install.rs index f6bc97256..7580c5379 100644 --- a/sudo-secretspec-cli/src/install.rs +++ b/sudo-secretspec-cli/src/install.rs @@ -382,13 +382,23 @@ pub fn run(req: InstallRequest) -> Result<(), InstallError> { if req.vault.is_symlink() { return Err(InstallError::Denied("vault must not be a symlink".into())); } - let _ = Command::new("/usr/sbin/chown") - .arg(format!("{}:{}", req.service_user, req.service_group)) - .arg(&req.vault) - .status(); - let mut perms = fs::metadata(&req.vault)?.permissions(); - perms.set_mode(0o700); - fs::set_permissions(&req.vault, perms)?; + if req.adopt_existing { + // Never rewrite ownership of an adopted vault; only verify metadata. + let meta = fs::metadata(&req.vault)?; + if (meta.permissions().mode() & 0o777) != 0o700 { + return Err(InstallError::Denied( + "adopted vault must be mode 0700".into(), + )); + } + } else { + let _ = Command::new("/usr/sbin/chown") + .arg(format!("{}:{}", req.service_user, req.service_group)) + .arg(&req.vault) + .status(); + let mut perms = fs::metadata(&req.vault)?.permissions(); + perms.set_mode(0o700); + fs::set_permissions(&req.vault, perms)?; + } let vault_real = resolve_path(&req.vault); if !vault_real.starts_with("/private/var/db/") { From 9cbdcafad245dd617366d504a1f6ece9b1b5c7b3 Mon Sep 17 00:00:00 2001 From: Daniel JB Clark Date: Thu, 13 Aug 2026 19:26:03 -0400 Subject: [PATCH 4/4] feat: short install UX, doctor elevation, and fork docs Make install usable as `sudo-secretspec install` / `--adopt-existing` with auto-detected declarations and TTY prompts. Prefer system SQLite, chown the audit ledger to the vault owner, classify legacy vault clutter, and document the downstream companion for humans and later AIs. --- CHANGELOG.md | 3 + CLAUDE.md | 17 +- Cargo.lock | 1 - FORK-AI.md | 82 ++++++++ README.downstream.md | 50 +++++ sudo-secretspec-cli/Cargo.toml | 2 +- sudo-secretspec-cli/src/audit.rs | 24 ++- sudo-secretspec-cli/src/drift.rs | 6 + sudo-secretspec-cli/src/main.rs | 332 +++++++++++++++++++++++++------ sudo-secretspec/README.md | 77 +++++++ 10 files changed, 527 insertions(+), 67 deletions(-) create mode 100644 FORK-AI.md create mode 100644 README.downstream.md create mode 100644 sudo-secretspec/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index a51921722..4f6738b69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 binary with mediated credential operations, fail-closed SQLite audit, metadata-only doctor/drift checks, explicit install/adopt/rollback, and Homebrew packaging that never performs privileged installation side effects. +- Short install UX: `sudo-secretspec install` / `install --adopt-existing` + with declaration auto-detection and TTY prompts; long flags are overrides. +- Fork docs: `sudo-secretspec/README.md`, `README.downstream.md`, `FORK-AI.md`. ## [0.19.1] - 2026-08-11 diff --git a/CLAUDE.md b/CLAUDE.md index 9276acb98..cc1526c35 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,9 +15,22 @@ For an upcoming provider or feature: pages, README files, and generated documentation summaries with the minimum version, for example `(0.15+)`. -## Project Overview +## Downstream fork notes (`djbclark/sudo-secretspec`) -SecretSpec is a declarative secrets manager for development workflows written in Rust. It provides a CLI tool and Rust library for managing environment variables and secrets across different environments using multiple storage backends (keyring, dotenv, environment variables, OnePassword, LastPass). +This repository is a fork. In addition to upstream SecretSpec: + +- Companion crate: `sudo-secretspec-cli` (binary `sudo-secretspec`) +- Downstream docs: `sudo-secretspec/README.md`, `README.downstream.md` +- AI automation contract: `sudo-secretspec/AI-GUIDANCE.md` +- Fork-only agent notes/tricks: `FORK-AI.md` (do not upstream) +- Branches: `main` mirrors upstream; `sudo-main` is the downstream release line +- Version scheme: `0.19.1-djbclark.1` + +When changing the companion, update `CHANGELOG.md` Unreleased with a user-facing +entry and keep privileged install explicit (Homebrew must not silently edit +sudoers/users/vaults). + +Prefer system SQLite (not `rusqlite` bundled) on macOS; see `FORK-AI.md`. ## Build and Development Commands diff --git a/Cargo.lock b/Cargo.lock index ebb083fba..3434e4556 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3637,7 +3637,6 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c10584274047cb335c23d3e61bcef8e323adae7c5c8c760540f73610177fc3f" dependencies = [ - "cc", "pkg-config", "vcpkg", ] diff --git a/FORK-AI.md b/FORK-AI.md new file mode 100644 index 000000000..60f41202c --- /dev/null +++ b/FORK-AI.md @@ -0,0 +1,82 @@ +# Fork-only notes for AI agents (`djbclark/sudo-secretspec`) + +This file is **downstream-only**. Do not port it upstream to `cachix/secretspec`. + +## Layout that matters + +| Path | Purpose | +|---|---| +| `sudo-secretspec-cli/` | Rust companion binary/library (the product) | +| `sudo-secretspec/` | Guidance, config example, companion README | +| `packaging/` | Release script + Homebrew formula | +| `skills/sudo-secretspec/` | Distributable AI skill | +| `main` | upstream mirror | +| `sudo-main` | downstream default/release branch | + +## High-value lessons (save time) + +1. **Do not write complex shell for the boundary.** Runtime policy is Rust. +2. **Avoid `rusqlite` `bundled` on this Mac.** It can hang in `libsqlite3-sys` + build scripts. Prefer system SQLite: + ```bash + export PKG_CONFIG_PATH="/opt/homebrew/opt/sqlite/lib/pkgconfig:$PKG_CONFIG_PATH" + export LIBRARY_PATH="/opt/homebrew/opt/sqlite/lib:$LIBRARY_PATH" + export CPATH="/opt/homebrew/opt/sqlite/include:$CPATH" + ``` + and `rusqlite = { version = "0.31" }` (no `bundled`). +3. **Cargo registry extract cache can be incomplete** after interrupted builds. + Incomplete dirs under `~/.cargo/registry/src/index.crates.io-*` missing + `Cargo.toml` can be deleted when the matching `.crate` archive exists. +4. **Toolchain is pinned** by `rust-toolchain.toml` (currently `1.92.0`). Ensure + `PATH` includes `~/.cargo/bin`. +5. **macOS path aliases:** `/var` → `/private/var`, `/etc` → `/private/etc`. + Validate resolved protected chains; accept public spellings. +6. **Dotenv provider must be pinned** to the vault file: + `dotenv:///var/db/.../.env` — never bare `dotenv` (cwd-relative). +7. **Audit must fail closed.** Do not ignore `append_event` errors. +8. **Public client elevates with:** + - lifecycle: `sudo -n /usr/local/libexec/sudo-secretspec __broker ...` + - install/rollback: interactive `sudo` (Touch ID) + - doctor: prefer `sudo -n` libexec elevation +9. **Adopt-existing must not chown/chmod the vault.** Only verify metadata. +10. **Install UX goal:** short forms (`install`, `install --adopt-existing`) with + auto-detection/prompts; long flags are overrides only. + +## Useful commands + +```bash +# focused tests +cargo test -p sudo-secretspec-cli + +# release binary +cargo build -p sudo-secretspec-cli --release +cp target/release/sudo-secretspec ~/bin/sudo-secretspec + +# live smoke after install +sudo -n /usr/local/libexec/sudo-secretspec doctor +sudo-secretspec check --reason "smoke" +``` + +## Delivery conventions + +- PRs target `sudo-main` on `djbclark/sudo-secretspec` (not upstream). +- Never open upstream issues/PRs without explicit permission. +- Keep `CHANGELOG.md` Unreleased entries user-facing. +- After privileged install, verify paths under `/usr/local` and vault ownership + without reading secret values. + +## Known residual findings on this host + +After adopt-existing install of the stayturgid vault, doctor may report: + +- `LEGACY_VAULT_CLUTTER` / previously `UNEXPECTED_RUNTIME_ENTRY` for `.local` / + `.ansible` under the vault (non-secret tool state; safe to clean later) +- audit ledger ownership should be `_secretspec:staff` (fixed in current tree by + chown-after-open when broker is root) + +## Related human/AI guidance + +- `sudo-secretspec/AI-GUIDANCE.md` +- `skills/sudo-secretspec/SKILL.md` +- `packaging/README.md` +- Local reusable Rust agent notes: `~/src/agent-guidance/rust/AGENTS.md` diff --git a/README.downstream.md b/README.downstream.md new file mode 100644 index 000000000..762060452 --- /dev/null +++ b/README.downstream.md @@ -0,0 +1,50 @@ +# djbclark/sudo-secretspec + +Downstream fork of [cachix/secretspec](https://github.com/cachix/secretspec) +with an optional privilege-separated companion for autonomous local AI/operator +use on macOS. + +## Upstream SecretSpec + +See [`secretspec/README.md`](secretspec/README.md) for the upstream product, +providers, and quick start. + +## Downstream companion: `sudo-secretspec` + +This fork adds **`sudo-secretspec`**: a single Rust binary that mediates all +credential CRUD/use through a root-owned broker, fail-closed value-free audit, +and metadata-only doctor checks. + +Full companion docs: [`sudo-secretspec/README.md`](sudo-secretspec/README.md) + +AI automation rules: [`sudo-secretspec/AI-GUIDANCE.md`](sudo-secretspec/AI-GUIDANCE.md) + +Fork development notes for AIs: [`FORK-AI.md`](FORK-AI.md) + +### Short install / use + +```bash +# after packaging or local release build +sudo-secretspec install # prompts / auto-detects when possible +sudo-secretspec install --adopt-existing + +sudo-secretspec check --reason "smoke" +sudo-secretspec run --reason "start app" -- your-command +sudo-secretspec doctor +``` + +### Branch policy + +| Branch | Role | +|---|---| +| `main` | upstream mirror | +| `sudo-main` | downstream release line (default) | +| `feature/*` | work targeting `sudo-main` | + +Downstream version scheme: `0.19.1-djbclark.1` (`v0.19.1-djbclark.1`). + +### Packaging + +See [`packaging/README.md`](packaging/README.md). Homebrew installs unprivileged +files only; privileged boundary creation is always an explicit +`sudo-secretspec install`. diff --git a/sudo-secretspec-cli/Cargo.toml b/sudo-secretspec-cli/Cargo.toml index 177ec6e41..7a766e1ce 100644 --- a/sudo-secretspec-cli/Cargo.toml +++ b/sudo-secretspec-cli/Cargo.toml @@ -14,7 +14,7 @@ path = "src/main.rs" [dependencies] clap.workspace = true -rusqlite = { version = "0.31", features = ["bundled"] } +rusqlite = { version = "0.31" } serde = { workspace = true, features = ["derive"] } serde_json.workspace = true secretspec = { path = "../secretspec", version = "0.19.1-djbclark.1", default-features = false } diff --git a/sudo-secretspec-cli/src/audit.rs b/sudo-secretspec-cli/src/audit.rs index 5ded2f55b..8c52f2298 100644 --- a/sudo-secretspec-cli/src/audit.rs +++ b/sudo-secretspec-cli/src/audit.rs @@ -338,7 +338,7 @@ fn open_connection(directory: &Path, expected_uid: Option) -> Result) -> Result Report { Some(&path), "pending rollback artifact requires operator review", )); + } else if matches!(name.as_ref(), ".local" | ".ansible" | ".cache") { + findings.push(finding( + "LEGACY_VAULT_CLUTTER", + Some(&path), + "non-secret tool state under the vault; safe to remove after review", + )); } else if !allowed.iter().any(|a| *a == name) { findings.push(finding( "UNEXPECTED_RUNTIME_ENTRY", diff --git a/sudo-secretspec-cli/src/main.rs b/sudo-secretspec-cli/src/main.rs index 9b48512f6..0f3c2a813 100644 --- a/sudo-secretspec-cli/src/main.rs +++ b/sudo-secretspec-cli/src/main.rs @@ -1,4 +1,5 @@ use std::ffi::OsString; +use std::io::{self, Write}; use std::os::unix::process::CommandExt; use std::path::PathBuf; use std::process::Command; @@ -52,11 +53,18 @@ enum Cmd { #[arg(last = true, required = true)] command: Vec, }, + /// Install or adopt the privileged boundary. + /// + /// Typical short form: + /// sudo-secretspec install + /// sudo-secretspec install --adopt-existing Install { + /// Declaration TOML. Optional: auto-detected or prompted. #[arg(long)] - declarations: PathBuf, + declarations: Option, #[arg(long)] dry_run: bool, + /// Adopt an existing vault/service identity instead of creating one. #[arg(long)] adopt_existing: bool, #[arg(long)] @@ -67,6 +75,9 @@ enum Cmd { service_group: Option, #[arg(long)] operator: Option, + /// Never prompt; fail if required values cannot be defaulted. + #[arg(long)] + non_interactive: bool, }, Doctor { #[arg(long)] @@ -102,64 +113,17 @@ fn main() { service_user, service_group, operator, - } => { - let mut req = sudo_secretspec_cli::install::InstallRequest::from_cli( - declarations, - dry_run, - adopt_existing, - ); - if let Some(v) = vault { - req.vault = v; - } - if let Some(u) = service_user { - req.service_user = u; - } - if let Some(g) = service_group { - req.service_group = g; - } - if let Some(o) = operator { - req.operator = o; - } - // Install itself needs interactive sudo/Touch ID, not NOPASSWD -n. - if unsafe { libc::geteuid() } != 0 { - let status = Command::new("sudo") - .arg(self_exe()) - .arg("install") - .arg("--declarations") - .arg(&req.declarations) - .args(if req.dry_run { - vec!["--dry-run"] - } else { - vec![] - }) - .args(if req.adopt_existing { - vec!["--adopt-existing"] - } else { - vec![] - }) - .arg("--vault") - .arg(&req.vault) - .arg("--service-user") - .arg(&req.service_user) - .arg("--service-group") - .arg(&req.service_group) - .arg("--operator") - .arg(&req.operator) - .status(); - match status { - Ok(s) if s.success() => return, - Ok(s) => std::process::exit(s.code().unwrap_or(1)), - Err(e) => { - eprintln!("cannot elevate install: {e}"); - std::process::exit(2); - } - } - } - if let Err(e) = sudo_secretspec_cli::install::run(req) { - eprintln!("install denied: {e}"); - std::process::exit(2); - } - } + non_interactive, + } => run_install( + declarations, + dry_run, + adopt_existing, + vault, + service_user, + service_group, + operator, + non_interactive, + ), Cmd::Doctor { json, config } => doctor(json, config), Cmd::Rollback { snapshot } => { if unsafe { libc::geteuid() } != 0 { @@ -203,6 +167,235 @@ fn privileged_broker() -> PathBuf { } } +fn is_tty() -> bool { + unsafe { libc::isatty(libc::STDIN_FILENO) == 1 } +} + +fn prompt_line(label: &str, default: Option<&str>) -> Option { + if !is_tty() { + return default.map(str::to_string); + } + let mut stdout = io::stdout(); + match default { + Some(d) if !d.is_empty() => { + let _ = write!(stdout, "{label} [{d}]: "); + } + _ => { + let _ = write!(stdout, "{label}: "); + } + } + let _ = stdout.flush(); + let mut line = String::new(); + if io::stdin().read_line(&mut line).is_err() { + return default.map(str::to_string); + } + let trimmed = line.trim(); + if trimmed.is_empty() { + default.map(str::to_string) + } else { + Some(trimmed.to_string()) + } +} + +fn prompt_yes_no(label: &str, default_yes: bool) -> bool { + if !is_tty() { + return default_yes; + } + let def = if default_yes { "Y/n" } else { "y/N" }; + let mut stdout = io::stdout(); + let _ = write!(stdout, "{label} [{def}]: "); + let _ = stdout.flush(); + let mut line = String::new(); + if io::stdin().read_line(&mut line).is_err() { + return default_yes; + } + match line.trim().to_ascii_lowercase().as_str() { + "" => default_yes, + "y" | "yes" => true, + "n" | "no" => false, + _ => default_yes, + } +} + +fn declaration_candidates() -> Vec { + let mut out = Vec::new(); + if let Ok(env) = std::env::var("SUDO_SECRETSPEC_DECLARATIONS") { + out.push(PathBuf::from(env)); + } + if let Ok(home) = std::env::var("HOME") { + out.push(PathBuf::from(home).join("ops/site-private/secretspec.toml.example")); + } + out.push(PathBuf::from( + "/usr/local/share/sudo-secretspec/secretspec.toml", + )); + // Common worktree layout relative to cwd. + out.push(PathBuf::from("site-private/secretspec.toml.example")); + out.push(PathBuf::from("../site-private/secretspec.toml.example")); + out +} + +fn resolve_declarations( + explicit: Option, + non_interactive: bool, +) -> Result { + if let Some(path) = explicit { + if path.is_file() && !path.is_symlink() { + return Ok(path); + } + return Err(format!( + "declarations not found or not a regular file: {}", + path.display() + )); + } + for cand in declaration_candidates() { + if cand.is_file() && !cand.is_symlink() { + if !non_interactive && is_tty() { + if prompt_yes_no(&format!("Use declarations at {}?", cand.display()), true) { + return Ok(cand); + } + } else { + return Ok(cand); + } + } + } + if non_interactive || !is_tty() { + return Err( + "declarations required; pass --declarations PATH or set SUDO_SECRETSPEC_DECLARATIONS" + .into(), + ); + } + let typed = prompt_line("Path to declarations TOML", None) + .ok_or_else(|| "declarations path required".to_string())?; + let path = PathBuf::from(typed); + if path.is_file() && !path.is_symlink() { + Ok(path) + } else { + Err(format!("declarations not found: {}", path.display())) + } +} + +fn detect_existing_vault() -> Option<(PathBuf, String, String)> { + // Prefer the already-deployed local vault if present. + let candidates = [ + PathBuf::from("/var/db/stayturgid-secrets"), + PathBuf::from("/var/db/sudo-secretspec"), + ]; + for vault in candidates { + if vault.is_dir() && !vault.is_symlink() { + // Ownership can only be fully trusted after elevation; use names we know. + if vault.ends_with("stayturgid-secrets") { + return Some((vault, "_secretspec".into(), "staff".into())); + } + return Some((vault, "_sudo_secretspec".into(), "_sudo_secretspec".into())); + } + } + None +} + +fn run_install( + declarations: Option, + dry_run: bool, + adopt_existing: bool, + vault: Option, + service_user: Option, + service_group: Option, + operator: Option, + non_interactive: bool, +) { + let declarations = match resolve_declarations(declarations, non_interactive) { + Ok(p) => p, + Err(e) => { + eprintln!("install denied: {e}"); + std::process::exit(2); + } + }; + + let mut req = sudo_secretspec_cli::install::InstallRequest::from_cli( + declarations, + dry_run, + adopt_existing, + ); + + if let Some(existing) = detect_existing_vault() { + if vault.is_none() { + if adopt_existing + || (!non_interactive + && is_tty() + && prompt_yes_no( + &format!( + "Found existing vault at {}. Adopt it?", + existing.0.display() + ), + true, + )) + { + req.adopt_existing = true; + req.vault = existing.0; + req.service_user = existing.1; + req.service_group = existing.2; + } + } + } + + if let Some(v) = vault { + req.vault = v; + } + if let Some(u) = service_user { + req.service_user = u; + } + if let Some(g) = service_group { + req.service_group = g; + } + if let Some(o) = operator { + req.operator = o; + } else if !non_interactive && is_tty() { + if let Some(o) = prompt_line("Operator username for sudoers", Some(&req.operator)) { + req.operator = o; + } + } + + // Install itself needs interactive sudo/Touch ID, not NOPASSWD -n. + if unsafe { libc::geteuid() } != 0 { + let status = Command::new("sudo") + .arg(self_exe()) + .arg("install") + .arg("--declarations") + .arg(&req.declarations) + .args(if req.dry_run { + vec!["--dry-run"] + } else { + vec![] + }) + .args(if req.adopt_existing { + vec!["--adopt-existing"] + } else { + vec![] + }) + .arg("--vault") + .arg(&req.vault) + .arg("--service-user") + .arg(&req.service_user) + .arg("--service-group") + .arg(&req.service_group) + .arg("--operator") + .arg(&req.operator) + .arg("--non-interactive") + .status(); + match status { + Ok(s) if s.success() => return, + Ok(s) => std::process::exit(s.code().unwrap_or(1)), + Err(e) => { + eprintln!("cannot elevate install: {e}"); + std::process::exit(2); + } + } + } + if let Err(e) = sudo_secretspec_cli::install::run(req) { + eprintln!("install denied: {e}"); + std::process::exit(2); + } +} + fn lifecycle(op: &str, name: &str, reason: &str) { let mut cmd = Command::new("sudo"); cmd.arg("-n") @@ -301,6 +494,27 @@ fn run_target(reason: &str, command: &[OsString]) { } fn doctor(json: bool, config: Option) { + // Privileged checks (sudoers/vault) need root. Prefer NOPASSWD libexec. + if unsafe { libc::geteuid() } != 0 { + let broker = privileged_broker(); + let mut cmd = Command::new("sudo"); + cmd.arg("-n").arg(&broker).arg("doctor"); + if json { + cmd.arg("--json"); + } + if let Some(cfg) = &config { + cmd.arg("--config").arg(cfg); + } + match cmd.status() { + Ok(s) if s.success() => return, + Ok(s) => std::process::exit(s.code().unwrap_or(1)), + Err(e) => { + eprintln!("cannot elevate doctor via {}: {e}", broker.display()); + // Fall through to unprivileged best-effort. + } + } + } + let config = config.unwrap_or_else(|| PathBuf::from("/usr/local/etc/sudo-secretspec.toml")); let layout = match sudo_secretspec_cli::load_config(&config) { Ok(l) => l, diff --git a/sudo-secretspec/README.md b/sudo-secretspec/README.md new file mode 100644 index 000000000..8133b0229 --- /dev/null +++ b/sudo-secretspec/README.md @@ -0,0 +1,77 @@ +# sudo-secretspec (downstream companion) + +Privilege-separated SecretSpec companion for this fork +(`djbclark/sudo-secretspec`). + +Upstream SecretSpec remains the declaration/provider engine. This companion adds +a single mediated control plane for autonomous local AI/operator use on macOS. + +## Quick start (short forms) + +After the binary is available (`brew install` or local build): + +```bash +# Preferred short install forms +sudo-secretspec install +sudo-secretspec install --adopt-existing + +# Day-to-day use +sudo-secretspec check --reason "smoke" +sudo-secretspec run --reason "start gateway" -- your-command +sudo-secretspec doctor +``` + +`install` auto-detects common declaration paths and existing vaults, and +prompts on a TTY when needed. Use flags only to override defaults: + +```bash +sudo-secretspec install \ + --declarations /path/to/secretspec.toml.example \ + --vault /var/db/stayturgid-secrets \ + --service-user _secretspec \ + --service-group staff \ + --operator "$USER" \ + --adopt-existing +``` + +## What gets installed + +| Path | Role | +|---|---| +| `/usr/local/bin/sudo-secretspec` | public client | +| `/usr/local/libexec/sudo-secretspec` | privileged broker (same binary) | +| `/usr/local/etc/sudo-secretspec.toml` | protected config | +| `/etc/sudoers.d/sudo-secretspec` | NOPASSWD broker policy for operator | +| `/usr/local/share/sudo-secretspec/` | declarations pin, guidance, manifest | +| vault (e.g. `/var/db/stayturgid-secrets`) | `_secretspec`-owned runtime store | + +Homebrew packaging installs files only. Privileged boundary creation always +requires an explicit `sudo-secretspec install` (Touch ID/sudo). + +## Security model + +- Singular mediated path for credential CRUD/use +- Fail-closed value-free SQLite audit (`broker-audit.sqlite3`) +- No caller-selected manifests/providers/profiles +- Doctor/drift is metadata-only and never repairs +- Rollback snapshots restore installed artifacts, not vault secret values + +See `AI-GUIDANCE.md` for AI/automation rules. + +## Develop + +Workspace member: `sudo-secretspec-cli`. + +```bash +export PKG_CONFIG_PATH="/opt/homebrew/opt/sqlite/lib/pkgconfig:$PKG_CONFIG_PATH" +cargo test -p sudo-secretspec-cli +cargo build -p sudo-secretspec-cli --release +``` + +Branch policy for this fork: + +- `main` mirrors upstream +- `sudo-main` is the downstream release line +- feature work PRs into `sudo-main` + +Current downstream version: `0.19.1-djbclark.1`.